电脑好玩的网页游戏推荐宁波seo博客
前言
学过java的同学应该都知道注解的作用,但是在php中注解有什么用呢?我的理解就是美化代码和便于维护一些类的设计。
说明
我们先设计一个类,声明人类的性别
<?php
class Sex
{//男人const MAN = 1;//女人const WIFE = 2;//未知const UNKNOWN = 0;
}
由上可知,我们分别设计了3个类型,0=>未知,1=>男人,2=>女人
现在,应业务需求,我给前端展示的内容不能显示数字(0,1,2),要展示汉字(未知,男人,女人),数据映射在后端完成。 结合php8引入了枚举的支持。那么我们重新设计如下
<?phpenum Sex : int
{//男人case MAN = 1;//女人case WIFE = 2;//未知case UNKNOWN = 0;public function getDescription() : string{return match($this){self::MAN => '男人',self::WIFE => '女人',self::UNKNOWN => '未知'};}
}
echo Sex::MAN->getDescription(); //获得中文映射
由上可知,是不是看着就简单了许多。
但是,还有更直观的显示,设计会稍微复杂一点,我们接着慢慢向下看。
我们先设计一个trait,此trait完成注解的反射。
<?php
trait EnumFeature
{/*** 获取case 注解内容* @param string $class 注解类* @return null | Object*/protected function getTargetCaseReflectionAnnotation(string $class) : mixed{$reflection = new \ReflectionEnumBackedCase(self::class,$this->name);$attributes = $reflection->getAttributes();if(empty($attributes)){return null;}foreach($attributes as $attribute){if($attribute->getName() === $class){return $attribute->newInstance();}}return null;}
}
在设计一个注解类,让这个注解类可以注解 enum - case
<?php
#[\Attribute(\Attribute::TARGET_CLASS_CONSTANT)]
class CaseDescription
{public function __construct(public string $description){}
}
重构 enum 设计如下
enum Sex : int
{use EnumFeature#[CaseDescription('男人')]case MAN = 1;#[CaseDescription('女人')]case WIFE = 2;#[CaseDescription('未知')]case UNKNOWN = 0;public function getDescription() : ?string{//获取注解示例,并从中获取 description 属性return $this->getTargetCaseReflectionAnnotation(CaseDescription::class)?->description;}
}
这样看着是否直观了很多?对比之前的方案,也便于维护。
完整版,应业务需求,不同的性别在页面上呈现的性别颜色也不同。
再设计一个Color注解
<?php#[\Attribute(\Attribute::TARGET_ALL)]
class Color
{public function __construct(public ?string $value = null){}
}
对性别进行color注解添加
enum Sex : int
{use EnumFeature#[CaseDescription('男人'),Color("#000000")]case MAN = 1;#[CaseDescription('女人'),Color("#FFF000")]case WIFE = 2;#[CaseDescription('未知'),Color("#CCCCCC")]case UNKNOWN = 0;//获取中文名称public function getDescription() : ?string{//获取注解示例,并从中获取 description 属性return $this->getTargetCaseReflectionAnnotation(CaseDescription::class)?->description;}//获取颜色public function getColort() : ?string{return $this->getTargetCaseReflectionAnnotation(Color::class)?->value;}
}
以上就是我对注解的实际应用。当然再hyperf 框架中,注解实际上被赋予了更多的含义(如自动注入等高级功能,类似java的spring容器了)
总结
以前总觉得php 语言开发大型项目并不是很适合,但现在php8出来后,个人觉得php8越来越适合开发大型项目,祝php越来越好,能够再众多的开发语言中再次脱颖而出。php是世界上最好的语言~