您现在的位置是:首页 > PHP框架交流PHP框架交流
PHP8.0新特性(2) 注解的使用教程 终于不用三方库支持注解了
上善若水2024-03-04 17:58:37【PHP框架交流】
929人已围观
简介PHP8.0新特性之二注解,注解的使用教程终于不用三方库那种,官方加入了注解,注解用于依赖注入,权限认证,路由生成还是非常合适的,只可惜注解来的太晚,用的人太少了,大部分公司还是用的旧版本PHP.简单
PHP8.0新特性之二注解,注解的使用教程终于不用三方库那种,官方加入了注解,注解用于依赖注入,权限认证,路由生成还是非常合适的,只可惜注解来的太晚,用的人太少了,大部分公司还是用的旧版本PHP.
简单使用下PHP注解吧。
<?php
#熟悉PHP8.0的新特性
//1.注解。
//旧版本不支持注解的方式写法 不好获取注解中的信息,而是采用注释的方式去写注解,idea工具无法识别注解导致误删程序报错异常
#[Component(type: 'service')]
class PostsControllerNew
{
#[Route("/api/posts/{id}", methods: ["GET"])]
public function get($id)
{
return "get";
}
}
#[Attribute]
class Route
{
public $url;
public $methods;
function __construct($url, $methods = ["GET"])
{
$this->url = $url;
$this->methods = $methods;
}
}
#[Attribute]
class Component
{
public $type;
function __construct($type)
{
$this->type = $type;
}
}
//获取注解信息
function getClassAnnotations($class)
{
$annotations = [];
$reflection = new ReflectionClass($class);
$attributes = $reflection->getAttributes();
foreach ($attributes as $attribute) {
$annotations[$attribute->getName()] = $attribute->getArguments();
}
return $annotations;
}
function getMethodAnnotations($class, $method)
{
$annotations = [];
$reflection = new ReflectionClass($class);
$reflectionMethod = $reflection->getMethod($method);
$attributes = $reflectionMethod->getAttributes();
foreach ($attributes as $attribute) {
$annotations[$attribute->getName()] = $attribute->getArguments();
}
return $annotations;
}
print_r(getClassAnnotations(PostsControllerNew::class));
print_r(getMethodAnnotations(PostsControllerNew::class, 'get'));
定义了两个注解,分别需要同过反射来获取到信息!
Array
(
[Component] => Array
(
[type] => service
)
)
Array
(
[Route] => Array
(
[0] => /api/posts/{id}
[methods] => Array
(
[0] => GET
)
)
)
程序的输出结果。希望各大开源框架能迅速接入新版的注解吧!
记得再没有注解前,部分框架的注解是这样写的。
/**
* @ControllerAnnotation(title="测试控制器")
*/
class Test extends AdminController
{
/**
* @NodeAnotation(title="列表")
*/
public function index(){
echo __METHOD__;
}
}
开发的时候总是容易把注解的引用当做无效导入,导致程序报错!
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
新版注解PHPstorm提升还算友好,期待注解还后续项目中发光发热!
Tags: PHP8.0
很赞哦! (0)
随机图文
逗女生开心的爆笑笑话
1、在地铁上我越发的感觉现在乘客们素质低了!我左边的一个女孩在低着头吃早餐,右边的大哥在明目张胆的吃卷饼,还喝着饮料,你们难道没看到标语写着地铁内禁止吃东西吗?最过分的是,你们一个个的都看着我,让我还怎么安心的吃臭豆腐?!2、在街上撞着前女友,实在不想停下来和她交谈,于是我就装作在打电话的样子。。。不料她径直冲我走来说:你在假装打电话吧!?“抱歉稍等一下。”我对不存在的通话linux 查看当前文件大小 当前文件夹数量
linux如何查看当前文件夹大小,文件夹文件个数,查看文件详情的命令是啥,linux命令只有用到时候才会搜。查看当前文件大小:du -sh查看当前文件数量:ls-l |grep “^-“|wc -lphp技术提升心得与方法
现在的PHP市场虽然充斥了大量的的PHP开发人员,但这些人当中真正能称得上高手的却寥寥无几。很多公司虽然招聘了一些PHP开发人员,但是由于技术水平不高,导致公司的项目一直堆积。这不仅另公司无奈也让已经入职的PHP开发人员着急,他们也想要在PHP领域更近一步,但却苦于找不到提高自己的方法,下面我们的鸥仔收集了一些PHP大神的一些工作方式、习惯,让大家看看PHP大神们是如何工作,也希望这些方法能帮助到那些想要在PHP领域更近一步的人。springboot 自带定时任务
定时执行是比较常见的功能,springboot自带了定时执行,上手第一个hello cron第一个定时脚本执行… 搭建springboot项目编写需要执行cron定时脚本添加注解加入容器以及开启定时脚