如何解决用于JWT的Zend 1独立服务
我需要创建一个独立的服务(用于jwt逻辑),但是我发现引用要使用'new'的服务并不是那么容易,但是不幸的是我创建了一个新实例。 。:/,但我想在一个全局上(使用公共方法)工作并存储令牌值。
应用程序/服务/Jwt.php
<?php
class Application_Service_Jwt
{
private $token;
public function getToken()
{
return $this->token;
}
public function setToken($token)
{
$this->token = $token;
}
}
application / configs / services.global.php
<?php
return [
"services" => array(
'Jwt' => new Application_Service_Jwt()
)
];
application / Bootstrap.php
protected function _initServiceManager()
{
$conf = glob(__DIR__ . "/configs/services.global.php",GLOB_BRACE);
$serviceManagerConfigurator = new \Laminas\ServiceManager\Config($conf["services"]);
$serviceManager = new \Laminas\ServiceManager\ServiceManager();
$serviceManagerConfigurator->configureServiceManager($serviceManager);
// Register it into zend registry is not mandatory
\Zend_Registry::set("serviceManager",$serviceManager);
return $serviceManager;
}
解决方法
这是在ZF1应用程序中实现Laminas Service Manager的方法。由于ZF2和ZF3服务管理器相同,因此也可以使用。
在您的作曲家中添加此依赖项
"laminas/laminas-servicemanager": "^3.4"
在您的Bootstrap.php中添加此_init函数
protected function _initServiceManager()
{
$files = glob(__DIR__ . "/configs/{config,services}.{global,".APPLICATION_ENV."}.php",GLOB_BRACE);
$conf = [];
foreach ($files as $file) {
$conf = array_replace_recursive($conf,include($file));
}
$serviceManagerConfigurator = new \Laminas\ServiceManager\Config($conf["services"]);
$serviceManager = new \Laminas\ServiceManager\ServiceManager();
$serviceManagerConfigurator->configureServiceManager($serviceManager);
// Register it into zend registry is not mandatory
\Zend_Registry::set("serviceManager",$serviceManager);
return $serviceManager;
}
现在,您应该在application / configs下创建services.global.php文件,您可以在其中添加服务定义(请阅读文档ZF2 version is ok中提供的所有可能性)
return [
"services" => [,"factories" => [
"hello" => function() {
return "OK";
}
]
]
在同一文件夹中,添加config。{ENVIRONMENT} .php文件,您可以在其中根据环境定义属性(它们也会根据其值加载)
return [
"myApiConfig" => [
"endpoint" => "...","username" => "...","password" => "...",],
从控制器中,您可以使用getResource或Zend注册表访问服务管理器实例,可以将其添加到覆盖的初始化中
$this->serviceManager = $this->getFrontController()->getParam('bootstrap')->getResource('serviceManager');
并获得任何已定义的服务
$this->serviceManager->get('hello');
您还可以分离使用正确的php名称空间的服务类,并在composer中添加自动加载键(根据需要更改名称空间名称和目录)
"autoload": {
"psr-4": {
"MyNewLibs\\": "library/"
}
},
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。