Home Backend Development PHP Tutorial The best way to split the routes file (routes.php) in Laravel

The best way to split the routes file (routes.php) in Laravel

Feb 15, 2017 pm 05:07 PM

本文是一篇关于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);
    }
  });
}
Copy after login

文件组织结构图如下:

The best way to split the routes file (routes.php) in Laravel

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

举个例子:

<?php
/**
 * Created by PhpStorm.
 * User: xl
 * Date: 2016/7/4
 * Time: 18:07
 */
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;]);
    });
  }
}
Copy after login

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

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

php artisan route:cache
Copy after login

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

好了,以上就是Laravel路由文件(routes.php)最佳分割方式的全部内容,希望对大家学习Laravel有所帮助。也希望大家多多支持PHP中文网。

更多The best way to split the routes file (routes.php) in Laravel相关文章请关注PHP中文网!

Statement of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Framework Security Features: Protecting against vulnerabilities. Framework Security Features: Protecting against vulnerabilities. Mar 28, 2025 pm 05:11 PM

Article discusses essential security features in frameworks to protect against vulnerabilities, including input validation, authentication, and regular updates.

Customizing/Extending Frameworks: How to add custom functionality. Customizing/Extending Frameworks: How to add custom functionality. Mar 28, 2025 pm 05:12 PM

The article discusses adding custom functionality to frameworks, focusing on understanding architecture, identifying extension points, and best practices for integration and debugging.

See all articles