根据要求可选参数 class

Optional parameters on request class

在服务请求中处理可选参数的正确方法是什么?

假设在这种情况下我还想将 $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;
    }
}

示例来自 here

您可以在任何函数调用中使用可选参数,也可以在构造函数中使用。最佳做法是,在 "get" 之前到 getters.

public function __construct($userId, $email, $content, $title = "")

表示,$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

然后通过 $this->property 访问它并且始终为 null(直到您设置一个值)。您应该让 getter 负责 return 正确的值。

以下示例将始终 return 一个使用 NULL 合并运算符的数组:

  • 如果 $something 为真(或具有数组内容)将 return $something
  • 否则将return空数组
public function getSomething() : array {
  return $this->something ?? [];
}

通常在 DDD 中也遵循干净代码的规则,如果你有可选参数,你有多个构造函数,在这种情况下有两个:

  • 一个仅用于强制参数。

  • 一个用于所有参数,包括可选参数,但在此构造函数中它也是强制性的。

如果你想构造 object 没有可选参数你调用第一个。如果你想提供一个非空的可选参数,你可以使用第二个。

通常你应该使用具有有意义名称的工厂方法,并隐藏构造函数。

AddWishRequest.create(用户 ID、电子邮件、内容)

AddWishRequest.createWithTitle(用户 ID、电子邮件、内容、标题)