Most of the popular frameworks and platforms support some form of modules, plugins, extensions or bundles. For most of the time, the difference really lies just in the naming, while the concept of extensibility and modularity is the same. With Symfony, these modular blocks are called bundles.
Bundles are a first-class citizen in Symfony, as they support all of the operations available to other components. Everything in Symfony is a bundle, even the core framework. Bundles enable us to build modularized applications, whereas the entire code for a given feature is contained within a single directory.
A single bundle holds all its PHP files, templates, style sheets, JavaScript files, tests, and anything else in one root directory.
When we first setup our test app, it created an AppBundle
for us, under the src
directory. As we moved forward with the auto-generated CRUD, we saw our bundle getting all sorts of directories and files.
For a bundle to be noticed by Symfony, it needs to be added to the app/AppKernel.php
file, with the registerBundles
method as shown here:
public function registerBundles() { $bundles = [ new SymfonyBundleFrameworkBundleFrameworkBundle(), new SymfonyBundleSecurityBundleSecurityBundle(), new SymfonyBundleTwigBundleTwigBundle(), new SymfonyBundleSwiftmailerBundleSwiftmailerBundle(), new DoctrineBundleDoctrineBundleDoctrineBundle(), //… new AppBundleAppBundle(), ]; //… return $bundles; }
Creating a new bundle is as simple as creating a single PHP file. Let's go ahead and create an src/TestBundle/TestBundle.php
file with content that looks like:
namespace TestBundle; use SymfonyComponentHttpKernelBundleBundle; class TestBundle extends Bundle { … }
Once the file is in place, all we need to do is to register it via the registerBundles
method of the app/AppKernel.php
file as shown here:
class AppKernel extends Kernel { //… public function registerBundles() { $bundles = [ // … new TestBundleTestBundle(), // … ]; return $bundles; } //… }
An even easier way to create a bundle would be to just run a console command as follows:
php bin/console generate:bundle --namespace=Foggyline/TestBundle
This would trigger a series of questions about bundle that in the end results in bundle creation that looks like the following screenshot:
Once the process is complete, a new bundle with several directories and files is created as shown in the following screenshot:
Bundle generator was kind enough to create controller, dependency injection extension extension, routing, prepare services configuration, templates, and even tests. Since we chose to share our bundle, Symfony opted for XML as default configuration format. The dependency extension simply means we can access our bundle configuration by using foggyline_test
as the root element in Symfony's main config.yml
. The actual foggyline_test
element is defined within the DependencyInjection/Configuration.php
file.
3.17.6.75