搜尋
首頁php框架Laravel聊聊怎麼在大型Laravel專案中組織路由

聊聊怎麼在大型Laravel專案中組織路由

想像一個擁有 100 多個路由的 Laravel 項目,其中包括訪客,用戶,管理員等分離的模組。你真的要將所有內容寫在一個文件中嗎?那麼如何將它們分組,並為 URL 添加前綴呢?看看有哪些辦法。


1. 分離 WEB 和 API 路由

這個簡單,因為 Laravel 已經幫你做了。有以下兩個檔案:

##因此,如果你的專案同時有前端頁面和API (使用場景越來越廣),請把API 的路由放在api.php 裡。 【相關推薦:

laravel影片教學

例如,如果你有

/users 頁面,又有/api/users/ 端點,把他們分別寫在自己屬於自己路由文件裡,以免在同一文件中出現同一相同名稱而產生混淆。

但我最近還是從

官方 Laravel 專案中看到了反例。在Laravel Horizo​​​​n 中,Taylor 只有 API 路由,但他沒有分開寫,還是寫在了routes/web.php :

#另一個例子證明Laravel 還是非常的個人化,連Taylor 自己也沒有100% 依照標準來。


2. 把routes/web.php 檔案分組結構化

#下面範例也是來自Laravel

官方文件 的範例:

Route::middleware(['first', 'second'])->group(function () {
    Route::get('/', function () {
        // 使用 first 和 second 中间件
    });

    Route::get('user/profile', function () {
        // 使用 first 和 second 中间件
    });
});

最基本的用法是將不同的路由分組包含在不同的中間件裡面。例如,你希望一個群組預設受

auth 中間件限制,另一組受單獨的  admin 自訂中間件限制等。

這樣,你還可以使用

名稱前綴 等路由分組方法。同樣,官方文件中給出了示例:

Route::prefix('admin')->group(function () {
    Route::get('users', function () {
        // 匹配 URL 「/admin/users」
    });
});

Route::name('admin.')->group(function () {
    Route::get('users', function () {
        // 路由名为 「admin.users」...
    })->name('users');
});

另外,如果您要將所有中間件名稱前綴添加到一個組中,則將它們放入數組中更容易理解:

// 而不是这样做: 
Route::name('admin.')->prefix('admin')->middleware('admin')->group(function () {
    // ...
});

// 可以使用数组
Route::group([
    'name' => 'admin.', 
    'prefix' => 'admin', 
    'middleware' => 'auth'
], function () {
    // ...
});

我們將其結合為一個擁有三個路由分組的真實範例:

    帶有
  • / front / XXXXX# URL 且沒有中間件的「訪客」群組
  • 帶有
  • / user / XXXXX URL 和auth 中間件的「使用者」群組
  • 帶有
  • / admin / XXXXX# URL 和自訂admin 中間件的「管理員」群組
以下是將所有內容分組到

routes / web.php 檔案中的一種方法:

Route::group([
    'name' => 'admin.',
    'prefix' => 'admin',
    'middleware' => 'admin'
], function () {

    // URL链接:/admin/users
    // 路由名称:admin.users
    Route::get('users', function () {
        return 'Admin: user list';
    })->name('users');

});

Route::group([
    'name' => 'user.',
    'prefix' => 'user',
    'middleware' => 'auth'
], function () {

    // URL链接:/user/profile
    // 路由名称:user.profile
    Route::get('profile', function () {
        return 'User profile';
    })->name('profile');

});

Route::group([
    'name' => 'front.',
    'prefix' => 'front'
], function () {

    // 这里没有中间件
    // URL链接:/front/about-us
    // 路由名称:front.about
    Route::get('about-us', function () {
        return 'About us page';
    })->name('about');

});


3. 使用命名空間對控制器進行分組

在上面的範例中,我們沒有使用控制器,只是傳回了靜態文字作為範例。讓我們加入一個控制器,來點小花樣— 我們會將它們建構到各自不同的命名空間的資料夾中,如下所示:

##然後我們可以在路由檔案中使用它們:

Route::group([
    'name' => 'front.',
    'prefix' => 'front'
], function () {
    Route::get('about-us', 'Front.boutController@index')->name('about');
});

但是如果在這個群組中我們有很多控制器呢? 我們應該一直添加

Front.omeController

嗎?當然不是。您也可以將命名空間作為參數之一。

Route::group([
    'name' => 'front.',
    'prefix' => 'front',
    'namespace' => 'Front',
], function () {
    Route::get('about-us', 'AboutController@index')->name('about');
    Route::get('contact', 'ContactController@index')->name('contact');
});


4. 群組嵌套群組

上面的情況,分成了3個群組,實際上這是簡化的, 實際專案的結構稍有不同– 是

兩個

個群組:frontauth 。然後在 auth 中,有兩個子群組:useradmin 。為此, 我們可以在 routes/web.php中建立子組,並分配不同的中間件/前綴等。

Route::group([
    'middleware' => 'auth',
], function() {

    Route::group([
        'name' => 'admin.',
        'prefix' => 'admin',
        'middleware' => 'admin'
    ], function () {

        // URL: /admin/users
        // Route name: admin.users
        Route::get('users', 'UserController@index')->name('users');

    });

    Route::group([
        'name' => 'user.',
        'prefix' => 'user',
    ], function () {

        // URL: /user/profile
        // Route name: user.profile
        Route::get('profile', 'ProfileController@index')->name('profile');

    });

});
我們甚至可以多層嵌套,這是開源專案的一個範例。

Akaunting

:

Route::group(['middleware' => 'language'], function () {
    Route::group(['middleware' => 'auth'], function () {
        Route::group(['prefix' => 'uploads'], function () {
            Route::get('{id}', 'Common.ploads@get');
            Route::get('{id}/show', 'Common.ploads@show');
            Route::get('{id}/download', 'Common.ploads@download');
        });

        Route::group(['middleware' => 'permission:read-admin-panel'], function () {
            Route::group(['prefix' => 'wizard'], function () {
                Route::get('/', 'Wizard.ompanies@edit')->name('wizard.index');

        // ...
另一個範例來自另一個流行的Laravel CRM,名稱為

Monica

:

Route::middleware(['auth', 'verified', 'mfa'])->group(function () {
    Route::name('dashboard.')->group(function () {
        Route::get('/dashboard', 'DashboardController@index')->name('index');
        Route::get('/dashboard/calls', 'DashboardController@calls');
        Route::get('/dashboard/notes', 'DashboardController@notes');
        Route::get('/dashboard/debts', 'DashboardController@debts');
        Route::get('/dashboard/tasks', 'DashboardController@tasks');
        Route::post('/dashboard/setTab', 'DashboardController@setTab');
    });


##5 . RouteServiceProvider 中的全域設定

有一個服務於所有路由設定的檔案–

app/Providers/RouteServiceProvider.php

. 它具有綁定兩個路由檔案– web 和API 的map() 方法:

    public function map()
    {
        $this->mapApiRoutes();
        $this->mapWebRoutes();
    }

    protected function mapWebRoutes()
    {
        Route::middleware('web')
             ->namespace($this->namespace)
             ->group(base_path('routes/web.php'));
    }

    protected function mapApiRoutes()
    {
        Route::prefix('api')
             ->middleware('api')
             ->namespace($this->namespace)
             ->group(base_path('routes/api.php'));
    }

您是否注意到方法中提及的 middleware, namespaceprefix ? 这是您可以为整个文件设置全局配置的地方,因此不必为文件中的每个路由组重复这些设置。

它主要用于 API 路由,因为它们的设置通常是相同的,如下所示:

protected function mapApiRoutes(){
    Route::group([
        'middleware' => ['api'],
        'namespace' => $this->namespace,
        'prefix' => 'api/v1',
    ], function ($router) {
        require base_path('routes/api.php');
    });}

上述方法将在所有 API URLs 的开头加上 api/v1/ 前缀。


6. 分组成更多文件 – 这值得吗?

如果您有大量的路由,并且希望将它们分组到单独的文件中,那么您可以使用上一节中提到的相同文件 – app/Providers/RouteServiceProvider.php。如果您仔细查看它的 map() 方法,您将在末尾看到注释位置:

public function map(){
    $this->mapApiRoutes();

    $this->mapWebRoutes();

    //}

如果愿意,您可以将其解释为添加更多文件的“邀请”。因此,您可以在此文件内创建另一个方法,例如 mapAdminRoutes(),然后将其添加到 map() 方法, 您的文件将被自动注册并加载。

但是,就我个人而言,我看不出这种方法有什么优势,而且我也没有经常看到这种做法。它会带来更多的路由分离,但有时您会迷失在那些文件中,不确定在哪里查找特定的路由。


7. 使用 Artisan route:list 命令查找特定路由

说到更大的路由并迷失在那里,我们有一个 Artisan 命令可以帮助定位某个路由。

您可能知道 php artisan route:list 将展示项目中的所有路由

但您知道还有更多的过滤功能来找到您想要的东西吗? 只需添加带参数的 –method,–name,–path

通过 method 过滤 – GET, POST 等:

按名称或 URL 部分过滤:


这就是我所能告诉的关于在大型项目中分组路由的全部内容。你还有其他例子吗?请在评论中分享。

原文地址:https://laraveldaily.com/how-to-structure-routes-in-large-laravel-projects/

译文地址:https://learnku.com/laravel/t/38917

更多编程相关知识,请访问:编程视频!!

以上是聊聊怎麼在大型Laravel專案中組織路由的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:learnku。如有侵權,請聯絡admin@php.cn刪除
包容的幻想:解決偏遠工作中的孤立和孤獨感包容的幻想:解決偏遠工作中的孤立和孤獨感Apr 25, 2025 am 12:28 AM

Tocombatisolationandlonelinessinremotework,companiesshouldimplementregular,meaningfulinteractions,provideequalgrowthopportunities,andusetechnologyeffectively.1)Fostergenuineconnectionsthroughvirtualcoffeebreaksandpersonalsharing.2)Ensureremoteworkers

Laravel用於全堆棧開發:綜合指南Laravel用於全堆棧開發:綜合指南Apr 25, 2025 am 12:27 AM

laravelispularfullull-stackDevelopmentBecapeitOffersAsAseAseAseAseBlendOfbackendEdpoperandPowerandForterFlexibility.1)ITSbackEndCapaPabilities,sightifyDatabaseInteractions.2)thebladeTemplatingEngingEngineAllolowsLows

視頻會議攤牌:為遠程會議選擇正確的平台視頻會議攤牌:為遠程會議選擇正確的平台Apr 25, 2025 am 12:26 AM

選擇視頻會議平台的關鍵因素包括用戶界面、安全性和功能。 1)用戶界面應直觀,如Zoom。 2)安全性需重視,MicrosoftTeams提供端到端加密。 3)功能需匹配需求,GoogleMeet適合簡短會議,CiscoWebex提供高級協作工具。

哪些數據庫版本與最新的Laravel兼容?哪些數據庫版本與最新的Laravel兼容?Apr 25, 2025 am 12:25 AM

最新版本的Laravel10與MySQL5.7及以上、PostgreSQL9.6及以上、SQLite3.8.8及以上、SQLServer2017及以上兼容。這些版本選擇是因為它們支持Laravel的ORM功能,如MySQL5.7的JSON數據類型,提升了查詢和存儲效率。

將Laravel用作全棧框架的好處將Laravel用作全棧框架的好處Apr 25, 2025 am 12:24 AM

Laravelisanexcellentchoiceforfull-stackdevelopmentduetoitsrobustfeaturesandeaseofuse.1)ItsimplifiescomplextaskswithitsmodernPHPsyntaxandtoolslikeBladeforfront-endandEloquentORMforback-end.2)Laravel'secosystem,includingLaravelMixandArtisan,enhancespro

Laravel的最新版本是什麼?Laravel的最新版本是什麼?Apr 24, 2025 pm 05:17 PM

Laravel10,releasedonFebruary7,2023,isthelatestversion.Itfeatures:1)Improvederrorhandlingwithanewreportmethodintheexceptionhandler,2)EnhancedsupportforPHP8.1featureslikeenums,and3)AnewLaravel\Promptspackageforinteractivecommand-lineprompts.

最新的Laravel版本如何簡化開發?最新的Laravel版本如何簡化開發?Apr 24, 2025 pm 05:01 PM

thelatestlaravelververversionenhancesdevelopmentwith:1)簡化的inimpliticmodelbinding,2)增強EnhancedeloquentcapabibilitionswithNewqueryMethods和3)改善了supportorfortormodernphpfortornphpforternphpfeatureserslikenamedargenamedArgonedArgonsemandArgoctess,makecodingMoreftermeforefterMealiteFficeAndEnjoyaigaigaigaigaigaiganigaborabilyaboipaigyAndenjoyaigobyabory。

在哪裡可以找到最新的Laravel版本的發行說明?在哪裡可以找到最新的Laravel版本的發行說明?Apr 24, 2025 pm 04:53 PM

你可以在laravel.com/docs找到最新Laravel版本的發布說明。 1)發布說明提供了新功能、錯誤修復和改進的詳細信息。 2)它們包含示例和解釋,幫助理解新功能的應用。 3)注意新功能的潛在復雜性和向後兼容性問題。 4)定期審查發布說明可以保持更新並激發創新。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器