How to remove a Symfony service? (Sonata Classification) How to remove a Symfony service? (Sonata Classification) symfony symfony

How to remove a Symfony service? (Sonata Classification)


Since we're talking about a bundle which is a dependency of your application, you have no control over what services it defines and registers into your application.

I believe it's possible to remove them using ContainerBuilder::removeDefinition(). It will work for services defined in other bundles as well, therefore it will work on the Sonata bundle.

You can see an example in Symfony's documentation on exactly where to put this code and how to gain access to the ContainerBuilder object.

However, I advise you to not do this. Even though you won't use some services, they won't bother you and, given how Symfony handles services, they won't cause any performance problems in production, I promise.


You will need to create a compiler pass to remove the definition. In order to be able to do that you have to make sure your bundle is declared after the Sonata one. If you can't control that, then extend the Sonata bundle and define the compiler pass in it.


Half a year later, I found a much cleaner way that keeps the services in the container(because they are needed somewhere), but doesn't show them on the admin panel.

   $definitionsNames = array('sonata.media.admin.media', 'sonata.media.admin.gallery_has_media', 'sonata.media.admin.gallery',        'sonata.classification.admin.category','sonata.classification.admin.tag','sonata.classification.admin.context','sonata.classification.admin.collection');    foreach ($definitionsNames as $definitionName) {        $definition = $container->getDefinition($definitionName);        $tags = $definition->getTags();        $tags['sonata.admin'][0]['show_in_dashboard'] = false;        $definition->setTags($tags);    }

Unfortunately, the admin routes are still available. Not an issue for my side, but I believe there are ways to remove them.The thing is the media_widget contains a link to the admin media edit route, so that needs to be overwritten to not show it anymore. Then the Media, Gallery and GHM admins need to be overridden, and override the configureroutes() function and remove all routes. Then I believe you can't access anything through the admin, but the application can still use the admin services, if they are needed anywhere.

This way, I still follow Radu's advice of not removing services from the container.