How to use dependency injection in Zend Framework?

前端 未结 5 762
攒了一身酷
攒了一身酷 2021-02-02 14:52

Currently I am trying to learn the Zend Framework and therefore I bought the book \"Zend Framework in Action\".

In chapter 3, a basic model and controller is introduced

5条回答
  •  离开以前
    2021-02-02 15:10

    With the Service Manager at Zend Framework 3.

    Official Documentation:

    https://zendframework.github.io/zend-servicemanager/

    1. Dependencies at your Controller are usually be injected by DI Constructor injector.
    2. I could provide one example, that inject a Factory responsible to create the ViewModel instance into the controller.

    Example:

    Controller `

    class JsonController extends AbstractActionController
    {
        private $_jsonFactory;
        private $_smsRepository;
        public function __construct(JsonFactory $jsonFactory, SmsRepository $smsRepository)
        {
            $this->_jsonFactory = $jsonFactory;
            $this->_smsRepository = $smsRepository;
        }
    ...
    }
    

    Creates the Controller

    class JsonControllerFactory implements FactoryInterface
    {
        /**
         * @param ContainerInterface $serviceManager
         * @param string $requestedName
         * @param array|null $options
         * @return JsonController
         */
        public function __invoke(ContainerInterface $serviceManager, $requestedName, array $options = null)
        {
            //improve using get method and callable
            $jsonModelFactory = new JsonFactory();
            $smsRepositoryClass = $serviceManager->get(SmsRepository::class);
            return new JsonController($jsonModelFactory, $smsRepositoryClass);
        }
    }
    

    ` Complete example at https://github.com/fmacias/SMSDispatcher

    I hope it helps someone

提交回复
热议问题