这里是代码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 "用户名和密码不能为空";
}
}
?>