它在 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();
}
// ...
}
然后创建一个新的服务工厂,将配置表依赖注入控制器(使用新的 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);
}
}
然后更新配置以使用新工厂。
use Foo\Controller\FooControllerFactory;
'factories' => [
'Foo\\Controller\\Foo' => FooControllerFactory::class,
],