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

后端 未结 3 443
庸人自扰
庸人自扰 2020-12-18 16:07

I have several services: DieselCaseService, CarloanCaseService LvCaseService.

The controller decides which of services to get.

$type = $quickCheck[\         


        
3条回答
  •  囚心锁ツ
    2020-12-18 16:29

    I have created a wrapper-service

    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);
    
    .
    .
    .
    }
    
    

提交回复
热议问题