Symfony 4. How to access the service from controller without dependency injection?

只谈情不闲聊 提交于 2019-12-23 04:53:19

问题


I have several services: DieselCaseService, CarloanCaseService LvCaseService.

The controller decides which of services to get.

$type = $quickCheck["type"];
/**
 * @var $caseService \App\Service\Cases\CaseInterface
*/
$type = 'diesel; // for test purposes

$caseService = $this->get('case_service.' . $type);

The service aliases are declared like this:

case_service.diesel:
    alias: App\Service\Cases\DieselCaseService
    public: true
class DieselCaseService implements CaseInterface 
{
.
.
.
}

If I try to get the DieselCaseService, I get an error

Service "case_service.diesel" not found: even though it exists in the
app's container, the container inside
"App\Controller\Api\AccountController" is a smaller service locator that only knows about the "doctrine", "form.factory",
"fos_rest.view_handler", "http_kernel", "parameter_bag",
"request_stack", "router", "security.authorization_checker",
"security.csrf.token_manager", "security.token_storage", "serializer",
"session", "templating" and "twig" services. Try using dependency
injection instead.

What can I do? I don't want to inject all of the services to the controller


回答1:


For any "multiple instances of same type by key" situation, you can use autowired array.

1. Autodiscovery Services with App\ namespace

services:
    _defaults:
        autowire: true

    App\:
        resource: ../src

2. Require autowired array in Constructor

<?php

namespace App\Controller\Api;

use App\Service\Cases\DieselCaseService

final class AccountController
{
    /**
     * @var CaseInterface[]
     */
    private $cases;

    /**
     * @param CaseInterface[] $cases
     */
    public function __construct(array $cases)
    {
        foreach ($cases as $case) {
            $this->cases[$case->getName()] = $cases;
        }
    }

    public function someAction(): void
    {
        $dieselCase = $this->cases['diesel']; // @todo maybe add validation for exisiting key
        $dieselCase->anyMethod();
    }
}

3. Register compiler pass in Kernel

The autowired array functionality is not in Symfony core. It's possible thanks to compiler passes. You can write your own or use this one:

use Symplify\PackageBuilder\DependencyInjection\CompilerPass\AutowireArrayParameterCompilerPass;

final class AppKernel extends Kernel
{
    protected function build(ContainerBuilder $containerBuilder): void
    {
        $containerBuilder->addCompilerPass(new AutowireArrayParameterCompilerPass);
    }
}

That's it! :)

I use it on all my projects and it works like a charm.


Read more in post about autowired arrays I wrote.




回答2:


Some rainy Sunday afternoon code. This question is basically a duplicate of several other questions but there are enough moving parts that I suppose it is worthwhile to provide some specific solutions.

Start by defining the cases just to make sure we are all on the same page:

interface CaseInterface { }
class DieselCaseService implements CaseInterface {}
class CarloanCaseService implements CaseInterface{}

The easiest way to answer the question is to add the case services directly to the controller's container:

class CaseController extends AbstractController
{
    public function action1()
    {
        $case = $this->get(DieselCaseService::class);

        return new Response(get_class($case));
    }
    // https://symfony.com/doc/current/service_container/service_subscribers_locators.html#including-services
    public static function getSubscribedServices()
    {
        return array_merge(parent::getSubscribedServices(), [
            // ...
            DieselCaseService::class => DieselCaseService::class,
            CarloanCaseService::class => CarloanCaseService::class,
        ]);
    }
}

The only thing I changed for your question is using the class names for service ids instead of something like 'case_service.diesel'. You can of course tweak the code to use your ids but class names are more standard. Note that there is no need for any entries in services.yaml for this to work.

There are a couple of issues with the above code which may or may not be a problem. The first is that only the one controller will have access to the case services. Which may be all you need. The second potential issue is that you need to explicitly list all your case services. Which again might be okay but it might be nice to automatically pick up services which implement the case interface.

It's not hard to do but it does require following all the steps.

Start be defining a case locator:

use Symfony\Component\DependencyInjection\ServiceLocator;

class CaseLocator extends ServiceLocator
{

}

Now we need some code to find all the case services and inject them into the locator. There are several approaches but perhaps the most straight forward is to use the Kernel class.

# src/Kernel.php
// Make the kernel a compiler pass by implementing the pass interface
class Kernel extends BaseKernel implements CompilerPassInterface 
{
    protected function build(ContainerBuilder $container)
    {
        // Tag all case interface classes for later use
        $container->registerForAutoconfiguration(CaseInterface::class)->addTag('case');
    }
    // and this is the actual compiler pass code
    public function process(ContainerBuilder $container)
    {
        // Add all the cases to the case locator
        $caseIds = [];
        foreach ($container->findTaggedServiceIds('case') as $id => $tags) {
            $caseIds[$id] = new Reference($id);
        }
        $caseLocator = $container->getDefinition(CaseLocator::class);
        $caseLocator->setArguments([$caseIds]);
    }

If you follow all of the above steps then you can inject your case locator into any controller (or other service) that happens to need it:

class CaseController extends AbstractController
{
    public function action2(CaseLocator $caseLocator)
    {
        $case = $caseLocator->get(CarloanCaseService::class);

        return new Response(get_class($case));
    }

And once again, there is no need to make any changes to your services.yaml for all this to work.




回答3:


I have created a wrapper-service

<?php
namespace App;

use Symfony\Component\DependencyInjection\ContainerInterface;

class ServiceFactory
{

    /** @var ContainerInterface */
    private $container;


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

    public function getService($alias)
    {
        return $this->container->get($alias);
    }

    /**
     * @param $alias
     * @return bool
     */
    public function hasService($alias)
    {
        return $this->container->has($alias);
    }
}

than I inject this service into controller

public function saveRegisterData(Request $request, AccountService $accountService, ServiceFactory $serviceFactory) 
{
.
.
.

    if (!$serviceFactory->hasService('case_service.'.$type)) {
        throw new \LogicException("no valid case_service found");
    }

    /**
    * @var $caseService \App\Service\Cases\CaseInterface
    */
    $caseService = $serviceFactory->getService('case_service.' . $type);

.
.
.
}



来源:https://stackoverflow.com/questions/54590981/symfony-4-how-to-access-the-service-from-controller-without-dependency-injectio

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!