这个模式首要由 呼吁类、用户哀求数据类、营业逻辑类、呼吁类工场类及挪用类组成,各个类的浸染归纳综合如下:
1、呼吁类:挪用用户哀求数据类和营业逻辑类;
2、用户哀求数据类:获取用户哀求数据及生涯靠山处理赏罚后返回的功效;
3、营业逻辑类:如以下的示例中验证用户登岸信息是否正确的成果等;
4、呼吁工场类(我本身取的名字,哈哈):天生呼吁类的实例,这个类第一次看的时辰我认为有点屌,虽然看了几遍了照旧认为很屌 :);
5、挪用类:挪用呼吁类,天生视图;
直接看代码:
class LoginCommand extends Command{ //处理赏罚用户登岸信息的呼吁类
function execute (CommandCotext $context){ //CommandCotext 是一个处理赏罚用户哀求数据和靠山回馈数据的类
$manager = Registry::getAccessManager(); //原文代码中并没有详细的实现,但声名白这是一个处理赏罚用户登岸信息的营业逻辑类
$user = $context->get('username');
$pass = $context->get('pass');
$user_obj = $manager->login($user,$pass);
if(is_null($user_obj)){
$context->setError($manager->getError);
return false;
}
$context->addParam('user',$user_obj);
return true; //用户登岸乐成返回true
}
}
class FeedbackCommand extends Command{ //发送邮件的呼吁类
function execute(CommandContext $context){
$msgSystem = Registry::getMessageSystem();
$email = $context->get('email');
$msg = $context->get('msg');
$topic = $context->get('topci');
$result = $msgSystem->send($email,$msg,$topic);
if(!$result){
$context->setError($msgSystem->getError());
return false;
}
return true;
}
}
//用户哀求数据类
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;
}
}
//呼吁类工场,这个类按照用户哀求数据中的action来天生呼吁类
class CommandNotFoundException extends Exception {}
class CommandFactory {
private static $dir = 'commands';
static function getCommand($action='Default'){
if(preg_match('/w',$action)){
throw new Exception("illegal characters in action");
}
$class = UCFirst(strtolower($action))."Command";
$file = self::$dir.DIRECTORY_SEPARATOR."{$class}.php"; //DIRECTORY_SEPARATOR代表'/',这是一个呼吁类文件的路径
if(!file_exists($file)){
throw new CommandNotFoundException("could not find '$file'");
}
require_once($file);
if(!class_exists($class)){
throw new CommandNotFoundException("no '$class' class located");
}
$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(!$comd->execute($this->context)){
//处理赏罚失败
} else {
//乐成
// 分发视图
}
}
}
// 客户端
$controller = new Controller();
//伪造用户哀求,真实的场景中这些参数应该是通过post或get的方法获取的,貌似又空话了:)
$context = $controller->getContext();
$context->addParam('action','login');
$context->addParam('username','bob');
$context->addParam('pass','tiddles');
$controller->process();
以上这篇老生常谈PHP面向工具之呼吁模式(必看篇)就是小编分享给各人的所有内容了,但愿能给各人一个参考,也但愿各人多多支持编程之家。 (编辑:湖南网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|