Create and Run Symfony Project
What is Symfony?
Symfony is an open-source PHP web framework created by SensioLabs, aimed at providing developers with an efficient, flexible, and powerful set of tools to build modern web applications. Symfony offers a wealth of features such as routing, templating engine, form processing, authentication, etc., simplifying common web development tasks.
Key Features and Advantages of Symfony
- Modular Design: Symfony uses a modular design, allowing developers to select and use components as needed.
- High Performance: With an optimized architecture and caching mechanism, Symfony delivers excellent performance.
- Strong Community Support: A large developer community and rich ecosystem.
- Flexibility: Can integrate various third-party libraries and extensions, suitable for projects of all sizes.
- Good Documentation: Provides comprehensive documentation and tutorials, helping developers to get started quickly.
Symfony can help developers quickly build high-quality web applications and APIs, suitable for projects ranging from small applications to large enterprise systems.
Create and Run Symfony Project using ServBay
In this article, we will use the PHP environment provided by ServBay to create and run a Symfony project. We will utilize the 'Host' feature of ServBay to set up the web server and achieve project access through simple configuration.
Note: If you were an NGINX or Apache user
ServBay uses Caddy as the default web server. For users migrating from NGINX and Apache to ServBay, there are some key changes to note:
Caddy Configuration
ServBay has built-in Caddy with default configuration optimized and debugged. Developers only need to manage the sites via the 'Host' feature of ServBay without manually modifying the Caddy configuration files.
Rewrite Rules and .htaccess
In NGINX and Apache, developers often need to write Rewrite rules and .htaccess files to handle URL rewriting and other configurations themselves. However, ServBay is pre-configured with Caddy rules, so developers generally do not need to write these rules themselves unless there are specific needs.
Learn More
For more information, see Rewrite and htaccess, How to Migrate Apache Website to ServBay, How to Migrate NGINX Website to ServBay.
Create Symfony Project
TIP
ServBay recommends developers place websites in the /Applications/ServBay/www
directory for easy management.
Install Composer
ServBay comes with Composer pre-installed, so there's no need for separate installation.
Create Symfony Project
Use Composer to create a new Symfony project:
bashcd /Applications/ServBay/www mkdir servbay-symfony-app cd servbay-symfony-app composer create-project symfony/website-skeleton .
1
2
3
4Enter the Project Directory
Enter the newly created Symfony project directory:
bashcd /Applications/ServBay/www/servbay-symfony-app
1
Initial Configuration
Configure Environment Variables
Configure database connection information and other environment variables in the
.env
file. Ensure the following configurations are set correctly:APP_ENV=dev APP_SECRET=your_secret_key DATABASE_URL=mysql://root:[email protected]:3306/servbay_symfony_app
1
2
3
Configure Web Server
Use ServBay's 'Host' feature to access the Symfony project via a web server. In ServBay's 'Host' settings, add a new host:
- Name:
My First Symfony Dev Site
- Domain:
servbay-symfony-test.local
- Website Type:
PHP
- PHP Version: Choose
8.3
- Web Root Directory:
/Applications/ServBay/www/servbay-symfony-app/public
For detailed setup steps, please refer to Adding the First Website.
Add Sample Code
Add the following code in the config/routes.yaml
file to output "Hello ServBay!":
index:
path: /
controller: App\Controller\DefaultController::index
2
3
Add the following code in the src/Controller/DefaultController.php
file:
namespace App\Controller;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
class DefaultController
{
/**
* @Route("/", name="index")
*/
public function index(): Response
{
return new Response('Hello ServBay!');
}
}
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Access the Website
Open a browser and visit https://servbay-symfony-test.local
, you will see the page output Hello ServBay!
.
NoSQL Database Example
Memcached Example
Install Memcached Extension
Memcached extension is pre-installed in ServBay, no additional installation is required.
Configure Memcached
Configure Memcached connection information in the
.env
file:CACHE_DRIVER=memcached MEMCACHED_HOST=127.0.0.1
1
2Add the following code in the
config/routes.yaml
file:
memcached:
path: /memcached
controller: App\Controller\DefaultController::memcached
2
3
Use Memcached
Use cache in the Controller:
phpuse Symfony\Component\Cache\Adapter\MemcachedAdapter; class DefaultController { /** * @Route("/memcached", name="memcached") */ public function memcached(): Response { $client = MemcachedAdapter::createConnection('memcached://127.0.0.1:11211'); $cache = new MemcachedAdapter($client); $cacheItem = $cache->getItem('my_cache_key'); if (!$cacheItem->isHit()) { $cacheItem->set('Hello Memcached!'); $cache->save($cacheItem); } return new Response($cacheItem->get()); } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21Open your browser and visit
https://servbay-symfony-test.local/memcached
Redis Example
Install Redis Extension
Redis extension is pre-installed in ServBay, no additional installation is required.
Configure Redis
Configure Redis connection information in the
.env
file:REDIS_URL=redis://127.0.0.1:6379
1Add the following code in the
config/routes.yaml
file:
redis:
path: /redis
controller: App\Controller\DefaultController::redis
2
3
Use Redis
Use cache in the Controller:
phpuse Symfony\Component\Cache\Adapter\RedisAdapter; class DefaultController { /** * @Route("/redis", name="redis") */ public function redis(): Response { $redisConnection = RedisAdapter::createConnection('redis://127.0.0.1:6379'); $cache = new RedisAdapter($redisConnection); $cacheItem = $cache->getItem('my_cache_key'); if (!$cacheItem->isHit()) { $cacheItem->set('Hello Redis!'); $cache->save($cacheItem); } return new Response($cacheItem->get()); } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21Open your browser and visit
https://servbay-symfony-test.local/redis
Relational Database Example
Create Database Schema and Migrations
Create Migration File
Use Symfony's Maker Bundle to create a migration file:
bashphp bin/console make:migration
1Edit Migration File
Find the newly created migration file in the
src/Migrations
directory and edit it to define the database table structure:phppublic function up(Schema $schema): void { $this->addSql('CREATE TABLE users (id INT AUTO_INCREMENT NOT NULL, name VARCHAR(255) NOT NULL, email VARCHAR(255) NOT NULL UNIQUE, PRIMARY KEY(id))'); }
1
2
3
4Run Migration
Use Symfony commands to run the migration and create the database table:
bashphp bin/console doctrine:migrations:migrate
1
MySQL Example
Configure MySQL
Configure MySQL connection information in the
.env
file:DATABASE_URL=mysql://root:[email protected]:3306/servbay_symfony_app
1Add the following code in the
config/routes.yaml
file:
mysql_add:
path: /mysql-add
controller: App\Controller\DefaultController::mysqlAdd
mysql_get:
path: /mysql
controller: App\Controller\DefaultController::mysql
2
3
4
5
6
Write User Data
Write user data in the Controller:
phpuse Doctrine\ORM\EntityManagerInterface; use App\Entity\User; use Symfony\Component\Routing\Annotation\Route; class DefaultController { private $entityManager; public function __construct(EntityManagerInterface $entityManager) { $this->entityManager = $entityManager; } /** * @Route("/mysql-add", name="mysql_add") */ public function mysqlAdd(): Response { $user = new User(); $user->setName('ServBay'); $user->setEmail('[email protected]'); $this->entityManager->persist($user); $this->entityManager->flush(); return new Response('User added'); } /** * @Route("/mysql", name="mysql") */ public function mysql(): Response { $users = $this->entityManager->getRepository(User::class)->findAll(); return new Response(json_encode($users)); } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37Open your browser and visit
https://servbay-symfony-test.local/mysql-add
andhttps://servbay-symfony-test.local/mysql
PostgreSQL Example
Configure PostgreSQL
Configure PostgreSQL connection information in the
.env
file:DATABASE_URL=pgsql://root:[email protected]:5432/servbay_symfony_app
1Add the following code in the
config/routes.yaml
file:
pgsql_add:
path: /pgsql-add
controller: App\Controller\DefaultController::pgsqlAdd
pgsql_get:
path: /pgsql
controller: App\Controller\DefaultController::pgsql
2
3
4
5
6
Write User Data
Write user data in the Controller:
phpuse Doctrine\ORM\EntityManagerInterface; use App\Entity\User; use Symfony\Component\Routing\Annotation\Route; class DefaultController { private $entityManager; public function __construct(EntityManagerInterface $entityManager) { $this->entityManager = $entityManager; } /** * @Route("/pgsql-add", name="pgsql_add") */ public function pgsqlAdd(): Response { $user = new User(); $user->setName('ServBay'); $user->setEmail('[email protected]'); $this->entityManager->persist($user); $this->entityManager->flush(); return new Response('User added'); } /** * @Route("/pgsql", name="pgsql") */ public function pgsql(): Response { $users = $this->entityManager->getRepository(User::class)->findAll(); return new Response(json_encode($users)); } }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37Open your browser and visit
https://servbay-symfony-test.local/pgsql-add
andhttps://servbay-symfony-test.local/pgsql
By following the above steps, you have successfully created and run a Symfony project, used ServBay's features to manage and access your project, and connected various databases and invoked data.