Laravel 注解路由

Route and Event Annotations for the Laravel Framework

安装/使用

  • composer 安装
1
composer require "laravelcollective/annotations:5.8.*"
  • 创建app/Providers/AnnotationsServiceProvider.php
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
<?php

namespace App\Providers;

use Collective\Annotations\AnnotationsServiceProvider as ServiceProvider;

class AnnotationsServiceProvider extends ServiceProvider
{
/**
* The classes to scan for event annotations
* @var array
*/
protected $scanEvents = [];

/**
* The classes to scan for route annotations
* @var array
*/
protected $scanRoutes = [];

/**
* The classes to scan for model annotations
* @var array
*/
protected $scanModels = [];

/**
* Determines if we will auto-scan in the local environment.
* @var bool
*/
protected $scanWhenLocal = false;

/**
* Determines whether or not to automatically scan the controller
* @var bool
*/
protected $scanControllers = false;

/**
* Determines whether or not to automatically scan all namespaced
* @var bool
*/
protected $scanEverything = false;

/**
* 指定扫描的Controllers
* @return array
*/
public function routeScans()
{
static $app_path = [
'Api',
'Http',
];

$classes = parent::routeScans();

foreach ($app_path as $path) {
$classes = array_merge(
$classes,
$this->getClassesFromPath("app/$path/Controllers")
);
}

return $classes;
}

protected function getClassesFromPath(string $path)
{
$directory = base_path($path);

return $this->app->make('Collective\Annotations\Filesystem\ClassFinder')
->findClasses($directory);
}
}
  • 修改config/app.php
1
2
3
4
5
'providers' => [
// ...
App\Providers\AnnotationsServiceProvider::class
// ...
];
  • 创建app/api/Controllers/TestController.php
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
<?php

namespace App\Api\Controller;

use App\Api\Controller as BaseController;
use Collective\Annotations\Routing\Annotations\Annotations\{
Controller, Get
};

/**
* Class TestController
* @package App\Api\Controller
*
* @Controller(prefix="/api/test")
*/
class TestController extends BaseController
{
/**
* @Get("/test_route")
*/
public function test_route()
{
dd('1024');
}
}
  • 执行 php artisan route:scan

  • 生成了/storage/framework/routes.scanned.php

1
2
3
4
5
6
7
8
<?php 
$router->get('api/test/test_route', [
'uses' => 'App\Api\Controller\TestController@test_route',
'as' => NULL,
'middleware' => [],
'where' => [],
'domain' => NULL,
]);
  • 访问路由laravel8.test/api/test/test_route即可

其他命令参考: Laravel Annotations

Powered by Hexo and Hexo-theme-hiker

Copyright © 2017 - 2023 Keep It Simple And Stupid All Rights Reserved.

访客数 : | 访问量 :