Php Zf3控制器无法访问位于其他模块中的模型类表

Php Zf3控制器无法访问位于其他模块中的模型类表,php,zend-framework,zend-framework2,zend-controller,zend-framework3,Php,Zend Framework,Zend Framework2,Zend Controller,Zend Framework3,我是Zend框架的新手。 是否有方法从我的活动控制器访问位于另一个模块中的模型类表?由于ZF3中的再见服务定位器,我无法访问位于其他模块中的模型类表 以前在ZF2控制器中使用过 private configTable; public function getConfigTable() { if (!$this->configTable) { $sm = $this->getServiceLocator(); $this->configT

我是Zend框架的新手。 是否有方法从我的活动控制器访问位于另一个模块中的模型类表?由于ZF3中的再见服务定位器,我无法访问位于其他模块中的模型类表

以前在ZF2控制器中使用过

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();
    ......

}
私有配置表;
公共函数getConfigTable()
{
如果(!$this->configTable){
$sm=$this->getServiceLocator();
$this->configTable=$sm->get('Config\Model\configTable');//configTable;
}
公共函数索引(){
$allConfig=$this->getConfigTable()->getAllConfiguration();
......
}
As服务定位器足以将函数从控制器调用到位于另一个模块中的模型类。 在没有服务定位器的情况下,有没有办法在ZF3中实现类似的功能

提前谢谢各位。 再见

它的再见服务定位器在ZF3中

尚未从ZF3中删除服务定位器。但是,新版本的框架引入了一些更改,如果您依赖
ServiceLocatorAwareInterface
和/或将服务管理器注入控制器/服务,这些更改将破坏现有代码

在ZF2中,默认操作控制器实现了此接口,并允许开发人员从控制器中获取服务管理器,如您的示例所示

建议的解决方案是解决服务工厂中控制器的所有依赖项,并将它们注入构造函数

首先,更新控制器

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

    // ...
}
然后创建一个新的服务工厂,将配置表依赖项注入控制器(使用)

然后更新配置以使用新工厂

use Foo\Controller\FooControllerFactory;

'factories' => [
    'Foo\\Controller\\Foo' => FooControllerFactory::class,
],

1.您可以在控制器的构造函数中使用
DI
。2.为什么您的控制器从另一个模块了解表?@newage感谢您的建议,我确实使用了DI。我试图访问另一个模块模型中已创建的函数以避免冗余。非常感谢!!!!您太棒了@AlexP.Service Manager.d文档对我帮助很大,这个例子非常好,也很容易理解。@PrashantKasajoo我们应该写createService()吗methode?在旧版本中,服务定位器用作参数。我应该在该函数中写什么?我是zend的新手…@PrashantKasajoo我遇到了这个错误
Class Application\Factory\IndexFactory包含1个抽象方法,因此必须声明为抽象或实现其余方法(Zend\ServiceManager\FactoryInterface::createService)
@CJRamki答案显示了如何专门为ZF3创建工厂。错误是因为您使用的是ZF2,而
Zend\ServiceManager\FactoryInterface
是已更新的接口之一。您需要使用
createService()
方法或更新到ZF3以使上述示例生效。@AlexP如何检查我当前的供应商目录zend库是ZF3还是ZF2?因为每个组件都有自己的版本。
use Foo\Controller\FooControllerFactory;

'factories' => [
    'Foo\\Controller\\Foo' => FooControllerFactory::class,
],