swoft
swoft copied to clipboard
Inject 注解是进程单一实例化的操作。那我要使用注解实现一个会话级别生命周期的对象如何创建?
bean 注入的类是在服务器中全局实例化的对象
例如我先注入一个 TestService 类
/**
* @Bean("services.test")
*/
class TestService
{
public $data;
public function getData()
{
return $this->data;
}
public function setData($data)
{
$this->data = $data;
}
}
在通过控制器中调用
/**
* @Inject("services.test")
*
* @var TestService
*/
public $testService;
/**
* @RequestMapping(route="/add", method={RequestMethod::GET})
*/
public function add(TestService $test,Request $request)
{
$this->testService->setData("hello world");
return $this->testService->getData();
}
/**
* @RequestMapping(route="/get", method={RequestMethod::GET})
*/
public function get(Request $request)
{
return $this->testService->getData();
}
- 上面的行为中通过访问 /add 路径 会实现对 testService 类的data 赋值 在返回一个 "hello world"
- 之后通过 /get 再次请求http 服务会出现没有进行 对象的赋值操作也会返回一个 "hello world" (也就是全局的注入)
希望操作
/**
* @Inject("services.test")
*
* @var TestService
*/
public $testService;
/**
* @RequestMapping(route="/add", method={RequestMethod::GET})
*/
public function add(TestService $test,Request $request)
{
$this->testService->setData("hello world");
$this->setData();
return $this->testService->getData(); //结果是 world
}
protected function setData()
{
$this->testService->setData("world");
}
/**
* @RequestMapping(route="/get", method={RequestMethod::GET})
*/
public function get(Request $request)
{
return $this->testService->getData(); //这里始终返回null
}
- 我希望通过注解的形式 注入一个对象只可在单一会话中使用,会话结束也就会被释放
Request bean 看看 能不能满足