Skip to main content

Create a local bundle in Symfony 4/5

Symfony 4 don`t need bundles anymore when you create new application. Its very good move in my opinion because many people use them in a wrong way. Admin panel, front, or login page its not a bundle - I saw many applications with similar structure. What can be a bundle? Everything that can be easilly reused between any application:

  • library for caching, scaling images,
  • pack of usefull twig extensions,
  • comments system, that can be attached to any entity,
  • and anything you think it will be reused!

If you have custom fields (Form Types) like: image upload, ckeditor field, an much more it is good idea to organize those components in reusable bundle. So lets create Scriptun Form Bundle.

1. Choose path for your local bundle

Where to put your new bundle? Inside src/ where is your whole app? Not so good idea but possible, and namespace it`s already registered. But let`s say we want to put our bundle inside "bundle" folder. So directory structure will look like that:

├─ config/
├─ bundle/
│  └─ Scriptun/
│     └─ FormBundle/
├─ public/
├─ src/
│  └─ Controller/
│  └─ Entity/
├─ tests/
├─ var/
└─ vendor/

It can be anything you want.

2. Create bundle class

Now we need to create file with our bundle class:

// bundle/Scriptun/FormBundle/ScriptunFormBundle.php
namespace Scriptun\FormBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class ScriptunFormBundle extends Bundle

Our bundle is ready!

3. Add path to autoloader

We need to register autoloader paths and notify symfony, about our bundle. First autoload, edit composer.json inside main application folder and find autoload section. Add there your new namespace:

    "autoload": {
        "psr-4": {
            "App\\": "src/",
            "Scriptun\\": "bundle/Scriptun"

As you can see, there is only main, organization namespace. So we can create many bundles there, no need to register every one.

Remember to dump autoload after updating:

composer dump-autoload

4. Register bundle in Symfony configuration

Last step is to add our bundle to config/bundles.php. Add this line:

Scriptun\FormBundle\ScriptunFormBundle::class => ['all' => true],

last part is used to select env where bundle will be loaded. We want our bundle on dev and production so all its true. For bundles like webprofiler you can see dev true configuration.

5. Check your bundle

That's it! We can check if our bundle works in Symfony profiler. When you go to any profiling page, select from left menu "Configuration" and you will see "Enabled Bundles" section. Your bundle should be there.

Add new comment


This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.

We use cookies on our website to enhance your user experience. We also use Google analytics and ads.

Click here to read more I've read it