php 命令模式,客户端发出命令,commandfactory接收命令,commandcontext处理数据,logincommand执行命令

这里是代码1,取名是command.php

<?php
//处理数据信息
class CommandContext{
	private $params=array();
	private $error="";
	function __construct(){
		$this->params=$_REQUEST;
	}
	function addParam($key,$val){
		$this->params[$key]=$val;
	}
	function get($key){
		return $this->params[$key];
	}
	function setError($error){
		$this->error=$error;
	}
	function getError(){
		return $this->error;
	}
}
class CommandNotFoundException extends Exception{}
//接收者,接收命令
class CommandFactory{
	private static $dir="commands";
	static function getCommand($action='Default'){
		if(preg_match("/\W/",$action)){
			throw new Exception("含有非法字符");
		}
		$class =ucfirst(strtolower($action))."Command";
		$file=self::$dir.DIRECTORY_SEPARATOR."{$class}.php";
		if(!file_exists($file)){
			throw new CommandNotFoundException("没有找到文件");
		}
		require_once($file);
		if(!class_exists($class)){
			throw new CommandNotFoundException("没有找到相应的类");
		}
		$cmd=new $class();
		return $cmd;
	}
}
//调用者,发出命令
class Controller{
	private $context;
	function __construct(){
		$this->context=new CommandContext();
	}
	function getContext(){
		return $this->context;
	}
	function process(){
		$cmd=CommandFactory::getCommand($this->context->get('action'));
		if(!$cmd->execute($this->context)){
			echo "处理失败";
		}else{
			echo "处理成功";
		}
	}
}
$controller=new Controller();
$context=$controller->getContext();
$context->addParam('action','login');
$context->addParam('username','bob');
$context->addParam('pass','123456');
$controller->process();

这里是代码2,取名为LoginCommand.php,必须取这个名字,放在文件夹commands里面,因为上面addParam(‘action’,‘login’)的命令是访问前缀为login的文件

<?php
abstract class Command{
	abstract function execute(CommandContext $context);
}
//执行者
class LoginCommand extends Command{
	function execute(CommandContext $context){
		$manager=Registry::getAccessManager();
		$user=$context->get('username');
		$pass=$context->get('pass');
		$user_obj=$manager->login($user,$pass);
		if(empty($user_obj)){
			$context->setError($manager->getError());
			return false;
		}
		$context->addParam("user",$user_obj);
		return true;
	}
}
//管理者
class Registry{
	private static $instance;
	private $user;
	private $pass;
	public $logarray=array();
	static function getAccessManager(){
		if(empty(self::$instance)){
			self::$instance=new self();
		} 
		return self::$instance;
	}
	function login($user,$pass){
		if(!empty($user) && !empty($pass)){
			$this->user=$user;
			$this->pass=$pass;
			array_push($this->logarray,$this->user,$this->pass);
		}
		return $this->logarray;
	}
	function getError(){
		echo "用户名和密码不能为空";
	}
}
?>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值