keygn / tp6-annotation
ThinkPHP6 的注解 Plus
1.0.1
2020-06-27 09:43 UTC
Requires
- php: >=7.0
- doctrine/annotations: ^1.6
- php-di/phpdoc-reader: ^2.1
- topthink/framework: ^6.0
This package is not auto-updated.
Last update: 2024-09-30 04:32:40 UTC
README
安装
composer require keygn/tp6-annotation
配置
配置文件位于
config/annotation.php
使用方法
创建注解
通过命令行模式创建,例如创建一个User的注解,分为以下三部分
-
添加注解命令行
修改tp6命令行文件位置:
config/console.php
添加以下内容
<?php // +---------------------------------------------------------------------- // | 控制台配置 // +---------------------------------------------------------------------- return [ // 指令定义 'commands' => [ \keygn\tp6\annotation\command\Annotation::class, \keygn\tp6\annotation\command\Handler::class ], ];
-
生成注解类(annotation)
命令行操作:例如生成一个 User 类注解
php think make:annotation User
生成的注解类如下:
<?php declare (strict_types = 1); namespace app\annotation; use Doctrine\Common\Annotations\Annotation; /** * class User * @package app\annotation * @Annotation * @Target({"METHOD","CLASS"}) # 不需要进行类注解去掉"CLASS",不需要方法注解去掉"METHOD" */ class User extends Annotation { // TODO 完成你对注解字段的定义 }
只需要完成 TODO 位置对注解参数的定义,可以参考TP6自带的注解类
-
生成注解处理器类(handler)
命令行操作:例如生成一个 User 类注解处理器类
php think make:handler User
生成的注解类如下:
<?php declare (strict_types = 1); namespace app\annotation\handler; use Doctrine\Common\Annotations\Annotation; use \keygn\tp6\annotation\handler\Handler; class User extends Handler { public function cls(\ReflectionClass $refClass, Annotation $annotation, \think\Route &$route) { // TODO: 完成类注解的操作 } public function func(\ReflectionMethod $refMethod, Annotation $annotation, \think\route\RuleItem &$rule) { // TODO: 完成方法注解的操作 } }
只需要完成 TODO 注解的解释进行操作处理哦,
cls()
方法是针对注解类@Target()
中包含CLASS
时才会被调用,func()
方法是针对注解类@Target()
中包含METHOD
时才会被调用。参数说明:
上述只是对参数做的阐述,实际参数意义和作用具体看自身业务。
-
添加到用户自定义的注解配置中
文件位置:
config/annotation.php
添加内容:
return [ 'custom' => [ # 格式:注解类 => 注解操作类 \app\annotation\User::class => \app\annotation\handler\User::class, # 这里写上你的注解 ] ];
IDE 支持
一些 IDE 已经提供了对注解的支持
- Eclipse 通过 Symfony2 插件 http://symfony.dubture.com/
- PHPStorm 通过 PHP Annotations 插件 http://plugins.jetbrains.com/plugin/7320 或 Symfony2 插件 http://plugins.jetbrains.com/plugin/7219