gpt4 book ai didi

php - Zend Framework 2 中的服务定位器

转载 作者:行者123 更新时间:2023-12-03 01:02:58 24 4
gpt4 key购买 nike

在 Controller 中我创建并使用我的模型

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

如何在项目的其他位置(例如在其他模型中,而不仅仅是在任何 Controller 中)使用此全局服务定位器?

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

谢谢。

最佳答案

Zend MVC 会将 ServiceLocator 实例注入(inject)到实现 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');
//...
}
}

关于php - Zend Framework 2 中的服务定位器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12770966/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com