search
HomeBackend DevelopmentPHP TutorialLaravel optimization split routing file

Laravel optimization split routing file

Jan 02, 2018 pm 01:24 PM
laraveldocumentrouting

本文是一篇关于Laravel分割路由文件(routes.php)的最佳方式教程文章,内容介绍的很详细,学习Laravel的小伙伴可以参考学习。

前言

Laravel 的路由功能很强大,默认都是定义在 routes.php 文件中,随着项目越来越大,我们需要的定义的路由越来越多,想象一下,如果几百上千个路由都定义在一个文件中,如何去维护?也许还有不同的人都在同一个文件定义路由,这就造成了冲突,因此我们需要分割 routes.php 文件。

下面介绍一种很优雅的方式。

app/Providers/RouteServiceProvider.php map 方法中可以如下定义:

public function map(Router $router)
{
  $router->group(['namespace' => $this->namespace], function ($router) {
    //require app_path('Http/routes.php');
    foreach (glob(app_path('Http//Routes') . '/*.php') as $file) {
      $this->app->make('App\\Http\\Routes\\' . basename($file, '.php'))->map($router);
    }
  });
}

文件组织结构图如下:

这样它会遍历 app/Http/Routes/ 文件夹下的文件,遍历每个文件路由类的 map 方法,每个文件的结构都类似,

举个例子:

<?php
namespace App\Http\Routes;

use Illuminate\Contracts\Routing\Registrar;

class HomeRoutes
{
  public function map(Registrar $router)
  {
    $router->group([&#39;domain&#39; => &#39;www.tanteng.me&#39;, &#39;middleware&#39; => &#39;web&#39;], function ($router) {
      $router->auth();
      $router->get(&#39;/&#39;, [&#39;as&#39; => &#39;home&#39;, &#39;uses&#39; => &#39;IndexController@index&#39;]);
      $router->get(&#39;/blog&#39;, [&#39;as&#39; => &#39;index.blog&#39;, &#39;uses&#39; => &#39;BlogController@index&#39;]);
      $router->get(&#39;/resume&#39;, [&#39;as&#39; => &#39;index.resume&#39;, &#39;uses&#39; => &#39;IndexController@resume&#39;]);
      $router->get(&#39;/post&#39;, [&#39;name&#39; => &#39;post.show&#39;, &#39;uses&#39; => &#39;ArticleController@show&#39;]);
      $router->get(&#39;/contact&#39;, [&#39;as&#39; => &#39;index.contact&#39;, &#39;uses&#39; => &#39;IndexController@contact&#39;]);
      $router->post(&#39;/contact/comment&#39;, [&#39;uses&#39; => &#39;IndexController@postComment&#39;]);
      $router->get(&#39;/travel&#39;, [&#39;as&#39; => &#39;index.travel&#39;, &#39;uses&#39; => &#39;TravelController@index&#39;]);
      $router->get(&#39;/travel/latest&#39;, [&#39;as&#39; => &#39;travel.latest&#39;, &#39;uses&#39; => &#39;TravelController@latest&#39;]);
      $router->get(&#39;/travel/{destination}/list&#39;, [&#39;as&#39; => &#39;travel.destination&#39;, &#39;uses&#39; => &#39;TravelController@travelList&#39;]);
      $router->get(&#39;/travel/{slug}&#39;, [&#39;uses&#39; => &#39;TravelController@travelDetail&#39;]);
      $router->get(&#39;/sitemap.xml&#39;, [&#39;as&#39; => &#39;index.sitemap&#39;, &#39;uses&#39; => &#39;IndexController@sitemap&#39;]);
    });
  }
}

把路由规则都写到每个文件的 map 方法中,这样一来,就实现了很好的 routes.php 文件的分开管理。此外,你也可以简单的分割,直接把 routes.php 中的定义拆散成多个文件,通过 require 的方式引入,但是哪个更好,一目了然。

那么这样路由分开多个文件后岂不是增加调用次数,会不会影响性能?答案是不必担心。通过 Laravel 的命令:

php artisan route:cache

生成路由缓存文件后,路由只会读取缓存文件的路由规则,因此不会影响性能,这样做让开发更高效和规范。

相关推荐:

利用Laravel生成Gravatar头像地址的优雅方法

Laravel使用Pagination插件实现自定义分页

laravel编写APP接口(API)

The above is the detailed content of Laravel optimization split routing file. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
What is the difference between unset() and session_destroy()?What is the difference between unset() and session_destroy()?May 04, 2025 am 12:19 AM

Thedifferencebetweenunset()andsession_destroy()isthatunset()clearsspecificsessionvariableswhilekeepingthesessionactive,whereassession_destroy()terminatestheentiresession.1)Useunset()toremovespecificsessionvariableswithoutaffectingthesession'soveralls

What is sticky sessions (session affinity) in the context of load balancing?What is sticky sessions (session affinity) in the context of load balancing?May 04, 2025 am 12:16 AM

Stickysessionsensureuserrequestsareroutedtothesameserverforsessiondataconsistency.1)SessionIdentificationassignsuserstoserversusingcookiesorURLmodifications.2)ConsistentRoutingdirectssubsequentrequeststothesameserver.3)LoadBalancingdistributesnewuser

What are the different session save handlers available in PHP?What are the different session save handlers available in PHP?May 04, 2025 am 12:14 AM

PHPoffersvarioussessionsavehandlers:1)Files:Default,simplebutmaybottleneckonhigh-trafficsites.2)Memcached:High-performance,idealforspeed-criticalapplications.3)Redis:SimilartoMemcached,withaddedpersistence.4)Databases:Offerscontrol,usefulforintegrati

What is a session in PHP, and why are they used?What is a session in PHP, and why are they used?May 04, 2025 am 12:12 AM

Session in PHP is a mechanism for saving user data on the server side to maintain state between multiple requests. Specifically, 1) the session is started by the session_start() function, and data is stored and read through the $_SESSION super global array; 2) the session data is stored in the server's temporary files by default, but can be optimized through database or memory storage; 3) the session can be used to realize user login status tracking and shopping cart management functions; 4) Pay attention to the secure transmission and performance optimization of the session to ensure the security and efficiency of the application.

Explain the lifecycle of a PHP session.Explain the lifecycle of a PHP session.May 04, 2025 am 12:04 AM

PHPsessionsstartwithsession_start(),whichgeneratesauniqueIDandcreatesaserverfile;theypersistacrossrequestsandcanbemanuallyendedwithsession_destroy().1)Sessionsbeginwhensession_start()iscalled,creatingauniqueIDandserverfile.2)Theycontinueasdataisloade

What is the difference between absolute and idle session timeouts?What is the difference between absolute and idle session timeouts?May 03, 2025 am 12:21 AM

Absolute session timeout starts at the time of session creation, while an idle session timeout starts at the time of user's no operation. Absolute session timeout is suitable for scenarios where strict control of the session life cycle is required, such as financial applications; idle session timeout is suitable for applications that want users to keep their session active for a long time, such as social media.

What steps would you take if sessions aren't working on your server?What steps would you take if sessions aren't working on your server?May 03, 2025 am 12:19 AM

The server session failure can be solved through the following steps: 1. Check the server configuration to ensure that the session is set correctly. 2. Verify client cookies, confirm that the browser supports it and send it correctly. 3. Check session storage services, such as Redis, to ensure that they are running normally. 4. Review the application code to ensure the correct session logic. Through these steps, conversation problems can be effectively diagnosed and repaired and user experience can be improved.

What is the significance of the session_start() function?What is the significance of the session_start() function?May 03, 2025 am 12:18 AM

session_start()iscrucialinPHPformanagingusersessions.1)Itinitiatesanewsessionifnoneexists,2)resumesanexistingsession,and3)setsasessioncookieforcontinuityacrossrequests,enablingapplicationslikeuserauthenticationandpersonalizedcontent.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.