클라이언트 코드에서 조건 문을 제거하십시오
.
(공간 제한으로 인해 원본 텍스트의 FAQ 부분은 여기에서 생략됩니다.)
<code class="language-php"><?php namespace Model;
interface UserInterface
{
public function setId($id);
public function getId();
public function setName($name);
public function getName();
public function setEmail($email);
public function getEmail();
}</code>
<code class="language-php"><?php namespace Model;
class User implements UserInterface
{
private $id;
private $name;
private $email;
public function __construct($name, $email) {
$this->setName($name);
$this->setEmail($email);
}
public function setId($id) {
if ($this->id !== null) {
throw new BadMethodCallException(
"The ID for this user has been set already.");
}
if (!is_int($id) || $id throw new InvalidArgumentException(
"The ID for this user is invalid.");
}
$this->id = $id;
return $this;
}
public function getId() {
return $this->id;
}
public function setName($name) {
if (strlen($name) 30) {
throw new InvalidArgumentException(
"The user name is invalid.");
}
$this->name = $name;
return $this;
}
public function getName() {
return $this->name;
}
public function setEmail($email) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException(
"The user email is invalid.");
}
$this->email = $email;
return $this;
}
public function getEmail() {
return $this->email;
}
}</code>
<code class="language-php"><?php namespace ModelMapper;
use LibraryDatabaseDatabaseAdapterInterface,
ModelUser;
class UserMapper implements UserMapperInterface
{
private $adapter;
public function __construct(DatabaseAdapterInterface $adapter) {
$this->adapter = $adapter;
}
public function fetchById($id) {
$this->adapter->select("users", array("id" => $id));
if (!$row = $this->adapter->fetch()) {
return null;
}
return $this->createUser($row);
}
private function createUser(array $row) {
$user = new User($row["name"], $row["email"]);
$user->setId($row["id"]);
return $user;
}
}</code>
<code class="language-php"><?php use LibraryLoaderAutoloader,
LibraryDatabasePdoAdapter,
ModelMapperUserMapper;
require_once __DIR__ . "/Library/Loader/Autoloader.php";
$autoloader = new Autoloader;
$autoloader->register();
$adapter = new PdoAdapter("mysql:dbname=test", "myusername", "mypassword");
$userMapper = new UserMapper($adapter);
$user = $userMapper->fetchById(1);
if ($user !== null) {
echo $user->getName() . " " . $user->getEmail();
}</code>
완전한 엔티티 클래스가 모든 종류의 장식을 포장 할 것으로 예상되면 아마도 실망했을 것입니다. 엔티티의 "NULL"버전은 해당 인터페이스를 준수하지만 메소드는 빈 래퍼이며 실제 구현이 없습니다. Nulluser 클래스의 존재는 분명히 우리에게 칭찬을받을 가치가있는 것을 가져 오지 않지만, 그것은 우리가 이전의 모든 조건 진술을 쓰레기에 던질 수있게하는 간결한 구조입니다. 그것이 어떻게 구현되는지보고 싶습니까? 먼저, 사전 작업을 수행하고 데이터 맵퍼를 재구성하여 Finder가 빈 값 대신 빈 사용자 객체를 반환하도록해야합니다. <code class="language-php"><?php namespace Model;
interface UserInterface
{
public function setId($id);
public function getId();
public function setName($name);
public function getName();
public function setEmail($email);
public function getEmail();
}</code>
<code class="language-php"><?php namespace Model;
class User implements UserInterface
{
private $id;
private $name;
private $email;
public function __construct($name, $email) {
$this->setName($name);
$this->setEmail($email);
}
public function setId($id) {
if ($this->id !== null) {
throw new BadMethodCallException(
"The ID for this user has been set already.");
}
if (!is_int($id) || $id throw new InvalidArgumentException(
"The ID for this user is invalid.");
}
$this->id = $id;
return $this;
}
public function getId() {
return $this->id;
}
public function setName($name) {
if (strlen($name) 30) {
throw new InvalidArgumentException(
"The user name is invalid.");
}
$this->name = $name;
return $this;
}
public function getName() {
return $this->name;
}
public function setEmail($email) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new InvalidArgumentException(
"The user email is invalid.");
}
$this->email = $email;
return $this;
}
public function getEmail() {
return $this->email;
}
}</code>
결론
위 내용은 PHP 마스터 | 널 객체 패턴 - 도메인 모델의 다형성의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!