读《深入php面向对象、模式与实践》有感(三)

命令模式:

第一次接触到这个命令模式的时候,感觉它很像一个简化的mvc框架。从不同的路径访问,再由控制器来判断所要调用的具体php文件。



<?php

class CommandContext{   //"命令容器"
    private $params = array();

    function addParam($key,$val){
        $this->params[$key] = $val;
    }

    function getParam($key){
        return $this->params[$key];
    }
}

class Controller{
    private $cmdContext;

    function __construct(){
        $this->cmdContext = new CommandContext();
    }

    //
    function getCmdContext(){
        return $this->cmdContext;
    }

    function process(){
        $action = $this->cmdContext->getParam("action");   //通过命令容器获得命令
        $command = CommandFactory::getCommand($action);   //命令传给命令工厂,得到命令所对应的子command类对象
        if($command->execute($this->cmdContext)){//调用子类对象的execute方法并判断
            //成功
            //调用对应视图
        }else{
            //失败
        }
    }
}

class CommandFactory{
    static function getCommand($cmd){
        $file = 'commands/'.$cmd.'Command.php'; //命令所对应的php文件路径

        if(! file_exists($file)){
            throw new Exception("Could not find file $file");
        }

        require_once($file);

        $class = $cmd.'Command';    //形成类名
        if(! class_exists($class)){
            throw new Exception("Could not find class $class");
        }

        $result = new $class();
        return $result;
    }
}

//commands文件夹内
abstract class Command{
    abstract function execute(CommandContext $commandContext);
}

class demoCommand extends Command{
    function execute(CommandContext $commandContext){
        return "ok";
    }
}

//使用代码
$controller = new Controller();
$cmdContext = $controller->getCmdContext();

$cmdContext->addParam("action","demo");
$demo = $controller->process();
?>



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值