php8泛型的体现:
<?php
namespace App\Model\Dto\Mapper;
use App\Model\Dto\Interface\ResponsibleInterface;
/**
* @template TResponsibleInterface of ResponsibleInterface
* @template TMapperDtoInterface of MapperDtoInterface
*/
interface MapperInterface
{
/**
* @param TMapperDtoInterface $data
*
* @return TResponsibleInterface
*/
public function toDto(MapperDtoInterface $data): ResponsibleInterface;
/**
* @param array<TMapperDtoInterface> $data
*
* @return array<TResponsibleInterface>
*/
public function toListDto(array $data): array;
}
关于 `@template` 标签:
1. 这是 PHP 文档注解(Docblock)中的特性,不完全属于 PHP 8 的语法特性
2. 作用是为泛型提供类型注解和文档说明
- 帮助开发者理解接口或类的泛型约束
- 为 IDE 和静态分析工具提供类型提示
- 增强代码的类型安全性和可读性
3. 示例中的 `@template` 声明了两个泛型类型:
- `TResponsibleInterface`:受限于必须实现 `ResponsibleInterface`
- `TMapperDtoInterface`:受限于必须实现 `MapperDtoInterface`
4. 语法格式:`@template 泛型名称 [of 约束类型]`
这是一种文档和类型注解,提高代码的类型安全性和可读性。
/**
* @implements MapperDtoInterface<Country>
*/
#[ORM\Entity]
#[ORM\Table(name: "country")]
class Country implements MapperDtoInterface
{
}
怎么理解 @implements MapperDtoInterface<Country>
`@implements MapperDtoInterface<Country>` 是一种泛型注解,表示 `Country` 类实现了 `MapperDtoInterface` 接口,并且具体的泛型类型是 `Country` 本身。
这意味着:
1. `Country` 类遵守 `MapperDtoInterface` 的契约
2. 在接口的泛型定义中,`Country` 同时作为输入和输出类型
3. 提供给 IDE 和静态分析工具的类型信息
4. 增强代码的类型安全性和可读性
这是 PHP 中通过注解模拟泛型的一种方式。
解释:
在这个场景中,"同时作为输入和输出类型"意味着:
1. 输入:`Country` 可以作为数据传输对象(DTO)的类型
2. 输出:`Country` 也可以是最终返回的对象类型
例如,在映射器中,你可以:
- 将 `Country` 作为输入 DTO
- 经过转换后,仍然返回 `Country` 对象
这种注解提供了类型一致性的保证和更清晰的接口定义。
