ACs
ACs

Reputation: 1445

Getter method for services in Symfony controller

Is it a good practice to have a service getter for frequently used services in a controller? For example I mean:

class SomeController Extends Contorller {

      private function getSomethingManager()
      {
           return $this->get('myvendorname.something.manager');
      }

}

Upvotes: 1

Views: 384

Answers (2)

BentCoder
BentCoder

Reputation: 12740

If you are above Symfony 3.3 you can use a Service Locater. You list all common services in Service Locator class. When you need to fetch a specific service from anywhere (from example, Controller, Command, Service so on), all you have to do is, inject ServiceLocator class and fetch required service via ServiceLocator:locate.

It is pretty simple and useful. It helps you to reduce dependency injection as well. Have a look at the full example in the link above.

class ServiceLocator implements ServiceLocatorInterface, ServiceSubscriberInterface
{
    private $locator;

    public function __construct(ContainerInterface $locator)
    {
        $this->locator = $locator;
    }

    public static function getSubscribedServices()
    {
        return [
            ModelFactoryInterface::class,
            CalculatorUtilInterface::class,
            EntityManagerInterface::class,
            AnotherClass::class,
            AndAnother::class,
        ];
    }

    public function get(string $id)
    {
        if (!$this->locator->has($id)) {
            throw new ServiceLocatorException(sprintf(
                'The entry for the given "%s" identifier was not found.',
                $id
            ));
        }

        try {
            return $this->locator->get($id);
        } catch (ContainerExceptionInterface $e) {
            throw new ServiceLocatorException(sprintf(
                'Failed to fetch the entry for the given "%s" identifier.',
                $id
            ));
        }
    }
}

And this is how you use it: ServiceLocator->locate(AnotherClass::class);

Upvotes: 1

René Höhle
René Höhle

Reputation: 27295

Your example is a bit confusing because you can use the Doctrine service directly with your controller. You can inject it in your Action if you use the Autowire function.

public function test(EntityManagerInterface $em) {

}

Then you have the entity manager injected or you can load it over the controller with:

$this->getDoctrine()->getManager()

So this is not a real good example. When you use autowire all classes are registered as service and you can use it.

For database queries you have to use entities and repositories.

https://symfony.com/doc/current/doctrine.html

Upvotes: 1

Related Questions