crastlin/laravel-annotation is a Laravel package for routemapping routegroup node.
It currently has 3 GitHub stars and 272 downloads on Packagist (latest version v2.2beta).
Install it with composer require crastlin/laravel-annotation.
Discover more Laravel packages by crastlin
or browse all Laravel packages to compare alternatives.
Last updated
laravel-annotation (版本小于php8)是基于多行注释+PHP反射机制实现注解功能,已发布的注解有:
支持laravel版本 >= 5.8,php版本 >= 7.1
定义规则
注解例子1
class IndexController
{
/**
* @Route(url="login", method="post")
*/
function index()
{
// todo
}
}
或者
class IndexController
{
/**
* @PostMapping("login")
*/
function index(){
// todo
}
}
以上两种注解生成的路由配置结果相同:
Route::post('login', 'IndexController@index')->name('index.index');
注解例子2
class IndexController
{
/**
* @PostMapping("article/{cate}")
*/
function index(){
}
/**
* @PostMapping("article/{cate}/{id}/{page?}")
*/
function detail(){
// todo
}
}
以上两种注解生成的路由配置结果相同:
Route::post('article/{cate}', 'IndexController@index')->name('index.index');
Route::post('article/{cate}/{id}/{page?}', 'IndexController@detail')->name('index.detail');
定义规则
注解例子
/**
* @Group(prefix="home", namespace="Home", middleware="user.check", as="User::", domain="xxx.com")
*/
class IndexController
{
/**
* @Route(url=login, method=post|get)
*/
function index()
{
// todo
}
/**
* @RequestMapping("reg")
*/
function register()
{
// todo
}
/**
* @GetMapping
*/
function userCenter()
{
// todo
}
}
或者使用json格式
/**
* @Group({"prefix":"home", "namespace":"Home", "middleware": "user.check", "as": "User::"})
*/
class IndexController
{
/**
* @Group({"limit": true})
* @Route(url=login, method=post|get)
*/
function index()
{
// todo
}
/**
* @Group({"limit": true})
* @RequestMapping("reg")
*/
function register()
{
// todo
}
/**
* @GetMapping
*/
function userCenter()
{
// todo
}
}
Route::group(["preifx" => "home", "namespace" => "Home", "middleware" => "user.check", "as" => "User::"], function(){
Route::group(["limit" => true], function(){
Route::match(['GET', 'POST'], 'login', 'IndexController@index');
Route::match(['GET', 'POST'], 'reg','IndexController@register');
});
Route::get('Index/userCenter','IndexController@userCenter');
});
// ...
php artisan annotation:config
配置说明
return [
'modules' => ['User', 'Admin'],
'root_group' => [
'User' => [
['prefix' => 'user', 'namespace' => 'User', 'middleware' => 'user.check', 'as' => 'User::'],
// 更多分组
],
'Admin' => [
['prefix' => 'admin', 'namespace' => 'Admin', 'middleware' => 'admin.check', 'as' => 'Admin::'],
// 更多分组
],
],
];
命令说明
php artisan annotation:route {module?}
定义规则
类注解模块
/**
* @node (name="应用名称", parent="父节点", menu=0/1, auth=0/1/2, order=0, params="xx=yy&cc=ss", icon="xxx", remark="xxx", actions="defaultPage,xxx,yyyy")
*/
方法注解模块
/**
* @node (name="节点名称", parent="父节点", menu=0/1, auth=0/1/2, order=0, params="xx=yy&cc=ss", icon="xxx", code="query", remark="xxx", ignore, delete)
*/
参数说明
*(必须)注册节点名称, 如果使用子类名称,则需在子类的类注解定义 @node (name=xxx),实际名称 = 子类的类注解name + 当前方法name
*(可选)注册节点的父节点,如果不定义,则做为一级节点菜单, 默认父节点为当前控制器的defaultPage方法
*(可选)注册节点显示类型,0:不在左侧菜单显示(默认),1:显示左侧菜单;
*(可选)注册节点权限类型,0:只作为菜单,其它:验证权限(默认)
*(可选)菜单排序, menu为1时有效
(可选)菜单携带参数,格式为url参数格式
(可选)作为一级菜单时,定义图标
*(可选)备注功能信息
特殊说明
注解例子
class UserController
{
/**
* @Node(name="用户管理", menu=1, auth=0)
*/
function defaultPage()
{
// this method only for menu
}
/**
* @Node(name="用户列表", menu=1)
*/
function index()
{
// todo
}
/**
* @Node(name="编辑用户", parent="index")
*/
function setUserName()
{
// todo
}
}
继承类使用
abstract class BaseController implements \LaravelAnnotationNodeInterface
{
/**
* @Node(menu=1, auth=0)
*/
function defaultPage()
{
// this method only for menu
}
}
/**
* @Node(name="用户管理", order=1)
*/
class UserController extends BaseController
{
/**
* @Node(name="用户列表", menu=1)
*/
function index()
{
// todo
}
/**
* @Node(name="编辑用户", parent="index")
*/
function setUserName()
{
// todo
}
}
/**
* @Node(name="用户中心", menu=1, auth=0, order=1)
*/
function defaultPage()
{
// this method only for menu
}
多态控制器应用
/**
* @Node(name="动物园", order=1)
*/
abstract class Animal extends BaseController
{
/**
* @Node(name="主页", menu=1)
*/
function index()
{
// todo
}
/**
* @Node(name="观看时间", menu=1)
*/
function schedule()
{
// todo
}
}
/**
* @Node(name="长颈鹿", actions=index, schedule)
*/
class GiraffeController extends Animal
{
}
/**
* @Node(name="老虎")
*/
class TigerController extends Animal
{
}
php artisan annotation:node {module?}
节点注解demo
使用需要在app/Http/Kernel.php中增加中间件配置
class Kernel extends \Illuminate\Foundation\Http\Kernel
{
protected $middleware = [
// ...
Crastlin\LaravelAnnotation\Middleware\InterceptorMiddleware::class,
];
}
然后在控制器中定义规则
参数说明
*(可选)锁key名,默认为模块名+控制器名+方法名,完整的名称为:{prefix}_{name}
*(可选)锁后缀名,可解析输入参数变量,例如请求get id, 则可以使用: suffix="$id" 或者 suffix="get.$id" 或者 suffix="input.$id" 支持:input/get/post/put/delete/header等,其中input包含get/post/put/delete
*(可选)多个参数后缀,使用:suffix={"xxx", "yyy"},同样也支持解析输入变量,例如:suffixes={"$id", "header.$token", "post.name", ...}
*(可选)锁有效期,单位秒,默认为86400
(可选)是否自动释放锁,默认为否,即执行完成自动释放锁
(可选)拒绝时的响应数据,json格式,也可以单独配置code或msg,或者在config/annotation.php中配置lock => response
(可选)response中的自定义code
(可选)response中的自定义message
示例
class IndexController
{
/**
* @RequestMapping("test")
* @SyncLock(expire=30, suffix="$id")
*/
function test()
{
//todo
}
}
5.1 使用前需要对数据进行绑定,以下例子,在中间件绑定请求参数:
namespace App\Http\Middleware;
use Crastlin\LaravelAnnotation\Facades\Injection;
use \Illuminate\Http\Request;
use App\Model\User;
class AuthorizeCheck
{
function handle(Request $request)
{
$parameters = $request->getContent();
// todo something
// ...
// 绑定数据到依赖类容器
Injection::bind('parameters', $parameters);
// 绑定用户
try{
$user = User::find($parameters['uid']);
Injection::bind('user', $user);
}catch (\Throwable $throwable){
var_dump("用户不存在");
}
}
}
// 基类配置注入方法
namespace Illuminate\Routing\Controller;
use Crastlin\LaravelAnnotation\Facades\Injection;
use Crastlin\LaravelAnnotation\Annotation\Annotations\Inject;
use Crastlin\LaravelAnnotation\Annotation\Annotations\PostMapping;
abstract class BaseController extends Controller
{
// 通用注入属性方法
function setProperty(string $name, $value)
{
if (property_exists($this, $name))
$this->{$name} = $value;
}
// 重写callAction
public function callAction($method, $parameters)
{
$input = Input::toArray();
// 解析当前控制器对象属性注解,并自动注入
Injection::injectWithObject($this);
// call controller action
return call_user_func_array([$this, $method], $parameters);
}
}
class IndexController extends BaseController
{
// 在以下属性增加Inject注解
/**
* @var array $parameters
* @Inject
*/
protected $parameters;
/**
* @PostMapping
*/
function index()
{
// 当前访问index方法时,可以直接访问注入的属性
var_dump($this->parameters);
// 使用take方法直接取值
$user = Injection::take('user');
var_dump($user);
// 使用exists判断容器是否绑定对象
$exists = Injection::exists('user');
var_dump($exists);
}
}
5.2 使用别名注入
class IndexController extends BaseController
{
// 在以下属性增加Inject注解
/**
* @var array $data
* @Inject(name="parameters")
*/
protected $data;
/**
* @PostMapping
*/
function index()
{
// 当前访问index方法时,可以直接访问注入的属性
var_dump($this->parameters);
}
}
5.3 使用前缀注入
// 在中间件中绑定带前缀的数据或对象
namespace App\Http\Middleware;
use Crastlin\LaravelAnnotation\Facades\Injection;
use \Illuminate\Http\Request;
class AuthorizeCheck
{
function handle(Request $request)
{
$parameters = $request->getContent();
// todo something
// ...
// 绑定数据到依赖类容器
Injection::bind('common.parameters', $parameters);
}
}
class IndexController extends BaseController
{
// 在以下属性增加Inject注解
/**
* @var array $data
* @Inject(name="common.parameters")
* 或者配置prefix
* @Inject(name="parameters", prefix="common")
*/
protected $data;
/**
* @PostMapping
*/
function index()
{
// 当前访问index方法时,可以直接访问注入的属性
var_dump($this->parameters);
}
}
5.4 使用单例方法:SingletonTrait 自动注入
namespace App\Service;
use Crastlin\LaravelAnnotation\Utils\Traits\SingletonTrait;
class BusinessService
{
use SingletonTrait;
/**
* @var array $data
* @Inject(name="common.parameters")
*/
protected $data;
function profile()
{
var_dump($this->data);
}
}
namespace App\Http\Controllers\Api;
use App\Service\BusinessService;
class IndexController extends BaseController
{
/**
* @PostMapping
*/
function index()
{
$service = BusinessService::singleton();
$service->profile();
}
}
5.5 依赖注入的优先级是:setter方法 -> setProperty方法 -> 直接赋值
namespace App\Service;
use Crastlin\LaravelAnnotation\Utils\Traits\SingletonTrait;
class BusinessService
{
use SingletonTrait;
/**
* @var array $data
* @Inject(name="common.parameters")
*/
protected $data;
// 使用set + 属性名(小驼峰命名规则)
function setData(?array $data)
{
// todo something
$this->data = $data;
}
function profile()
{
var_dump($this->data);
}
}
5.6 方法依赖注入(需要更新版本至:v2.2)
namespace App\Service;
use Crastlin\LaravelAnnotation\Utils\Traits\SingletonTrait;
use App\Model\User;
class BusinessService
{
use SingletonTrait;
/**
* @var User $user
*/
protected $user;
/**
* @Inject(name="service.user")
*/
function takeUser(?User $user)
{
$this->user = $user;
}
function getUser()
{
var_dump($this->user);
}
}
6.1 在控制器中使用
class Kernel extends \Symfony\Component\HttpKernel\HttpKernel
{
protected $middleware = [
// ....
// 引入拦截器中间件
\Crastlin\LaravelAnnotation\Middleware\InterceptorMiddleware::class,
];
}
namespace App\Http\Controllers\Api;
use App\Service\BusinessService;
use Crastlin\LaravelAnnotation\Annotation\Annotations\Validation;
class IndexController extends BaseController
{
/**
* @PostMapping
* @Validation(field="username", rule="required", message="用户名不能为空")
* @Validation(field="mobile", rule="required|regex:~^1\d{10}$~", attribute="手机号", message=":attribute不能为空|:attribute格式不正确")
*/
function index()
{
}
}
namespace App\Http\Controllers\Api;
use App\Service\BusinessService;
use Crastlin\LaravelAnnotation\Annotation\Annotations\Validation;
class IndexController extends BaseController
{
/**
* @PostMapping
* @Validation(field="mobile", rule="required|regex:~^1\d{10}$~", attribute="手机号", message=":attribute不能为空|:attribute格式不正确")
*/
function index()
{
}
}
namespace App\Http\Controllers\Api;
use App\Service\BusinessService;
use Crastlin\LaravelAnnotation\Annotation\Annotations\Validation;
class IndexController extends BaseController
{
/**
* @PostMapping
* @Validation(class="Mobile")
*/
function index()
{
}
}
namespace App\Validator;
use App\Service\BusinessService;
use Crastlin\LaravelAnnotation\Utils\Validate;
class Mobile extends Validate
{
protected $rules = [
'mobile' => 'required|regex:/^1[3456789][0-9]{9}$/',
'code' => 'required|digits_between:3,6',
],
$messages = [
'required' => ':attribute不能为空',
'mobile.regex' => ':attribute输入不正确',
'code.digits_between' => ':attribute必须为3到6位',
],
$attributes = [
'mobile' => '手机号',
'code' => '验证码',
];
}
namespace App\Http\Controllers\Api;
use App\Service\BusinessService;
use Crastlin\LaravelAnnotation\Annotation\Annotations\Validation;
class IndexController extends BaseController
{
/**
* @PostMapping
* @Validation\Required(username)
* @Validation\AlphaNum(username)
* @Validation\Regex(field="username", rule="~^\w{6,20}$~")
*/
function index()
{
}
}
6.2 自定验证注解