Zend Framework 2中的服务定位器 [英] Service locator in Zend Framework 2

查看:62
本文介绍了Zend Framework 2中的服务定位器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在控制器中,我这样创建并使用我的模型

In controller I create and use my model so

public function getAlbumTable()
{
    if (!$this->albumTable) {
        $sm = $this->getServiceLocator();
        $this->albumTable = $sm->get('Album\Model\AlbumTable');
    }
    return $this->albumTable;
}

如何在项目的另一个位置(例如,在另一个模型中)而不是在任何控制器中使用此全局服务定位器?

How do I use this global Service Locator in another place of my project, for example, in the other model, and not only in any controller?

文件中定义了与数据库的连接配置:my_project/config/autoload/global.php

Сonfiguration of the connection to the database is defined in the file: my_project/config/autoload/global.php

谢谢.

推荐答案

已决定.所以.为了解决模型类的任务,必须实现ServiceLocatorAwareInterface接口.因此,注入ServiceManager将自动在您的模型中发生.请参阅前面的示例.

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.

对于您的应用程序的表单和其他对象,此处提出了合适的方法 http://michaelgallego.fr/blog/?p = 205 您可以创建扩展BaseForm的基类形式并实现ServiceManagerAwareInterface,从中您将在应用程序中继承其形式.

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

要插入ServiceManager的对象是自动在文件service_manager中的module.config.php文件中,您需要编写

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');

该表单将包含一个对象ServiceManager,该对象将允许其他依赖项.

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

感谢您的帮助.

这篇关于Zend Framework 2中的服务定位器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆