鍍金池/ 問答/PHP/ Laravel中的Auth::routes為什么是這樣寫?

Laravel中的Auth::routes為什么是這樣寫?

Laravel-5.5里的自帶的認證系統(tǒng)中, 路由 Auth::routes()為什么是這樣調(diào)用的?

而不是Routes::Auth()?

文件1: routes\web.php

<?php
Auth::routes();

文件2: vendor\laravel\framework\src\Illuminate\Routing\Router.php

    /**
     * Register the typical authentication routes for an application.
     *
     * @return void
     */
    public function auth()
    {
        // Authentication Routes...
        $this->get('login', 'Auth\LoginController@showLoginForm')->name('login');
        $this->post('login', 'Auth\LoginController@login');
        $this->post('logout', 'Auth\LoginController@logout')->name('logout');

        // Registration Routes...
        $this->get('register', 'Auth\RegisterController@showRegistrationForm')->name('register');
        $this->post('register', 'Auth\RegisterController@register');

        // Password Reset Routes...
        $this->get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
        $this->post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
        $this->get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
        $this->post('password/reset', 'Auth\ResetPasswordController@reset');
    }
回答
編輯回答
撿肥皂

先看源碼,看看 Auth::routes( ) 其實是做了什么 ?

圖片描述

// 如果你不知道 $app->make('router') 的返回值,dd() 打印一下就會知道是 Router 實例
static::$app->make('router')->auth();

底層其實還是手動創(chuàng)建了一個Router實例,并調(diào)用了它的auth方法,你所說的 Routes::Auth()也是這樣的。

所以,無論你使用 Routes::Auth() 或者 Auth::routes() 其實都是生成 Router 實例并調(diào)用了它的 auth方法,作者為什么建議使用 Auth::routes() ,稍微動腦就能想到,Auth::routes()這種寫法更容易讓人知道生成的路由是和認證權(quán)限有關(guān)的,和 Auth::id() , Auth::check 等對應,更規(guī)范整齊。

2018年2月21日 08:54
編輯回答
情已空

簡單來說 文件 2 才是 Route 組件的核心 所以寫成 $this 很正常
文件 1 的話 需要看下文檔的詳細解釋:
https://d.laravel-china.org/d...

2018年2月22日 02:06