воскресенье, 3 февраля 2013 г.

паттерн command php

паттерн command php

реализация



";
//////////////////////////////////////////////

abstract class Command {
	abstract function execute( CommandContext $context );
}

class LoginCommand extends Command{
	function execute( CommandContext $context ){
		$user = $context->get('username');
		$pass = $context->get('pass');
                Loger::write("enter user: ".$user);
		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;
	}
}

class CommandNotFoundException extends Exception {}

class CommandFactory {
	private static $dir = "commands";
	static function getCommand($action = 'default'){
		if (preg_match('/\W/', $action )){
			throw new CommandNotFoundExceptioin('Недопустимые символы в комманде'); 
		}
		$class=$action."Command";
		/*//времено
		//возможен иклюдинг предусмотреть
		$class = $action.".ph
		$file = self::$dir.DIRECTORY_SEPARATOR
		if (!file_exists($file)){
			throw new CommandNotFoundExceptioin('не найден файл '.$file); 
		}
		require_once( $file );
		*/
		if(!class_exists($class)){
			throw new CommandNotFoundExceptioin('не найден класс '.$class); 
		}
		$cmd = new $class();
		return $cmd;
	}
}

class Controller {
	private $context;
	function __construct(){
		$this->context = new CommandContext();
	}
	function getContext(){
		return $this->context;
	}
	function process(){
                //var_dump( $this->context->get('action') );
		$cmd = CommandFactory::getCommand( $this->context->get('action') );
		if ( !$cmd->execute($this->context) ){
			//обработка ошибок
		}else{
			//все прошло успешно
			//Теперь отобразим результаты
		}
	}	
}


$controler = new Controller();
//эмулируем действия пользователя
$context = $controler->getContext();
$context->addParam('action', 'Login');
$context->addParam('username', 'jo');
$context->addParam('pass', '1');
$controler->process();


?>

Комментариев нет:

Отправить комментарий

PHP: The Right Way блог програмышки
Яндекс.Метрика