功能:
給指定用戶發送郵件
將客戶端ip寫入ftp防火牆白名單
為什么要用命令模式實現?策略模式,狀態模式難道不可以嗎?
此處給用戶發郵件和將IP寫入白名單是兩個不同的操作.
策略模式是不同策略可以相互替換,這兒顯然不能替換,因為對應的功能不同.
命令請求者內部沒有維護一個狀態的必要.所以狀態模式也不適應.
一.命令接口
abstract class SystemCommandInterface
{
protected $receiver;
public function __construct(ReceiverInterface $receiver)
{
$this->receiver = $receiver;
}
abstract public function execute(array $params);
abstract public function log(array $params);
}
二.具體命令
1.發送郵件命令
/**
* 發送郵件
* Class SendEmail
*/
class SendEmail extends SystemCommandInterface
{
public function execute(array $params)
{
$this->log($params);
return $this->receiver->action($params);
}
public function log(array $params)
{
echo "向{$params['email']}發送了郵件<br/>";
}
}
2.ip寫入ftp白名單命令
/**
* 接受ftp 客戶端IP
*/
class AcceptFTPClientIp extends SystemCommandInterface
{
public function execute(array $params)
{
$this->log($params);
return $this->receiver->action($params);
}
public function log(array $params)
{
echo "請求接受ftp 客戶端IP: {$params['ip']}<br/>";
}
}
三.命令接受者
1.接口
interface ReceiverInterface
{
public function action(array $params);
}
2.發送郵件命令接受者
/**
* Class SendMailReceiver
*/
class SendMailReceiver implements ReceiverInterface
{
public function action(array $params)
{
/**
* 發送郵件
* ..........
* ........
*/
return true;
}
}
3.接受ip命令接受者
class AcceptFTPClientIpReceiver implements ReceiverInterface
{
public function action(array $params)
{
/**
* 將請求的ip寫入ftp ip 白名單
* ..........
* ........
*/
return false;
}
}
四.命令請求者
/**
* 命令請求者
* Class Invoker
*/
class Invoker
{
private $systemCommandS = [];
public function setCommands($key, SystemCommandInterface $commandInterface)
{
if (!isset($this->systemCommandS[$key])) {
$this->systemCommandS[$key] = $commandInterface;
}
}
public function call($key, $params)
{
$this->systemCommandS[$key]->execute($params);
}
}
五.調用
$sendMailCommand = new SendEmail(new SendMailReceiver());
$acceptFTPClientIpCommand = new AcceptFTPClientIp(new AcceptFTPClientIpReceiver());
$invoker = new Invoker();
$invoker->setCommands('send_email', $sendMailCommand);
$invoker->setCommands('accept_ftp_client_ip', $acceptFTPClientIpCommand);
$invoker->call('send_email', ['email' => 'example@mail.com']);
$invoker->call('accept_ftp_client_ip', ['ip' => '127.0.0.1']);
