成員屬性注解
我們直接看以下示例:
UserService
類
<?php
namespace App\Service;
class UserService
{
public function info()
{
var_dump("this is user info");
}
}
Index
控制器類
<?php
namespace App\HttpController;
use App\Service\UserService;
use EasySwoole\HttpAnnotation\AnnotationController;
use EasySwoole\HttpAnnotation\Attributes\Property\Context;
use EasySwoole\HttpAnnotation\Attributes\Property\Di;
use EasySwoole\HttpAnnotation\Attributes\Property\Inject;
class Index12 extends AnnotationController
{
#[Inject(object: new UserService())]
protected ?UserService $param1;
#[Di(key: 'param2Key')]
protected ?UserService $param2;
#[Context(key: 'param3Key')]
protected ?UserService $param3;
protected function onRequest(?string $action): ?bool
{
return parent::onRequest($action);
}
public function test()
{
$this->param1->info();
$this->param2->info();
$this->param3->info();
}
}
如果想正常注入 param2
和 param3
參數(shù),我們可以在框架的全局 onRequest 事件中進(jìn)行注入,如下:
<?php
namespace EasySwoole\EasySwoole;
use App\Service\UserService;
use EasySwoole\Component\Context\ContextManager;
use EasySwoole\Component\Di;
use EasySwoole\EasySwoole\AbstractInterface\Event;
use EasySwoole\EasySwoole\Swoole\EventRegister;
use EasySwoole\Http\Request;
use EasySwoole\Http\Response;
class EasySwooleEvent implements Event
{
public static function initialize()
{
date_default_timezone_set('Asia/Shanghai');
Di::getInstance()->set(SysConst::HTTP_GLOBAL_ON_REQUEST, function (Request $request, Response $response): bool {
// 提前使用 Di 注冊(cè) param2 參數(shù)
Di::getInstance()->set('param2Key', UserService::class); // param2 參數(shù)也可在 bootstrap、initialize、mainServerCreate 等事件中提前注冊(cè)。
// 提前使用 ContextManager 注冊(cè) param3 參數(shù)
ContextManager::getInstance()->set('param3Key', new UserService()); // param3 參數(shù)只可在全局 onRequest 事件中提前注冊(cè)。
return true;
});
}
public static function mainServerCreate(EventRegister $register)
{
}
}
Context 注解
Context
注解,完整命名空間是 \EasySwoole\HttpAnnotation\Attributes\Property\Context
,用于在每次請(qǐng)求進(jìn)來(lái)的時(shí)候,從上下文管理器中取數(shù)據(jù),并賦值到對(duì)應(yīng)的屬性中,以上等價(jià)于:
$this->param3 = \EasySwoole\Component\ContextManager::getInstance()->get('param3Key');
Di 注解
Di
注解,完整命名空間是 \EasySwoole\HttpAnnotation\Attributes\Property\Di
,用于在每次請(qǐng)求進(jìn)來(lái)的時(shí)候,從 IOC
中取數(shù)據(jù),并賦值到對(duì)應(yīng)的屬性中,以上等價(jià)于:
$this->param2 = \EasySwoole\Component\Di::getInstance()->get('param2Key');
Inject 注解
Inject
注解,完整命令空間是 \EasySwoole\HttpAnnotation\Attributes\Property\Inject
,可注入類并且傳入構(gòu)造函數(shù)參數(shù),以上等價(jià)于:
$this->param1 = new \App\Service\UserService(...$args)