在服务请求上处理可选参数的正确方法是什么?
假设在这种情况下,我还希望将$title
作为可选参数
<?php
namespace Lw\Application\Service\Wish;
class AddWishRequest
{
private $userId;
private $email;
private $content;
public function __construct($userId, $email, $content)
{
$this->userId = $userId;
$this->email = $email;
$this->content = $content;
}
public function userId()
{
return $this->userId;
}
public function email()
{
return $this->email;
}
public function content()
{
return $this->content;
}
}
[C0中的示例
通常在DDD中并且还遵循纯净代码规则,如果您有可选参数,则有多个构造函数,在这种情况下,有两个:
仅用于强制性参数。
所有参数之一,包括可选参数,但在此构造函数中,它也是必需的。
如果要构造不带可选参数的对象,则调用第一个。如果要提供一个非null的可选参数,请使用第二个。
通常,您应该使用带有有意义名称的工厂方法,并隐藏构造函数。
AddWishRequest.create(userId,电子邮件,内容)
[AddWishRequest.createWithTitle(userId,电子邮件,内容,标题)
您可以在任何函数调用中以及构造函数中使用可选参数。最好的做法是,先让吸气剂“得到”。
here
表示,$ title是一个可选参数。如果未提供,则将其设置为空字符串。您还可以提供其他任何类型或值。
public function __construct($userId, $email, $content, $title = "")
更新
如果您只声明一个属性,如
namespace Lw\Application\Service\Wish;
class AddWishRequest
{
private $userId;
private $email;
private $content;
private $title;
public function __construct($userId, $email, $content, $title = "")
{
$this->userId = $userId;
$this->email = $email;
$this->content = $content;
$this->title = $title;
}
public function getUserId()
{
return $this->userId;
}
public function getEmail()
{
return $this->email;
}
public function getContent()
{
return $this->content;
}
public function getTitle()
{
return $this->title;
}
}
然后通过private $property
访问它始终为null(直到您设置一个值)。您应该让getter负责返回正确的值。
以下示例将始终使用NULL-coalesce运算符返回一个数组:
$this->property