0%

slim4获取所有路由

可能是因为slim框架大家使用少,加上官方文档也非常的简单,这里整理一下slim4所有所有路由的方式;问:为什么要获取所有的路由? 答:肯定是用来做权限控制啦~~~

路由设置

本文的方式在通过中间件的方式去获取所有路由,在用户登录的时候会触发中间件去整理所有的路由

1
2
3
4

$app->group('/admin', function(Group $group) use ($app){
$group->post('/go_login', LoginController::class.':login')->addMiddleware(new AuthNodesMiddleware($app));
});

中间件整理所有路由

中间件中的逻辑主要是获取并解析所有的路由,然后整理存储在表里,每次登录的时候都需要重新整理

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
<?php

namespace App\Application\Middleware;

use App\Application\Models\SystemRoutes;
use App\Util\System;
use App\Util\Tools;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Server\MiddlewareInterface as Middleware;
use Psr\Http\Server\RequestHandlerInterface as RequestHandler;
use ReflectionClass;
use Slim\App;
use Slim\Factory\AppFactory;
use Slim\Routing\RouteCollector;
use Slim\Routing\RouteContext;


/**
* - 权限节点处理
*/
class AuthNodesMiddleware implements Middleware
{
public $app;
public function __construct(App $app) {
$this->app = $app;
}

/**
* - 整理并存储权限节点
* @param Request $request
* @param RequestHandler $handler
* @return Response
*/
public function process(Request $request, RequestHandler $handler): Response
{
// 获取所有路由
$routes = $this->app->getRouteCollector()->getRoutes();
$routes_list = [];
// 遍历
foreach ($routes as $route) {
$params = $route->getArguments();
if (!empty($params)) {
$class_name = Tools::arrGetVal($params, 'class_name', '');
$auth_name = Tools::arrGetVal($params, 'auth_name', '');
if (!empty($class_name) && !empty($auth_name)) {
$item = [
'route' => $route->getPattern(),
'route_name' => $auth_name
];
$routes_list[$class_name][] = $item;
}
}
}
$system_routes_model = new SystemRoutes();
// 重新整理存储数据
if (!empty($routes_list)) {
// 删除原始数据
$old_ids = $system_routes_model->column('id');
$system_routes_model->where('id','IN',$old_ids)->delete();
// 节点数据保存
$now_time = time();
foreach ($routes_list as $class_name => $items) {
$last_id = $system_routes_model->insertGetId([
'pid' => 0,
'group_name' => $class_name,
'created_at' => $now_time,
'updated_at' => $now_time
]);
foreach ($items as $item) {
$system_routes_model->insert([
'pid' => $last_id,
'group_name' => $class_name,
'route' => $item['route'],
'route_name' => $item['route_name'],
'created_at' => $now_time,
'updated_at' => $now_time
]);
}
}
}
return $handler->handle($request);
}
}