<?php
class State
{
/**
* @var string 数据库的字段状态值
*/
private $state;
public $delegate;
public function __construct($object, $state) {
$this->delegate = $object;
$this->ensureIsValidState($state);
}
public function getStateList() {
return $this->delegate->getStateList();
}
private function ensureIsValidState($state) {
if (!array_key_exists($state, $this->getStateList())) {
throw new \InvalidArgumentException('Invalid state given parameter');
}
$this->state = $state;
}
/**
* 获取英文名
* @return string
*/
public function name() {
$state_list = $this->getStateList();
return key($state_list[$this->state]);
}
//将不同的状态业务逻辑放对应的类文件中处理
public function createObject() {
$object = get_class($this->delegate) . ucfirst($this->name()) . "State";
return new $object;
}
/**
* 获取中文名
* @return string
*/
private function display() {
$state_list = $this->getStateList();
return $state_list[$this->state][$this->name()];
}
public function __toString() {
return $this->display();
}
}
代理模式,状态模式。 调用
<?php
class Orders
{
const STATE_CREATED = 1;
const STATE_CLOSED = 2;
/**
* @var array
*/
public static $validStates = [
self::STATE_CREATED => ['created' => '创建'],
self::STATE_CLOSED => ['closed' => '关闭'],
];
public static function getStatus() {
return new State(new self, 1);
}
public function getStateList() {
return static::$validStates;
}
}
echo Orders::getStatus()->name();
echo Orders::getStatus()->createObject();