【问题标题】:How to use controller outside folder App\Http\Controllers in Laravel?如何在 Laravel 中使用文件夹 App\Http\Controllers 外的控制器?
【发布时间】:2019-12-30 19:48:03
【问题描述】:

我在文件夹 App\Web\Controllers\WebController 中有一个控制器 WebController。

网络控制器

<?php namespace App\Web\Controllers;

use Illuminate\Http\Request;

class WebController extends Controller
{
    public index(){
        return view('layouts.master');
    }
}

路线

Route::get('home_page','WebController@index');

当我调用这个路由时,出现如下错误:

类 App\Http\Controllers\WebController 不存在

【问题讨论】:

  • 默认命名空间是App\Http\Controllers。您需要在 RouteServiceProvider.php 中自定义它

标签: php laravel


【解决方案1】:

我建议使用命名空间来使用 Devetoka 的上述代码,或者仅针对 1 个或两个控制器(在我的情况下),您可以简单地注入完整的命名空间。这是经过测试并且有效的。

Route::get('home_page','\App\Web\Controllers\WebController@index');

【讨论】:

    【解决方案2】:

    您在 RouteServiceProvider 中更改默认命名空间。
    protected $namespace = 'App\Http\Controllers';
    App\Http\Controllers 是默认命名空间,您可以将其更改为
    protected $namespace = 'App\Web\Controllers';
    然后你的代码应该可以工作了

    【讨论】:

      【解决方案3】:
      class WebController extends **Controller**
      

      这种关系有问题。您必须将控制器导入此文件。你不见了

      use App\Http\Controllers\Controller
      

      另外,你的路线是错误的。试试这个

      Route::namespace('your namespace here')->group(function () { 
         Route::get('/', 'your-controller-here@your-method'); 
       });
      

      不要更改routeserviceprovider的配置

      【讨论】:

      • 根据documentation,这仅适用于App/Http/Controllers以下的命名空间。你测试过这个吗?定义一个新的根命名空间会起作用吗?
      【解决方案4】:

      跟路由系统有关。

      App\Providers\RouteServiceProvider.php 你会找到map() 方法:

      /**
           * Define the routes for the application.
           *
           * @return void
           */
          public function map()
          {
              $this->mapWebRoutes();
              $this->mapApiRoutes();
          }
      

      在该类中,您将找到“Web Routes”命名空间的定义

      /**
       * Define the "web" routes for the application.
       *
       * These routes all receive session state, CSRF protection, etc.
       *
       * @return void
       */
      protected function mapWebRoutes()
      {
          Route::middleware('web')
               ->namespace($this->namespace) // 'App\Http\Controllers'
               ->group(base_path('routes/web.php'));
      }
      

      现在您只需根据自己的喜好更改namespace() 属性

      protected function mapWebRoutes()
      {
          Route::middleware('web')
               ->namespace('App\Web\Controllers')
               ->group(base_path('routes/web.php'));
      }
      

      【讨论】:

      • 这将如何影响默认功能?现在肯定不再使用默认命名空间了吗?
      • @MHewison 在routes/web.php 的任何路线中,例如Route::get('home_page','WebController@index'); 将指向App\Web\Controllers\WebController.php
      猜你喜欢
      • 1970-01-01
      • 2016-01-11
      • 2020-05-01
      • 2016-12-28
      • 2015-06-25
      • 2020-03-27
      • 2022-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多