您现在的位置是:首页 > PHP框架交流PHP框架交流

PHP8.0新特性(2) 注解的使用教程 终于不用三方库支持注解了

上善若水2024-03-04 17:58:37【PHP框架交流】 144人已围观

简介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)

文章评论

站点信息

  • 建站时间:2019-10-24
  • 网站程序:Thinkphp6 Layui
  • 文章统计247篇文章
  • 标签管理标签云
  • 统计数据cnzz统计
  • 微信公众号:扫描二维码,关注我们