转载请著名来源,侵权必究
| |
| declare(strict_types=1); |
| |
| namespace app\common\attribute; |
| |
| |
| interface AttributeHandler |
| { |
| public function handler(mixed $handler); |
| } |
| |
| |
| declare(strict_types=1); |
| |
| namespace app\common\attribute; |
| |
| |
| |
| |
| |
| |
| class NoLogin implements AttributeHandler |
| { |
| public function __construct(){ |
| |
| } |
| |
| public function handler(mixed $handler) |
| { |
| |
| |
| } |
| } |
| |
| |
| |
| declare(strict_types=1); |
| |
| namespace app\shop\attribute; |
| |
| |
| use app\common\attribute\AttributeHandler; |
| |
| |
| |
| |
| |
| class CheckPermission implements AttributeHandler |
| { |
| public function __construct(private string $permission){ |
| } |
| |
| public function handler(mixed $handler) |
| { |
| |
| |
| } |
| } |
| |
注意这里是要加到 控制器中间件
| |
| declare(strict_types=1); |
| |
| namespace app\common\middleware; |
| |
| |
| use app\common\attribute\AttributeHandler; |
| use Closure; |
| use think\App; |
| use think\Request; |
| use think\Response; |
| use think\Session; |
| |
| |
| |
| |
| |
| class AttributeMiddleware |
| { |
| |
| |
| |
| |
| public function handle($request, Closure $next) |
| { |
| |
| $context = app(Context::class); |
| $controller = str_replace('.', '\\', $request->controller()); |
| |
| |
| $reflect = new \ReflectionClass('app\\' . app('http')->getName() . '\controller\\' . $controller); |
| $attributes = $reflect->getMethod($request->action())->getAttributes(); |
| $annotations = [ |
| |
| |
| |
| |
| |
| |
| ]; |
| foreach ($attributes as $attribute) { |
| |
| |
| |
| $instance = $attribute->newInstance(); |
| if ($instance instanceof AttributeHandler) { |
| $annotations[$attribute->getName()] = [ |
| 'attribute' => $attribute, |
| 'instance' => $instance |
| ]; |
| } |
| } |
| $context->annotations = $annotations; |
| |
| foreach ($annotations as $attribute) { |
| |
| |
| |
| $instance = $attribute['instance']; |
| $instance->handler(request: $request); |
| } |
| return $next($request); |
| } |
| } |
| |
| |
| <?php |
| |
| namespace app\shop\controller; |
| |
| use app\common\attribute\NoLogin; |
| use app\shop\attribute\CheckPermission; |
| use app\shop\BaseController; |
| |
| class Index extends BaseController |
| { |
| |
| public function index() |
| { |
| return '<style>*{ padding: 0; margin: 0; }</style><iframe src="https://www.thinkphp.cn/welcome?version=' . \think\facade\App::version() . '" width="100%" height="100%" frameborder="0" scrolling="auto"></iframe>'; |
| } |
| |
| |
| public function hello($name = 'ThinkPHP8') |
| { |
| return 'hello,' . $name; |
| } |
| } |
| |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!