我是 Zend Framework 的新手。 有没有办法从我的事件 Controller 访问位于另一个模块中的模型类表?作为 ZF3 中的再见服务定位器,我无法访问位于其他模块中的模型类表。
以前在 ZF2 Controller 中
private configTable;
public function getConfigTable()
{
if (!$this->configTable) {
$sm = $this->getServiceLocator();
$this->configTable = $sm->get('Config\Model\ConfigTable'); // <-- HERE!
}
return $this->configTable;
}
public function indexAction(){
$allConfig = $this->getConfigTable()->getAllConfiguration();
......
}
因为服务定位器足以将函数从 Controller 调用到位于另一个模块中的模型类。 有没有办法在没有服务定位器的情况下在 ZF3 中实现类似的功能?
提前谢谢大家。 再见!
最佳答案
its bye bye service locator in ZF3
服务定位器尚未从 ZF3 中删除。但是,新版本的框架引入了一些更改,这些更改如果您依赖于 ServiceLocatorAwareInterface
和/或将服务管理器注入(inject)到您的 Controller /服务。
在 ZF2 中,默认操作 Controller 实现了这个接口(interface),并允许开发人员从 Controller 中获取服务管理器,就像在您的示例中一样。您可以在 migration guide 中找到有关更改的更多信息.
推荐的解决方案是在服务工厂内解析 Controller 的所有依赖项,并将它们注入(inject)构造函数。
首先,更新 Controller 。
namespace Foo\Controller;
use Config\Model\ConfigTable; // assuming this is an actual class name
class FooController extends AbstractActionController
{
private $configTable;
public function __construct(ConfigTable $configTable)
{
$this->configTable = $configTable;
}
public function indexAction()
{
$config = $this->configTable->getAllConfiguration();
}
// ...
}
然后创建一个新的服务工厂,将配置表依赖项注入(inject) Controller (使用 the new ZF3 factory interface )
namespace Foo\Controller;
use Foo\Controller\FooController;
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\FactoryInterface;
class FooControllerFactory implements FactoryInterface
{
public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
{
$configTable = $container->get('Config\Model\ConfigTable');
return new FooController($configTable);
}
}
然后更新配置以使用新工厂。
use Foo\Controller\FooControllerFactory;
'factories' => [
'Foo\\Controller\\Foo' => FooControllerFactory::class,
],
关于php - Zf3 Controller 无法访问位于另一个模块中的模型类表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38696620/