使用DTO进行方法间的数据传输

使用DTO进行方法间的数据传输

工作中经常会遇到方法需要的参数很多的情况。以下拿php举栗

以往的弊端

很多情况下是直接一个个形参列举开来,但往往很难维护或者阅读代码:

public function supplementContract(string $appId, string $ecid, string $mtchId, string $certNo, string $name, string $file, int $type = 2)
{
...
}

又或者数组传参,但往往又不能保证数组内的值是否规范,而需要再在方法中验证,徒增烦恼:

public function createInvoice(array $requestData)
{
$this->validation($requestData, [
'taxInclusiveTotalAmount' => 'required',
'invoiceType' => 'required|in:004,007,026,027',
'goodsName' => 'required',
'adresseeName' => 'required',
'adresseePhone' => 'required',
'provinceName' => 'required',
'cityName' => 'required',
'areaName' => 'required',
'detailedAddress' => 'required',
'address' => 'required',
'telephone' => 'required',
'openningBank' => 'required',
'accountBank' => 'required',
], [
'taxInclusiveTotalAmount.required' => '价税合计必填',
'invoiceType.required' => '发票类型必填',
'invoiceType.in' => '发票类型非法,仅支持004:专票, 007:普票, 026:电子普票, 027:电子专票',
'goodsName.required' => '开票项目必填',
'adresseeName.required' => '收件人姓名必填',
'adresseePhone.required' => '收件人电话必填',
'provinceName.required' => '省名称必填',
'cityName.required' => '市名称必填',
'areaName.required' => '区名称必填',
'detailedAddress.required' => '详细地址必填',
'address.required' => '发票抬头地址必填',
'telephone.required' => '发票抬头电话必填',
'openningBank.required' => '发票抬头开户行必填',
'accountBank.required' => '发票抬头银行账号必填',
]);
...
}

此时,DTO就可以很好的解决这个问题;

什么是DTO

DTO即Data Transfer Object(数据传输对象)的简称。

我们可以搭配spatie家的data-transfer-object来实现。

composer require spatie/data-transfer-object
class UserDTO extends \Spatie\DataTransferObject\DataTransferObject
{
public string $name;

public string $age;

public string $company;
}
$user = new UserDTO([
'name' => 'Tom',
'age' => '18',
'company' => '996',
]);
// 将$user作为参数传递即可
echo $user->$name;
// 'tom'
var_dump($user->toArray());
//array(3) {
// ["name"]=>
// string(3) "Tom"
// ["age"]=>
// string(2) "18"
// ["company"]=>
// string(3) "996"
//}

更多data-transfer-object用法,前往其github查看