php - 如何将服务管理器注入 Zend Framework 3 中的模型文件
问题描述
我刚刚将一个项目从 ZF 1.x 版本升级到 Zend Framework 3。
在 ZF 1.x 版本中,我们实现了一个功能,例如为使用 Zend Registry 组件在应用程序中发出的请求提供唯一 id,这在 ZF 3 中不存在。我正在尝试使用 ServiceManager 实现该功能。
所以我尝试通过创建一个工厂类将 ServiceManager 注入模型文件,如下所示:
我的模型类文件代码:
<?php
namespace Application\Model\Common;
use Application\Model\Common\Config\BaseConfig;
use Zend\Session\Container;
use \Zend\ServiceManager\ServiceManager;
class CommonUtils extends BaseConfig{
public function __construct(ServiceManager $sm) {
echo '<pre>';
print_r($sm);
exit();
}
}
?>
工厂类代码:
namespace Application\Model\Common;
use Zend\ServiceManager\Factory\FactoryInterface;
use Interop\Container\ContainerInterface;
class CommonUtilsFactory implements FactoryInterface{
//put your code here
public function __invoke(ContainerInterface $container, $requestedName, mixed $options = null) {
$serviceManager = $container->get('ServiceManager');
return new CommonUtils($serviceManager);
}
}
更新 module.config.php 文件如下:
/** SERVICE MANAGER CONFIGURATION - STARTS HERE **/
'service_manager' => [
'factories' => [
CommonUtils::class => \Application\Model\Common\CommonUtilsFactory::class
],
// Make an alias so that we can use it where we need
'aliases' => [
],
],
/** SERVICE MANAGER CONFIGURATION - ENDS HERE **/
但它不起作用并给出以下错误。
可捕获的致命错误:传递给 Application\Model\Common\CommonUtils::__construct() 的参数 1 必须是 Zend\ServiceManager\ServiceManager 的实例,没有给出
有人请在这里帮助我了解如何在 Zend Framework 3 的模型文件中访问/注入 ServiceManager。
提前致谢。
解决方案
推荐阅读
- r - Rails 6.0 操作文本找不到类型为“text/css”的文件“trix/dist/trix”
- ruby-on-rails - 创建对象后如何在 JSON 中包含嵌套关联?
- async-await - Blazor 组件设计注意事项
- java - Mapstruct 多对一映射
- ruby-on-rails - Ruby on Rails Excel 文件公式计算无需任何手动交互
- javascript - 如何从 JavaScript 表单中删除 google recaptcha?
- php - 从 php 中的唯一 URL 提供许多文件的内容
- neo4j - 根据它们之间的权重找到特定节点的前 n 个节点 - neo4j
- flutter - Flutter 在相机预览和捕获上显示徽标
- dgraph - Dgraph:可以原生存储数组吗?