이전에는 생성자 내에서 내 개체의 유효성 검사를 수행했으며 유효성 검사가 실패하면 예외가 발생했습니다. 예를 들어 :알림 패턴을 사용하여 도메인 유효성 검사
내 객체가 일관성을 시행하고이를 보장 할 책임이있다 나는이 방법을 좋아하는 동안class Name
{
const MIN_LENGTH = 1;
const MAX_LENGTH = 120;
private $value;
public function __construct(string $name)
{
if (!$this->isValidNameLength($name)) {
throw new InvalidArgumentException(
sprintf('The name must be between %d and %d characters long', self::MIN_LENGTH, self::MAX_LENGTH)
);
}
$this->value = $name;
}
public function changeName(string $name)
{
return new self($name);
}
private function isValidNameLength(string $name)
{
return strlen($name) >= self::MIN_LENGTH && strlen($name) <= self::MAX_LENGTH;
}
}
은 항상 유효합니다, 나는 예외의 사용에 대해 지나치게 열정적 적이 없습니다. 위와 같이 예외 사용을 반대하는 사람들이 있지만 여러 객체에 대해 유효성 검사를 수행 할 때 반환 할 수있는 유효성 검사 메시지의 수는 제한됩니다. 예를 들어 :
class Room
{
private $name;
private $description;
public function __construct(Name $name, Description $description)
{
$this->name = $name;
$this->description = $description;
}
}
class Name
{
public function __construct(string $name)
{
// do some validation
}
}
class Description
{
public function __construct(string $description)
{
// do some validation
}
}
모두 Name
및 Description
이 유효성 검사에 실패한 경우, 나는 두 개체에 대한 개체가 첫 번째 실패 중에서 단지 하나의 예외 오류 메시지를 반환 할 수 있어야합니다.
notification pattern에서 약간의 독서를 했더니 내 시나리오에 잘 어울리는 것 같았습니다. 내가 붙어있는 곳은 유효성 검증을 수행하는 방법이며, 유효성 검사가 실패하면 유효하지 않은 상태로 들어가는 것을 방지합니다.
class Name
{
const MIN_LENGTH = 1;
const MAX_LENGTH = 120;
private $notification;
private $value;
public function __construct(string $name, Notification $notification)
{
$this->notification = $notification;
$this->setName($name);
}
private function setName(string $name)
{
if ($this->isValidNameLength($name)) {
$this->value = $name;
}
}
private function isValidNameLength(string $name)
{
if (strlen($name) < self::MIN_LENGTH || strlen($name) > self::MAX_LENGTH) {
$this->notification->addError('NAME_LENGTH_INVALID');
return false;
}
return true;
}
public function hasError()
{
return $this->notification->hasError();
}
public function getError()
{
return $this->notification->getError();
}
}
내가 위의 대한 몇 가지 문제가 있습니다 유효성 검사가 실패 할 경우
- 를 다음 개체가 아직 구성되어 있지만
$value
는 유효한 상태하지 않은null
이다. Name
을 생성 한 후hasError
으로 전화하여 유효성 검사 오류가 발생했는지 확인해야합니다.- 지금 내 도메인 개체를
hasError
/getError
기능으로 조정하고 있는데 잘 모르겠습니다.
누락 된 퍼즐이 있습니까? 알림 패턴을 어떻게 활용할 수 있습니까?하지만 객체가 유효하지 않은 상태로 들어 가지 않도록 할 수 있습니까?
'Factory'는 어떤 객체,'Room'? 이'RoomFactory (문자열 이름, 문자열 설명)'에서'Name'과'Description' 객체를 만들고 각각에 대해 'hasError'를 검사하여 유효성을 확인합니다. 그것은 여전히 잘못된 불변량을 허용하지 않습니까? – Unflux