您现在的位置是:首页 > PHP框架交流PHP框架交流
PHP8.0新特性(2) 注解的使用教程 终于不用三方库支持注解了
上善若水2024-03-04 17:58:37【PHP框架交流】 163人已围观
简介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)
随机图文
-
springboot 整合mybatis 编写第一个查询demo
目前主流的数据库持久层有springdatajpa与mybatis两种方式,其中mybatis在国内使用更为广泛,一起来边写第一个mybatisdemo吧!项目源码下载地址:码云仓库首先看下最终代 -
PHP8.0新特性(6) Nullsafe 字符串与数字的比较更符合逻辑 Nullsafe operator
1.Nullsafe 运算符 $country = null; if ($session !== null) { $user = $session->user; if ($user != -
关于音乐的笑话故事,据说只有对音乐了解的人才看的懂!
1,在一次音乐会上,一位鼓手突然发疯似的将头猛地钻进了身旁的鼓中,台下顿时看傻了眼。原来,阿根廷作曲家毛里西奥·卡赫尔的《定音鼓协奏曲用》,谱子最后标明,要让演奏者用尽全力一头扎进鼓里(这个鼓就是专门用来钻的,之前一直不敲),完成演奏。鼓手也是用生命在演奏啊,太伟大了。2,一男同学木讷老实,但耳朵特别好,一女生不服,让男生闭着眼转过头,然后自己一屁股坐在钢琴键盘上,问此男生是什么音。男生说是a -
除了湖北省图书馆,武汉还有这些图书馆
都说上大学是最好的自学时光,这个时候时间充足,学校里面也有图书馆,资源丰富,没课的时候整天都可以泡在图书馆内接受知识的熏陶。只是很多人毕了业才想到要多看看书,可是借书好像就没有那么方便了,毕竟大部分的