【问题标题】:Loading multiple custom nested routes in Laravel在 Laravel 中加载多个自定义嵌套路由
【发布时间】:2020-07-26 15:48:32
【问题描述】:

我创建了一个长长的自定义路由文件列表,但我不知道加载它们的正确方法,它们被分隔在Routes 目录中的多个文件夹/嵌套文件夹中,如下所示:

Routes:
    custom_routes:
        auth.php
        general.php
        export.php
        admin:
            customers:
                customer.php
                list.php
            users:
                user.php
                // ...
            invoices:
                user.php
                // ...
            settings:
                user.php
                // ...
        front:
            account:
                settings:
                    setting.php
                    account.php
                    //...
            cart:
                cart.php
                //...
            contact:
                contact.php
                //...
    api.php
    channels.php
    console.php
    web.php

如果它们只是 1 或 2 个附加文件,我会使用 RouteServiceProvider 添加它们,但在这种情况下,它们有很多并且在多个嵌套级别/文件夹中。

我怎样才能以正确的方式做到这一点?

【问题讨论】:

    标签: laravel laravel-5 laravel-6


    【解决方案1】:

    我认为您将这样的内容添加到您的助手类/文件中。

    从嵌套目录中获取路由文件:

    function get_route_files($path, $routes) {
        $excludes = ['.', '..', 'channels.php', 'console.php'];
        foreach(scandir($path) as $routeFile) {
            if (in_array($routeFile, $excludes)) {
                continue;
            } else {
                $filePath = $path . '/' . $routeFile;
                if (is_dir($filePath)) {
                    $routes = array_merge($routes, get_route_files($filePath, $routes));
                } else {
                        $alias = get_route_file_alias($filePath);
                        $routes[] = ['path' => str_replace('../routes/', '', $filePath), 'alias' => $alias];
                }
            }
        }
    
        return $routes;
    }
    

    为您的路线获取别名:

    function get_route_file_alias($path) {
        $alias = '';
        foreach($keys = explode('/', $path) as $i => $key) {
            if (!in_array($key, ['..', 'routes'])) {
                if ($i <= count($keys) - 2) {
                        $alias .= $key . '.';
                }
            }
        }
        return $alias;
    }
    

    然后,将以下路线映射到您的RouteServiceProvider

    protected function mapApiRoutes() {
        $routes = get_route_files('../routes', []);
    
        foreach($routes as $route) {
            Route::prefix('api')
                // ->middleware($middleware)  -- if there's any
                ->as($route['alias'])
                ->namespace($this->namespace . "\\API")
                ->group($route['path']);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多