laravel修改加载路由文件为多文件

修改app\Providers\RouteServiceProvider.php文件下的mapApiRoutes()为

/**
     * Define the "api" routes for the application.
     *
     * These routes are typically stateless.
     *
     * @return void
     */
    protected function mapApiRoutes()
    {
        $apiRoutes = Route::prefix('api')
            ->middleware('api')
            ->namespace($this->namespace);

        //获取指定目录下的所有文件并根据文件创建路由组
        array_map(function ($file) use ($apiRoutes) {
            $apiRoutes->group($file);
        }, self::getFilesArray(base_path('routes/api')));
    }

并在mapApiRoutes()下添加如下方法

  /**
     * Search the route files from the dir.
     * @param $searchDir
     * @param array $files
     * @return array
     */
    private static function getFilesArray($searchDir, array &$files = []): array
    {
        //遍历目录下的所有文件和文件夹
        $handle = opendir($searchDir);
        while ($file = readdir($handle)) {
            if ($file !== '..' && $file !== '.') {
                $f = $searchDir . '/' . $file;
                if (is_file($f)) {
                    //只取php文件
                    $extension = isset(pathinfo($file)['extension']) ? pathinfo($file)['extension'] : '';
                    if ($extension === 'php' || $extension === 'PHP') {
                        $files[] = $f;
                    }
                } else {
                    //递归查询目录下的所有文件
                    self::getFilesArray($f, $files);
                }
            }
        }
        return $files;
    }

这时你的api路由可以放在
routes\api\example1.php
or
routes\api\XXX\example1.php
....

有利于项目的路由分类,便于修改和查找

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容