您好,欢迎访问一九零五行业门户网

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

命令模式:
第一次接触到这个命令模式的时候,感觉它很像一个简化的mvc框架。从不同的路径访问,再由控制器来判断所要调用的具体php文件。
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面向对象、模式与实践》有感(三),包括了方面的内容,希望对php教程有兴趣的朋友有所帮助。
其它类似信息

推荐信息