快速定位无用路由 妈妈再也不用担心人工排雷了


介绍

看到 Github 一个包,跟踪路由的请求,记录哪个路由在哪一个时刻被调用。这个包最大的目的不是分析数据,而是可以随时随地的查看哪些路由没被调用却还存在程序中。比如你现在去了新的公司,接手了一个新的项目或者你一年前的项目,可能很多路由在前端的请求已经砍掉了,但是你后端的接口还没去掉,这时候这个包的作用就发挥出来了,避免了你人工扫雷。

快速上手

确保 PHP 版本7.1及以上, Laravel 版本5.8及以上

composer require julienbourdeau/route-usage

接下来你所有的请求将记录表中,你可以通过两种方式来查看路由情况,可以直接访问 Auth.php

route1.png 当然该扩展还提供了命令行查看

route2.png 加一个参数

route3.png

剩下的好像也没做什么了,闲着也是闲着,看看他咋么写的

    public function boot()
    {
        Event::listen(RequestHandled::class, LogRouteUsage::class);

        $this->loadViewsFrom(__DIR__.'/../resources/views', 'route-usage');
        $this->loadMigrationsFrom(__DIR__.'/../database/migrations');
        $this->loadRoutesFrom(__DIR__.'/routes.php');

        if ($this->app->runningInConsole()) {
            // Registering package commands.
            $this->commands([
                UsageRouteCommand::class,
            ]);
        }
    }

引导应用程序运行服务,监听 RequestHandled 事件,这个事件是在什么时候执行的

#index.php
...
....
$kernel = $app->make(Illuminate\Contracts\Http\Kernel::class);\
$response = $kernel->handle(\
    $request = Illuminate\Http\Request::capture()\
);

#Illuminate\Foundation\Http\Kernel

public function handle($request)
{
    .....
	.....
	....
    $this->app['events']->dispatch(
        new Events\RequestHandled($request, $response)\
    );
  .....
}

进去看下监听器具体干了什么,好吧说白了就是记录2xx和3xx的请求记录

    public function handle($event)
    {
        $status_code = $event->response->getStatusCode();

        if ($status_code > 400 || $status_code < 200) {
            return;
        }

        $method = $event->request->getMethod();
        $path = $event->request->route()->uri ?? $event->request->getPathInfo();
        $action = optional($event->request->route())->getAction()['uses'];

        if ($action instanceof \Closure) {
            $action = '[Closure]';
        } elseif (!is_string($action) && !is_null($action)) {
            $action = '[Unsupported]';
        }

        $identifier = sha1($method.$path.$action.$status_code);
        $date = date('Y-m-d H:i:s');

        DB::statement(
            "INSERT INTO route_usage
                    (`identifier`, `method`, `path`, `status_code`, `action`, `created_at`, `updated_at`)
                VALUES (?, ?, ?, ?, ?, ?, ?)
                ON DUPLICATE KEY UPDATE `updated_at` = '{$date}'",
            [$identifier, $method, $path, $status_code, $action, $date, $date]
        );
    }

接下来看监听后面一坨是什么

.....
......
  $this->loadViewsFrom(__DIR__.'/../resources/views', 'route-usage');
        $this->loadMigrationsFrom(__DIR__.'/../database/migrations');
        $this->loadRoutesFrom(__DIR__.'/routes.php');

        if ($this->app->runningInConsole()) {
            // Registering package commands.
            $this->commands([
                UsageRouteCommand::class,
            ]);
        }

如果应用中包含了路由,视图还有迁移文件,你需要告诉服务容器咋么去加载他们,也就是位置甩给他们,如果是在命令行操作,需要把扩展包中的命令注册到 Laravel中, 调用 commands ,文件里面就是一个继承自 Illuminate\Foundation\Console\RouteListCommand 的基类

<?php

namespace Julienbourdeau\RouteUsage\Console\Commands;

use Illuminate\Foundation\Console\RouteListCommand;
use Julienbourdeau\RouteUsage\RouteUsage;

class UsageRouteCommand extends RouteListCommand
{
    protected $name = 'usage:route';

    protected $description = 'Show route list with the last access datetime';

    protected $headers = ['Domain', 'Method', 'URI', 'Last used', 'Name', 'Action', 'Middleware'];

    protected $compactColumns = ['method', 'uri', 'last used', 'action'];

    protected function getRoutes()
    {
        $routes = $this->splitRoutesByMethods(parent::getRoutes());

        // TODO: sort by updated_at and group by method+path
        $routeUsage = RouteUsage::all()->mapWithKeys(function ($r) {
            $key = $r->method.'.'.$r->path;

            return [$key => $r];
        });

        return $routes->map(function ($route) use ($routeUsage) {
            $usageKey = $route['method'].'.'.$route['uri'];
            $lastUsed = $routeUsage->has($usageKey) ?
                $routeUsage->get($usageKey)->updated_at->diffForHumans()
                : 'Never';

            return $this->option('compact') ?
                [
                    'method' => $route['method'],
                    'uri' => $route['uri'],
                    'last used' => $lastUsed,
                    'action' => $route['action'],
                ] : [
                    'domain' => $route['domain'],
                    'method' => $route['method'],
                    'uri' => $route['uri'],
                    'last used' => $lastUsed,
                    'name' => $route['name'],
                    'action' => $route['action'],
                    'middleware' => $route['middleware'],
                ];
        })->toArray();
    }

    protected function splitRoutesByMethods(array $routes)
    {
        return collect($routes)->transform(function ($r) {
            $splitRoutes = [];
            foreach (explode('|', $r['method']) as $m) {
                $r['method'] = $m;
                $splitRoutes[] = $r;
            }

            return $splitRoutes;
        })->flatten(1)->reject(function ($r) {
            return 'HEAD' === $r['method'];
        })->values();
    }
}

Route Usage for Laravel


Vote Vote Cancel Collect Collect Cancel

<< 上一篇: 手把手带你探索 MySQL 事务的隔离

>> 下一篇: 人人为我,我为人人!Laravel RBAC 权限管理包,快速搭建后台权限功能~