>  기사  >  PHP 프레임워크  >  Laravel 라우팅 파일을 분할하는 매우 세분화된 방법(번역)

Laravel 라우팅 파일을 분할하는 매우 세분화된 방법(번역)

藏色散人
藏色散人앞으로
2020-04-09 11:44:502869검색

우리 모두는 경로로 가득 찬 매우 큰 파일을 가지고 있는 상황에 처해 있었을 것입니다. 거짓말은 아니고, 이 문제로 인해 오랫동안 미칠 지경이 되었고 이를 고칠 방법을 찾아야 했습니다. 그래서 이것이 라우팅 파일을 구성한 방법입니다.

추천 튜토리얼: "laravel tutorial"

처음에는 라우팅 그룹 방식을 사용하여 파일을 수신할 생각이었습니다. 이것이 laravel이 RouteServiceProvider에서 경로를 분할하는 방법입니다.

<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
    /**
     * This namespace is applied to your controller routes.
     *
     * In addition, it is set as the URL generator&#39;s root namespace.
     *
     * @var string
     */
    protected $namespace = &#39;App\Http\Controllers&#39;;
    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        //
        parent::boot();
    }
    /**
     * Define the routes for the application.
     *
     * @return void
     */
    public function map()
    {
        $this->mapApiRoutes();
        $this->mapWebRoutes();
        //
    }
    /**
     * Define the "web" routes for the application.
     *
     * These routes all receive session state, CSRF protection, etc.
     *
     * @return void
     */
    protected function mapWebRoutes()
    {
        Route::middleware(&#39;web&#39;)
             ->namespace($this->namespace)
             ->group(base_path(&#39;routes/web.php&#39;));
    }
    /**
     * Define the "api" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    protected function mapApiRoutes()
    {
        Route::prefix(&#39;api&#39;)
             ->middleware(&#39;api&#39;)
             ->namespace($this->namespace)
             ->group(base_path(&#39;routes/api.php&#39;));
    }
}

사용자 관련 경로를 users.php라는 파일로 추상화하고 mapApiRoutes를 mapUsersRoutes로 복사한 후 이를 내 users.php 파일에 지정했습니다.

 /**
     * Define the routes for the application.
     *
     * @return void
     */
    public function map()
    {
        $this->mapApiRoutes();
        $this->mapWebRoutes();
        $this->mapUsersRoutes();
        //
    }
/**
     * Define the "api" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    protected function mapUsersRoutes()
    {
        Route::prefix(&#39;api&#39;)
             ->middleware(&#39;api&#39;)
             ->namespace($this->namespace)
             ->group(base_path(&#39;routes/users.php&#39;));
    }

나는 당신이 무슨 생각을 하는지 알아요. 분명히 이것이 최선의 해결책은 아닙니다. 왜냐하면 새 파일을 만들어야 할 때마다 이전처럼 등록해야 하기 때문입니다. 그래서 저는 이 초기 아이디어를 다듬어야 했습니다.

애플리케이션 전반에 걸쳐 공용 부분을 별도의 라우팅 파일로 분할하는 아이디어가 있었고, 우리 경로 중 어느 것도 인증된 경로, 게스트 경로, 공용 경로를 넘어설 수 없다는 생각이 있었습니다.

라우팅 폴더의 구조를 다음과 같이 최적화했습니다.

├── routes   
│   ├── api    
│   │   ├── public
│   |   │   ├── users.php 
│   │   ├── auth
│   |   │   ├── users.php 
│   │   ├── guest
│   |   │   ├── users.php

얼핏 보면 "글쎄, 별로 바뀌지 않았으니 아직 이 파일들을 매핑해야 해"라고 생각할 수도 있습니다. 그러나 우리는 실제로 PHP에서 기본적으로 제공하는 glob이라는 함수를 활용할 수 있습니다. 이는 laravel의 솔루션에 연결되지 않기 때문에 즉시 사용 가능한 솔루션입니다.

glob은 정규식을 허용하고 정규식과 일치하는 경로에서 파일 이름을 찾을 수 있습니다. 따라서 우리의 경로는 특정 폴더 아래에 구성되어 있으며 이제 이 폴더 아래의 모든 파일을 찾아 미들웨어에 등록할 수 있습니다.

<?php
namespace App\Providers;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\Route;
class RouteServiceProvider extends ServiceProvider
{
    /**
     * This namespace is applied to your controller routes.
     *
     * In addition, it is set as the URL generator&#39;s root namespace.
     *
     * @var string
     */
    protected $namespace = &#39;App\Http\Controllers&#39;;
    /**
     * Define the routes for the application.
     *
     * @return void
     */
    public function map()
    {
        $this->mapAuthRoutes();
        $this->mapGuestRoutes();
        $this->mapPublicRoutes();
//        $this->mapWebRoutes();
        //
    }
    /**
     * Define the "web" routes for the application.
     *
     * These routes all receive session state, CSRF protection, etc.
     *
     * @return void
     */
    protected function mapWebRoutes()
    {
        Route::middleware(&#39;web&#39;)
            ->namespace($this->namespace)
            ->group(base_path(&#39;routes/web.php&#39;));
    }
    /**
     * Define the "api" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    protected function mapAuthRoutes()
    {
        foreach (glob(base_path(&#39;routes/api/auth/*.php&#39;)) as $file) {
            Route::prefix(&#39;api&#39;)
                ->middleware([&#39;api&#39;, &#39;auth:api&#39;])
                ->group($file);
        }
    }
    protected function mapGuestRoutes()
    {
        foreach (glob(base_path(&#39;routes/api/guest/*.php&#39;)) as $file) {
            Route::prefix(&#39;api&#39;)
                ->middleware([&#39;api&#39;, &#39;guest:api&#39;])
                ->group($file);
        }
    }
    protected function mapPublicRoutes()
    {
        foreach (glob(base_path(&#39;routes/api/public/*.php&#39;)) as $file) {
            Route::prefix(&#39;api&#39;)
                ->middleware(&#39;api&#39;)
                ->group($file);
        }
    }
}

이제 새 파일을 만들 때마다 foreach는 정규식 일치를 사용하므로 파일을 찾습니다(파일은 해당 경로에 있고 PHP 확장자가 있으므로 정규식과 일치합니다). 너무 섹시해요! 하지만 잠시만 기다려주세요.

이 문서는 어떻게 등록되나요?

laravel의 수명주기를 연구했다면 서비스 제공자가 laravel 요청의 수명주기의 일부이며 우리는 이 기능을 활용하여 경로를 동적으로 등록할 수 있다는 것을 알고 있습니다.

그렇습니다! 나는 당신이 그것을 좋아하길 바랍니다.

원본 주소 : https://dev.to/secmohammed/how-to-separa...

번역 주소 : https://learnku.com/laravel/t/42989

위 내용은 Laravel 라우팅 파일을 분할하는 매우 세분화된 방법(번역)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 learnku.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제