05 June 2024
What are Bundles in Symfony?
One of the strengths of Symfony is its scalability. It allows segmenting the code into bundles so that the project can continue to grow. With a Bundle, we encapsulate one or several functionalities.
What is a bundle?
A Bundle is a package that can contain anything:
- Programming code
- Configuration files
- Templates
- CSS, JavaScript
The content of the bundle forms a sub-application within our application (essentially it is a plugin). For example, you can create a blog in a bundle, and it will contain all the necessary files to run it (controllers, templates, css files, js files, …)
Our application in Symfony can be entirely contained in one bundle or in several.
What is the structure of Symfony?
Before explaining how to create a Bundle, we must know the structure of a Symfony project, which is composed of the following directories:
- app/: contains the application configuration.
- src/: here is where all the PHP code of the application is located. By default, this is the directory where we will have the Bundles.
- vendor/: by convention, this is where all third-party libraries are stored. Initially, it is a directory that we do not need to touch.
- web/: this is the web root directory and contains all the files that can be publicly accessed.
How to create a Bundle in Symfony?
Suppose we want to create a bundle to manage users. We will create it in the directory src/Daw/UserBundle (the namespace must always end with Bundle). Therefore, from the terminal located in the directory of our project, we write the following command:
$ php app/console generate:bundle --namespace=Daw/UserBundle
It will ask us a series of questions that we will leave by default, except for the configuration format where we will indicate “yml”.
With this, the Bundle will be registered in our application. Inside src/Daw/UserBundle we will have the Bundle we just created.
To verify that it has been created correctly, we can follow two steps:
- Verify the file app/AppKernel: where a new position of the array $bundles will have been generated.
- Verify config/routing.yml: where an import of the routing.yml file of our bundle will be made.
Share