功能:
给指定用户发送邮件
将客户端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‘ => ‘[email protected]‘]); $invoker->call(‘accept_ftp_client_ip‘, [‘ip‘ => ‘127.0.0.1‘]);