Ere*_*ite 12 php zend-framework2
在控制器中,我创建并使用我的模型
public function getAlbumTable()
{
if (!$this->albumTable) {
$sm = $this->getServiceLocator();
$this->albumTable = $sm->get('Album\Model\AlbumTable');
}
return $this->albumTable;
}
Run Code Online (Sandbox Code Playgroud)
如何在项目的其他位置使用此全局服务定位器,例如,在其他模型中,而不仅仅在任何控制器中?
С配置与数据库的连接在文件中定义:my_project/config/autoload/global.php
谢谢.
Elv*_*van 15
Zend MVC将ServiceLocator实例注入到实现Zend\ServiceManager\ServiceLocatorAwareInterface的类中.模型表的简单实现如下所示:
<?php
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\ServiceManager\ServiceLocatorAwareInterface;
use Zend\ServiceManager\ServiceLocatorInterface;
class UserTable extends AbstractTableGateway implements ServiceLocatorAwareInterface {
protected $serviceLocator;
public function setServiceLocator(ServiceLocatorInterface $serviceLocator) {
$this->serviceLocator = $serviceLocator;
}
public function getServiceLocator() {
return $this->serviceLocator;
}
// now instance of Service Locator is ready to use
public function someMethod() {
$table = $this->serviceLocator->get('Album\Model\AlbumTable');
//...
}
}
Run Code Online (Sandbox Code Playgroud)
决定.所以.要解决类模型的任务,必须实现ServiceLocatorAwareInterface接口.因此,注入ServiceManager将自动发生在您的模型中.请参阅上一个示例.
对于您的应用程序的表单和其他对象,此处提出了合适的方法http://michaelgallego.fr/blog/?p=205您可以创建基类表单extends BaseForm并实现ServiceManagerAwareInterface,您将从该表单继承其在应用程序中的表单.
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;
}
}
Run Code Online (Sandbox Code Playgroud)
要注入ServiceManager的对象是自动在文件module.config.php中的service_manager部分,你需要编写
'invokables' => array(
'Album\Form\AlbumForm' => 'Album\Form\AlbumForm',
),
Run Code Online (Sandbox Code Playgroud)
然后在您的控制器中,您可以创建一个表单
$form = $this->getServiceLocator()->get('Album\Form\AlbumForm');
Run Code Online (Sandbox Code Playgroud)
该表单将包含一个对象ServiceManager,它将允许其他依赖项.
感谢你的帮助.