【发布时间】:2012-12-24 13:11:03
【问题描述】:
在 Zend Framework 1 中,我有几个映射器,它们从父 Mapper 类继承了 setDbTable 和 getDbTable。
现在在 ZF2 中,我面临一个问题,即我需要模型中的服务管理器,但我不知道如何获得它:
class Mapper
{
protected $tableGateway;
protected $module = 'application';
public function setTableGateway($table)
{
if (is_string($table)) {
$class = $this->module . '\Model\DbTable\\' . ucfirst($table);
$sm = $this->getServiceLocator(); <= Fatal error: Call to undefined method Mapper::getServiceLocator()
$tableGateway = (class_exists($class)) ? $sm->get($class) : $sm->get(new TableGateway($table));
} else {
$tableGateway = $table;
}
if (!$tableGateway instanceof Zend\Db\TableGateway\AbstractTableGateway) {
throw new \Exception('Invalid table data gateway provided');
}
$this->tableGateway = $tableGateway;
return $this;
}
// more code
行:
$sm = $this->getServiceLocator();
给出一个致命错误:
Call to undefined method Application\Model\Mapper\Doc::getServiceLocator()
如何在我的模型中获取服务管理器?还是我不是按照 ZF2 的方式做事?我知道如何在我的控制器中获取服务管理器并将 tableGateway 传递给映射器,但这对我来说似乎有很多重复的代码。
【问题讨论】:
-
在模型中注入服务管理器通常是一个非常糟糕的主意。尝试在您的类中注入依赖项,而不是依赖要注入的服务容器。这是“依赖注入”与“服务容器”的讨论,阅读其中的一些内容并理解为什么他们将这种类型的注入称为反模式是一个好主意。
-
@Jurian Sluiman:对我来说很难讨论,因为我最近才了解依赖注入,但我想我明白了基本概念。下面安迪的回答怎么样(我接受了,因为它有效)?在您看来,这也是一种反模式吗?
-
您可以好好阅读这篇文章:blog.ircmaxell.com/2012/08/…(对我来说,Anthony Ferrara 是一位非常受人尊敬的开发人员)。它并不是真正的黑/白,但在 SO 上就同一问题提出了类似的问题:stackoverflow.com/questions/9011787/…
标签: zend-framework2