Symfony notes

Create a project

Use the Symfony CLI tool:

symfony new project_name --version=7.4 --webapp

Will create a folder containing the Symfony application, which you can open in your favorite editor.

Launch development server

Use the Symfony CLI tool:

symfony serve --no-tls

Launches development server, defaults to port 8000. We can then access the application via the browser: http://localhost:8000

Create a page (controller)

There are two possibilities:

  • Use the MakerBundle and its php bin/console make:controller command to create a controller class
  • In an existing controller class, create a new method that will become a controller with a Route attribute

Configure a route (page)

In a method within a controller class, use the Route attribute:

#[Route('/my-url', name: 'my_route_name')]
public function myController(): Response
{}

Edit a Twig template

Twig is a template engine. All templates are located in templates/.

The appearance of our pages is built in templates (site layout).

Usually, we have a root template in templates/base.html.twig

Install Bootstrap/Tailwind

  • Bootstrap : we can use a command from the console:
php bin/console importmap:require bootstrap
composer require symfonycasts/tailwind-bundle

Configure access to the database

Always in the .env.local file, define an environment variable DATABASE_URL.

Create the database

php bin/console doctrine:database:create

Create a table (entity)

We will use the MakerBundle and the following command:

php bin/console make:entity

Create a migration

Again, a command from the MakerBundle:

php bin/console make:migration

Execute a migration

php bin/console d:m:m

Install the fixtures component

composer require --dev orm-fixtures
  • orm-fixtures is a Symfony Flex alias
  • When installing this component, a Symfony Flex recipe is automatically executed to pre-configure the component: a PHP class is created in src/DataFixtures

Edit fixtures

Fixtures are located in the App\DataFixtures\AppFixtures class, so if we follow the PSR-4 logic, we will find fixtures in the src/DataFixtures/AppFixtures.php file.

Fixtures will be written in the load method.

Execute fixtures

Once fixtures are written, we can load the data into the database with the following command:

php bin/console d:f:l

Create a relation between two entities

We will use the MakerBundle, and create a property pointing at the target entity.

Example :

  • We edit the Article entity
  • We want to make a link to Category, so that an article has a category
  • We will therefore create a category property
  • The type of this property will be ManyToOne

About the type, split the different types of the relation around the To keyword:

  • Many / To / One
  • One / To / Many
  • etc…

Then, we take the entity name we are editing, and insert it to the left of To. For example:

  • Many Articles / To / One

Finally, we insert the target entity to the right of To :

  • Many Articles / To / One Category