https://github.com/winwin-inc/mapper-generator
Object mapping code generator
https://github.com/winwin-inc/mapper-generator
generator mapper tool
Last synced: 5 months ago
JSON representation
Object mapping code generator
- Host: GitHub
- URL: https://github.com/winwin-inc/mapper-generator
- Owner: winwin-inc
- Created: 2020-09-15T03:00:32.000Z (almost 6 years ago)
- Default Branch: master
- Last Pushed: 2023-05-08T02:35:20.000Z (about 3 years ago)
- Last Synced: 2025-08-03T07:49:10.986Z (11 months ago)
- Topics: generator, mapper, tool
- Language: PHP
- Homepage:
- Size: 115 KB
- Stars: 0
- Watchers: 2
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Generate mapper class code
受 [mapstruct](https://mapstruct.org/) 项目启发,移植相关功能。
## 简介
项目中模型包括 DO(Data Object), DTO (Data Transfer Object), VO (View Object) 等,经常需要在模型之间进行转换,模型转换的过程称为 mapping ,包含 mapping 函数的类称为 mapper。编写 mapper 是非常枯燥,而且容易出错的过程。通过代码生成,可以简化 mapper 类的编写。
## 安装
```bash
composer require --dev winwin/mapper-generator
```
## 快速开始
假如我们项目中有如下类定义:
```php
setMake($car->getMake());
$carDto->setSeatCount($car->getNumberOfSeats());
$carDto->setType($car->getType() === null ? null : $car->getType()->name);
return $carDto;
}
}
```
## 生成器原理
只有使用 `@\winwin\mapper\annotations\Mapper` 注解标记的类才会进行代码生成。代码生成过程使用 [PHP Parser](https://github.com/nikic/PHP-Parser) 解析代码为 AST,替换需要 mapping 函数的方法体。可以确保只修改 mapping 函数部分,而其他函数仍保持不变。
这个类中符合以下特征的方法会生成 mapping 函数体:
- 必须是 public 实例方法 (即不能是 static 方法)
- 函数原型满足以下情况:
1. 一个参数,一个返回值,且都有类型声明。此时参数为转换来源对象,返回值为转换生成对象。
例如:
```php
getNumberOfSeats()>20")
*/
public function carToCarDto(\Car $car) : \CarDto
{
}
}
```
`qualifiedByName`用于指定 mapper 类中的方法进行转换,例如:
```php
20;
}
}
```
`condition` 用于设置一个表达式,当满足表达式值的时候才进行转换,例如:
```php
0")
*/
public function carToCarDto(\Car $car) : \CarDto
{
}
}
```