WithApplication.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. <?php
  2. namespace think\swoole\concerns;
  3. use Closure;
  4. use think\App;
  5. use think\swoole\App as SwooleApp;
  6. use think\swoole\pool\Cache;
  7. use think\swoole\pool\Db;
  8. use think\swoole\Sandbox;
  9. use Throwable;
  10. /**
  11. * Trait WithApplication
  12. * @package think\swoole\concerns
  13. * @property App $container
  14. */
  15. trait WithApplication
  16. {
  17. /**
  18. * @var SwooleApp
  19. */
  20. protected $app;
  21. protected function prepareApplication()
  22. {
  23. if (!$this->app instanceof SwooleApp) {
  24. $this->app = new SwooleApp($this->container->getRootPath());
  25. $this->app->bind(SwooleApp::class, App::class);
  26. //绑定连接池
  27. if ($this->getConfig('pool.db.enable', true)) {
  28. $this->app->bind('db', Db::class);
  29. $this->app->resolving(Db::class, function (Db $db) {
  30. $db->setLog($this->container->log);
  31. });
  32. }
  33. if ($this->getConfig('pool.cache.enable', true)) {
  34. $this->app->bind('cache', Cache::class);
  35. }
  36. $this->app->initialize();
  37. $this->prepareConcretes();
  38. }
  39. }
  40. /**
  41. * 预加载
  42. */
  43. protected function prepareConcretes()
  44. {
  45. $defaultConcretes = ['db', 'cache', 'event'];
  46. $concretes = array_merge($defaultConcretes, $this->getConfig('concretes', []));
  47. foreach ($concretes as $concrete) {
  48. if ($this->app->has($concrete)) {
  49. $this->app->make($concrete);
  50. }
  51. }
  52. }
  53. protected function getApplication()
  54. {
  55. return $this->app;
  56. }
  57. /**
  58. * 获取沙箱
  59. * @return Sandbox
  60. */
  61. protected function getSandbox()
  62. {
  63. return $this->app->make(Sandbox::class);
  64. }
  65. /**
  66. * 在沙箱中执行
  67. * @param Closure $callable
  68. * @param null $fd
  69. * @param bool $persistent
  70. */
  71. protected function runInSandbox(Closure $callable, $fd = null, $persistent = false)
  72. {
  73. try {
  74. $this->getSandbox()->run($callable, $fd, $persistent);
  75. } catch (Throwable $e) {
  76. $this->logServerError($e);
  77. }
  78. }
  79. }