Laravel 命名空间


命名空间可以定义为一个元素类,其中每个元素对于相关的类都有一个唯一的名称,它可以与其他类中的元素共享。

命名空间声明


use关键字允许开发人员缩短命名空间。

use <namespace-name>;

在Laravel中使用的默认命名空间是App,但是用户可以改变命名空间来匹配Web应用,使用artisan命令创建用户定义的命名空间,如下所述

php artisan app:name SocialNet


Select Git


命名空间一旦创建就可以在控制器和各种类中使用各种函数,在控制器和内核的命名空间基础上创建的代码,即app/console/kernel.phpapp/Http/controller.php,如下所示:

Kernel.php

<?php

namespace Newbiego\Console;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Foundation\Console\Kernel as ConsoleKernel;

class Kernel extends ConsoleKernel{
   
    /**
        * The Artisan commands provided by your application.
        *
        * @var array
    */
   
    protected $commands = [
    //
    ];
   
    /**
        * Define the application's command schedule.
        *
        * @param \Illuminate\Console\Scheduling\Schedule $schedule
        * @return void
    */
   
    protected function schedule(Schedule $schedule) {
        // $schedule->command('inspire')
        // -> 每小时();
    }
   
    /**
        * Register the Closure based commands for the application.
        *
        * @return void
    */
   
    protected function commands() {
        require base_path('routes/console.php');
    }
}

Controller.php

<?php
namespace Newbiego\Http\Controllers;

use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;

class Controller extends BaseController{
    use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}

控制器充当了模型和视图之间的中介,对于我们创建的名为Newbiego的命名空间,它们将被用于控制器的文件controller.php中,该命名空间被正确地初始化为Http/Controllers。

命名空间一旦创建,就会使用其他各种命名空间,如上面代码中提到的AuthorizesRequests, DispatchesJobs和ValidatesRequests。

Use 关键字


命名空间发生在当前类的位置,正如在我们的例子中提到的,我们已经声明Newbiego作为我们的命名空间,它位于app文件夹中,声明的命名空间将是App\Newbiego,每当你想使用该类时,你应该使用use关键字,use关键字的语法如下所示:

use Newbiego\Http\Controllers\Controller;