Session

Easyswoole 自3.2.x开始,不再提供默认的session服务,若需要使用的用户,请独立引入session组件。

安装

  1. composer require easyswoole/session

使用

定义一个基础session控制器,并继承AbstractSessionController父类即可,其余的控制器,只需要继承基础session控制器,即可实现session调用

  1. use EasySwoole\Session\FileSessionHandler;
  2. use EasySwoole\Session\Test\RedisHandler;
  3. use EasySwoole\Session\AbstractSessionController;
  4. class RedisHandler extends AbstractSessionController
  5. {
  6. protected function sessionHandler(): \SessionHandlerInterface
  7. {
  8. /*
  9. * 此处应该由连接池拿链接,否则实际生产会导致不断创建链接
  10. */
  11. $redis = new \Redis();
  12. $redis->connect('127.0.0.1');
  13. return new RedisHandler($redis);
  14. }
  15. function index()
  16. {
  17. $this->session()->start();
  18. $time = $this->session()->get('test');
  19. if($time){
  20. $this->response()->write('session time is '.$time);
  21. }else{
  22. $this->session()->set('test',time());
  23. $this->response()->write('session time is new set');
  24. }
  25. }
  26. }
  27. class FileHandler extends AbstractSessionController
  28. {
  29. protected function sessionHandler(): \SessionHandlerInterface
  30. {
  31. return new FileSessionHandler();
  32. }
  33. function index()
  34. {
  35. $this->session()->start();
  36. $time = $this->session()->get('test');
  37. if($time){
  38. $this->response()->write('session time is '.$time);
  39. }else{
  40. $this->session()->set('test',time());
  41. $this->response()->write('session time is new set');
  42. }
  43. }
  44. }

::: warning 自带的文件session实现是无锁的 :::

支持的方法列表

  • gcMaxLifetime()
  • gcProbability()
  • savePath()
  • sessionId()
  • start()
  • sessionName()
  • set()
  • get()
  • unset()
  • destroy()
  • close()
  • gc()