【问题标题】:Use specific ServiceProvider in Laravel 4在 Laravel 4 中使用特定的 ServiceProvider
【发布时间】:2013-09-13 10:19:54
【问题描述】:

Laravel 4 附带 php artisan routes 命令。这会在命令行上显示已注册路由的列表。我不想在命令行上显示注册的路由,而是想在控制器中获取它的值。

下面的方法正是我想要的:

Illuminate\Foundation\Console\RoutesCommand()

不幸的是,这是一个受保护的方法,所以当我尝试这样的事情时它不起作用

$rc = new Illuminate\Foundation\Console\RoutesCommand(new Illuminate\Routing\Router);

print_r($rc->getRoutes());

如何访问此方法以在我的 Laravel 4 应用中显示已注册的路线?

甚至更好;如何访问任何自动加载的服务提供者的方法?

【问题讨论】:

    标签: php laravel service-provider


    【解决方案1】:

    我相信您必须创建一个 extends Illuminate\Foundation\Console\RoutesCommand 的类,然后您可以使用 print_r($this->getRoutes()); 运行该方法

    【讨论】:

      【解决方案2】:

      以下是如何从控制器内部调用 Artisan 命令的示例:

      use Symfony\Component\Console\Input\ArrayInput;
      use Symfony\Component\Console\Output\Output;
      use Illuminate\Console\Application as ConsoleApplication;
      
      class MyOutput extends Output {
      
          protected $contents = '';
      
          protected function doWrite($message, $newline)
          {
              $this->contents .= $message . ($newline ? "\n" : '');
          }
      
          public function __toString()
          {
              return $this->contents;
          }
      }
      
      class MyController extends BaseController {
      
          public function getRoutes()
          {
              $app = app();
              $app->loadDeferredProviders();
              $artisan = ConsoleApplication::start($app);
      
              $command = $artisan->find('routes');
              $input = new ArrayInput(array('command' => 'routes'));
              $output = new MyOutput();
      
              $command->run($input, $output);
              return '<pre>' . $output . '</pre>';
          }
      
      }
      

      在这种情况下,Artisan 命令是routes,我们没有向它传递任何参数。

      【讨论】:

      • 使用exec('php /my/laravel/app/artisan routes', $output); 更容易,但这会返回一个字符串数组。我已经对结果进行了正则表达式,所以我可以处理它的数据,但这真的不是它应该工作的方式。
      【解决方案3】:

      你可以像这样得到所有的路线:

      $routes = App::make('router')->getRoutes();
      
      foreach($routes as $name => $route)
      {
          //do your stuff
      }
      

      【讨论】:

      • 我最终使用了:$routes = Route::getRoutes();
      猜你喜欢
      • 2014-07-02
      • 2017-12-07
      • 2013-05-23
      • 1970-01-01
      • 1970-01-01
      • 2017-11-18
      • 2013-10-05
      • 2014-09-12
      • 1970-01-01
      相关资源
      最近更新 更多