Route.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. <?php
  2. // +----------------------------------------------------------------------
  3. // | ThinkPHP [ WE CAN DO IT JUST THINK IT ]
  4. // +----------------------------------------------------------------------
  5. // | Copyright (c) 2006-2016 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\console\command\optimize;
  12. use think\console\Command;
  13. use think\console\Input;
  14. use think\console\Output;
  15. use think\Container;
  16. class Route extends Command
  17. {
  18. protected function configure()
  19. {
  20. $this->setName('optimize:route')
  21. ->setDescription('Build route cache.');
  22. }
  23. protected function execute(Input $input, Output $output)
  24. {
  25. $filename = Container::get('app')->getRuntimePath() . 'route.php';
  26. if (is_file($filename)) {
  27. unlink($filename);
  28. }
  29. file_put_contents($filename, $this->buildRouteCache());
  30. $output->writeln('<info>Succeed!</info>');
  31. }
  32. protected function buildRouteCache()
  33. {
  34. Container::get('route')->setName([]);
  35. Container::get('route')->setTestMode(true);
  36. // 路由检测
  37. $path = Container::get('app')->getRoutePath();
  38. $files = is_dir($path) ? scandir($path) : [];
  39. foreach ($files as $file) {
  40. if (strpos($file, '.php')) {
  41. $filename = $path . DIRECTORY_SEPARATOR . $file;
  42. // 导入路由配置
  43. $rules = include $filename;
  44. if (is_array($rules)) {
  45. Container::get('route')->import($rules);
  46. }
  47. }
  48. }
  49. if (Container::get('config')->get('route_annotation')) {
  50. $suffix = Container::get('config')->get('controller_suffix') || Container::get('config')->get('class_suffix');
  51. include Container::get('build')->buildRoute($suffix);
  52. }
  53. $content = '<?php ' . PHP_EOL . 'return ';
  54. $content .= var_export(Container::get('route')->getName(), true) . ';';
  55. return $content;
  56. }
  57. }