Legacy Bundle Structure in Symfony Flex
Symfony Flex simplifies the entire project structure. This post shows how to configure Composer such that you can keep your old legacy bundles in addition to the new src App namespace.
Symfony Flex simplifies the entire project structure. While this is nice for new projects, for legacy projects that comprise more than one source bundle, this switch in the structure can be quite tedious. If you only have a single AppBundle, you probably want to follow the official instructions and migrate the existing code to the new and arguably simpler structure. However, if you face a similar situation like me, having more than 10 bundles under src, you might want to keep the bundles in their original structure and migrate them over time.
As I was already busy switching to attributes, upgrading external dependencies, and several versions of Symfony, I definitely did not want to introduce more additional sources of errors. Instead, I decided to keep the bundles and introduce a new App namespace under the src directory. I moved the bundles to a bundles
directory, resulting in a clear separation from new code that sits in src
.
Resulting File Structure
your-project/
├── composer.json <-- add autoloading for legacy bundles
├── assets/
├── bin/
│ └── console
├── bundles/ <-- new directory for legacy bundles
│ └── NameSpace
│ └── DemoBundle
│ └── NameSpaceDemoBundle.php
├── config/
│ ├── bundles.php <-- Make sure to load your bundles in here as well!
│ ├── packages/ <-- Move your configs here
│ ├── routes.yaml
│ └── services.yaml
├── packages/ <-- optional: overwrite external dependencies
├── public/
│ └── index.php
├── src/
│ ├── ... <-- Holds new code in the App namespace
│ └── Kernel.php
├── templates/
├── tests/
├── translations/
├── var/
└── vendor/
Composer Autoload
Once you move your bundles to another directory, you need to enable PSR-4 Autoloading in our composer.json
and you should be good to keep your legacy bundles while having a new App namespace to migrate to.
"autoload": {
"psr-4": {
"App\\": "src/",
"": "bundles/"
}
},
Make sure the bundles are enabled.
Also make sure that your bundles are included in config/bundles.php
:
<?php
return [
// ... additional entries
NameSpace\DemoBundle\NameSpaceDemoBundle::class => ['all' => true],
];
Overwriting external dependencies
During my upgrades, I also had to change some external, abandoned dependencies. In some cases, the easiest way forward was to copy the dependency into the project and let Composer know. This is easily done using the composer.json
again:
"repositories": [
{
"type" : "path",
"url" : "./packages/some-dependency/example-bundle"
},
...
],
"require": {
"some-dependency/example-bundle": "@dev",
}