协程单例

为兼容协程环境下的单例模式安全 可以使用CoroutineSingleTon这个trait

引用方法可以参考普通Singleton trait

  1. namespace EasySwoole\Component;
  2. use Swoole\Coroutine;
  3. trait CoroutineSingleTon
  4. {
  5. private static $instance = [];
  6. static function getInstance(...$args)
  7. {
  8. $cid = Coroutine::getCid();
  9. if(!isset(self::$instance[$cid])){
  10. self::$instance[$cid] = new static(...$args);
  11. /*
  12. * 兼容非携程环境
  13. */
  14. if($cid > 0){
  15. Coroutine::defer(function ()use($cid){
  16. unset(self::$instance[$cid]);
  17. });
  18. }
  19. }
  20. return self::$instance[$cid];
  21. }
  22. function destroy(int $cid = null)
  23. {
  24. if($cid === null){
  25. $cid = Coroutine::getCid();
  26. }
  27. unset(self::$instance[$cid]);
  28. }
  29. }