读《深入php面向对象、模式与实践》有感(三)
2016-03-05 21:05
671 查看
命令模式:
第一次接触到这个命令模式的时候,感觉它很像一个简化的mvc框架。从不同的路径访问,再由控制器来判断所要调用的具体php文件。
![](http://img.blog.csdn.net/20160305210454312?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQv/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center)
第一次接触到这个命令模式的时候,感觉它很像一个简化的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(); ?>
相关文章推荐
- php变量
- 测试LFI WITH PHPINO过程中的一些记录
- 在Yii2中使用Pjax导致Yii2内联脚本载入失败的问题
- PHP正则表达式
- $smarty->display('index2.tpl');
- 酷狗音乐(繁星网)PHP岗位笔试题
- php实现一个单链表
- PHP实现页面静态化——局部动态化
- php 获取地址栏参数
- PHP spl_autoload和class_exsits使用技能
- CakePHP 3.2 数据库访问和ORM篇
- PHP 图片上传生成缩略图代码
- PHP 中实现GZIP压缩页面输出实例
- PHP 读取数据库内容并以二维数组按指定列输出实例
- CakePHP3.2 文件接口篇
- vsftpd配置文件讲解
- 适用于 php-5.2 的 php.ini 中文版
- ThinkPHP函数详解:C方法
- PHP - __clone 对象克隆
- 新版thinkphp3.2使用模板主题的方法