Event事件处理类里无法使用依赖注入, 然而把这个依赖注入放在controller下就能正常访问
# 事件注册
\plugin\foo\config\event.php
return [
'user.register' => [
[\plugin\foo\app\event\User::class, 'register'],
]
];
# 需要被注入依赖的类
\plugin\foo\app\service\FooService.php
class FooService {
public function test() {
var_dump("----------------");
}
}
# 事件处理类
\plugin\foo\app\event\User.php
class User
{
/**
* @Inject
* @var FooService
*/
protected $fooService;
/**
* 用户注册成功后的事件
* @param array $user 用户信息
* @return void
*/
public function register(array $user)
{
var_dump("用户注册callback");
$this->fooService->test(); //这里的$this->fooService 为空
}
}
# 正常访问
\plugin\foo\app\controller\UserController.php
class UserController
{
/**
* @Inject
* @var FooService
*/
protected $fooService;
public function index(Request $request) {
$this->fooService->test(); //这里就可以正常执行
}
}
Call to a member function test() on null
"php": ">=7.2",
"workerman/webman-framework": "^1.5.0",
"monolog/monolog": "^2.0",
"webman/gateway-worker": "^1.0",
"webman/console": "^1.3",
"webman/admin": "^0.6.24",
"phpmailer/phpmailer": "^6.9",
"illuminate/events": "^8.83",
"tinywan/jwt": "^1.6",
"psr/container": "^1.1.1",
"php-di/php-di": "^6",
"doctrine/annotations": "^1.14",
"topthink/think-validate": "^2.0",
"illuminate/redis": "^8.2.0",
"symfony/cache": "^5.2",
"webman/event": "^1.0"