Service locator in Zend Framework 2

前端 未结 3 1928
我寻月下人不归
我寻月下人不归 2020-12-28 08:52

In controller I create and use my model so

public function getAlbumTable()
{
    if (!$this->albumTable) {
                


        
3条回答
  •  囚心锁ツ
    2020-12-28 09:31

    Decided. So. For solving the task of classes of models must implement the interface ServiceLocatorAwareInterface. So injection ServiceManager will happen in your model automatically. See the previous example.

    For forms and other objects of your application suitable method proposed here http://michaelgallego.fr/blog/?p=205 You can to create a base class form extends BaseForm and implements ServiceManagerAwareInterface, from which you will inherit its forms in the application.

    namespace Common\Form;
    
    use Zend\Form\Form as BaseForm;
    use Zend\ServiceManager\ServiceManager;
    use Zend\ServiceManager\ServiceManagerAwareInterface;
    
    class Form extends BaseForm implements ServiceManagerAwareInterface
    {
        /**
         * @var ServiceManager
         */
        protected $serviceManager;
    
        /**
         * Init the form
         */
        public function init()
        {
        }
    
        /**
         * @param ServiceManager $serviceManager
         * @return Form
         */
        public function setServiceManager(ServiceManager $serviceManager)
        {
            $this->serviceManager = $serviceManager;
    
            // Call the init function of the form once the service manager is set
            $this->init();
    
            return $this;
        }
    }
    

    To injection of the object of the ServiceManager was automatically in the file module.config.php in section service_manager you need to write

    'invokables' => array(
        'Album\Form\AlbumForm' => 'Album\Form\AlbumForm',
    ),
    

    Then in your controller, you can create a form so

    $form = $this->getServiceLocator()->get('Album\Form\AlbumForm');
    

    The form will contain an object ServiceManager, which will allow other dependencies.

    Thanks all for your help.

提交回复
热议问题