InteractsWithSwooleTable.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006-2018 http://thinkphp.cn All rights reserved.
  6. // +----------------------------------------------------------------------
  7. // | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
  8. // +----------------------------------------------------------------------
  9. // | Author: yunwuxin <448901948@qq.com>
  10. // +----------------------------------------------------------------------
  11. namespace think\swoole\concerns;
  12. use Swoole\Table as SwooleTable;
  13. use think\App;
  14. use think\Container;
  15. use think\swoole\Table;
  16. /**
  17. * Trait InteractsWithSwooleTable
  18. *
  19. * @property Container $container
  20. * @property App $app
  21. */
  22. trait InteractsWithSwooleTable
  23. {
  24. /**
  25. * @var Table
  26. */
  27. protected $currentTable;
  28. /**
  29. * Register customized swoole tables.
  30. */
  31. protected function prepareTables()
  32. {
  33. $this->currentTable = new Table();
  34. $this->registerTables();
  35. $this->onEvent('workerStart', function () {
  36. $this->app->instance(Table::class, $this->currentTable);
  37. foreach ($this->currentTable->getAll() as $name => $table) {
  38. $this->app->instance("swoole.table.{$name}", $table);
  39. }
  40. });
  41. }
  42. /**
  43. * Register user-defined swoole tables.
  44. */
  45. protected function registerTables()
  46. {
  47. $tables = $this->container->make('config')->get('swoole.tables', []);
  48. foreach ($tables as $key => $value) {
  49. $table = new SwooleTable($value['size']);
  50. $columns = $value['columns'] ?? [];
  51. foreach ($columns as $column) {
  52. if (isset($column['size'])) {
  53. $table->column($column['name'], $column['type'], $column['size']);
  54. } else {
  55. $table->column($column['name'], $column['type']);
  56. }
  57. }
  58. $table->create();
  59. $this->currentTable->add($key, $table);
  60. }
  61. }
  62. }