khu*_*uri 2 php zend-framework zend-controller zend-framework2 zend-framework3
我是Zend Framework的新手.有没有办法从我的活动控制器访问位于另一个模块中的模型类表?作为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();
......
}
Run Code Online (Sandbox Code Playgroud)
由于服务定位器足以将函数从控制器调用到位于另一个模块中的模型类.有没有办法在没有服务定位器的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();
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
然后创建一个新的服务工厂,它将配置表依赖项注入控制器(使用新的ZF3工厂接口)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
然后更新配置以使用新工厂.
use Foo\Controller\FooControllerFactory;
'factories' => [
'Foo\\Controller\\Foo' => FooControllerFactory::class,
],
Run Code Online (Sandbox Code Playgroud)