In Symfony 2 Development, a bundle is a directory that has a structure that is well defined and it can host classes, controllers, web resources and much more. Bundles are very flexible. But it is essential that you are well informed of the best practices to use and distribute them.
Here are some of the best practices while you structure bundles in Symfony 2
A Bundle is basically a PHP namespace. It must follow the interoperability standards for PHP 5.3 name spaces and class names.
A typical bundle name starts with a vendor segment, a zero or some more category segments and a bundle suffix. A bundle class name has some specific rules to add to it. It allows only alphanumeric charecters, underscores are allowed, CamelCased names, descriptive and short name, prefix should be concatenation of vendor name, suffix with the name bundle.
Take a look at this example for helloBundle
XXX/... HelloBundle/ HelloBundle.php Controller/ Resources/ meta/ LICENSE config/ doc/ index.rst translations/ views/ public/ Tests/
The XXX directory(ies) shows the namespace structure
It’s mandatory to have the following files:
- Resources/meta/LICENSE: The full license for the code;
- Resources/doc/index.rst: The root file for the Bundle documentation.
Sub directories depth should be kept minimal. The Bundle directory should be read only. Just in case you need to create temporary files, you can store them under cache/ or log/ directories.
All classes and files should follow the Symfony 2 coding standards. A Bundle has a name space hierarchy. For example: a HelloController controller is stored in Bundle/HelloBundle/Controller/HelloController.php and the fully qualified class name is Bundle\HelloBundle\Controller\HelloController.
A Symfony 2 bundle comes with a test suite written with PHPUnit and stored under the Tests/ directory.
Following are the best practices for tests:
- must be executable with a simple phpunit
- should be used to test response output.
- Should test 95% of the code base.
A controller must not extend the controller base class. Instead, they can implement ContainerAwareInterface or extend ContainerAware .
If a bundle provides routes, they must be prefixed with bundle alias.
Twig must be used if a bundle provides templates. The main layout must not be provided by a bundle unless it’s a fully working application.
Message translations for a bundle must be defines in XLIFF format. Domain name should be after the bundle.
Symfony 2 built in mechanisms provide flexibility for configuration. For simple configuration, the default parameters entry will suffice.
Parameters are key value pairs (any valid PHP value). The parameter starts with the bundle alias. Rest of the parameter uses a period to separate different parts.
Symfony 2 allows the end user can provide values in any configuration file:
• YAML 1 2 3 # app/config/config.yml parameters: acme_hello.email.from: firstname.lastname@example.org