Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony 4 - controllers in two directories

In my application, I use Symfony 4. I want Symfony to search for controllers in two directories: A and B. I found something like this:

controllers:
    resource: '../src/DirectoryA/Controller/'
    type:     annotation

, but it only works for one directory. How can I have Symfony to search for controllers in two directories?

Regards

like image 618
mariusz08 Avatar asked Aug 18 '18 10:08

mariusz08


2 Answers

In your config/services.yaml

App\DirectoryA\Controller\: # assuming you have namespace like that
    resource: '../src/DirectoryA/Controller'
    tags: ['controller.service_arguments']
App\DirectoryB\Controller\: # assuming you have namespace like that
    resource: '../src/DirectoryB/Controller'
    tags: ['controller.service_arguments']

This will add next directory for service arguments. Thats answers your questions based In directory, what you have posted is routing file, in there would be similiar

controllers_a:
    resource: '../src/DirectoryA/Controller/'
    type:     annotation
controllers_b:
    resource: '../src/DirectoryB/Controller/'
    type:     annotation
like image 110
M. Kebza Avatar answered Sep 21 '22 11:09

M. Kebza


The accepted answer is of course completely correct.

However, once you move from having one controller directory to multiple directories, updating your services.yaml file can be a bit of a pain. Even having to have directories specifically for controllers can be limiting.

Here is an alternate approach which allows creating controllers wherever you want and automatically tagging them.

Start with an empty controller interface for tagging.

interface ControllerInterface {}

Now have all your controllers implement the interface

class Controller1 implements ControllerInterface { ...
class Controller2 implements ControllerInterface { ...

And then adjust the kernel to automatically tag all your controller interface classes with the controller tag.

# src/Kernel.php
protected function build(ContainerBuilder $container)
{
    $container->registerForAutoconfiguration(ControllerInterface::class)
        ->addTag('controller.service_arguments')
    ;
}

And presto. You can create your controllers wherever you want with nothing in services.yaml.

Update: If you would like to avoid editing Kernel.php then you can use the _instanceof functionality in your services.yaml file.

#config/services.yaml
services:
    _instanceof:
        App\Contract\ControllerInterface:
            tags: ['controller.service_arguments']

Another Update: As long as your controller extends Symfony's AbstractController then no additional tagging is needed. You can even delete the default controller lines in the default services.yaml file if you want.

like image 21
Cerad Avatar answered Sep 22 '22 11:09

Cerad