zoukankan      html  css  js  c++  java
  • 读《深入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();
    ?>




  • 相关阅读:
    manjaro 安装mysql
    Ubuntu安装Redis
    Ubuntu安装docker
    VirtualBox 安装 Ubuntu虚拟机 显卡驱动
    ubuntu 卸载软件
    Linux下环境变量设置的三种方法:
    error: open of glibc-devel-2.12-1.132.el6.i686.rpm failed: 没有那个文件或目录
    ip地址0.0.0.0与127.0.0.1的区别(转载)
    cmake的安装和卸载
    qmake 提示 Failure to open file:****
  • 原文地址:https://www.cnblogs.com/red-code/p/5288637.html
Copyright © 2011-2022 走看看