SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Guru whisher's Avatar
    Join Date
    May 2006
    Location
    Kakiland
    Posts
    732
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Url mapper. Asking for advice.

    Hi.
    Sorry for the subject and for
    the classes name as well (I don't know
    if they are completely suitable to the task)

    I'm looking for a quick and flexible
    way to build up my applications,
    so I ended up with this (is the first rough
    draft)

    PHP Code:
    <?php
    error_reporting
    (E_ALL E_STRICT);
    /**
     * include exceptions_error_handler
     * include debug_exception_handler
     * include __autoload
     * include w_utilities_RemoveMagicQuotes
     * 
     * /
    /***************************************
    Start framework
    ***************************************/
     
    class w_config{
         private static 
    $instancenull;
        private 
    $config= array('absoluteUrl'=>false);
        private function 
    __construct() {}
         private static function 
    instance(){
            if (!isset(
    self::$instance)) {
                 
    $c __CLASS__;    
                   
    self::$instance = new $c;
            }
            return 
    self::$instance;
        }
        static public function 
    get($var) {
            return 
    self::instance()->$var;
        }
        private function 
    __get($var){
            if (isset( 
    $this->config[$var])){
                return 
    $this->config[$var];
            }
            return 
    null;
        }
    }

    /**
    * Get the query string.
    * Strategy to supply query string to w_http_Request 
    */
    abstract class  w_Router 
    {
        protected 
    $routeParts= array();
        protected 
    $queryString'';
        public function 
    __construct(){
            
    $this->routeParts$this->get();
        }
        protected function 
    isValid($key){
            return isset(
    $this->routeParts[$key]) && !empty($this->routeParts[$key]);
        }
        public function 
    controller(){
            return (
    $this->isValid(0))?$this->routeParts[0]:null;
        }
        public function 
    command(){
            return (
    $this->isValid(1))?$this->routeParts[1]:null;
        }
        public function 
    paramaters(){
            
    $parametersarray_slice($this->routeParts2); 
            return !empty(
    $parameters)?$parameters:array();
        }
        public function 
    queryString(){
            return 
    $this->queryString;
        }
        abstract public function 
    get();
    }
    /**
     * Get the really query string.
     * At the moment manage with a single get
     * key 'qs' also set in the .htaccess file 
     * RewriteRule ^([a-zA-Z0-9_\-\/]+)$ index.php?qs=$1 
    */
    class w_ExplitRouter extends w_Router
    {
        protected 
    $getKey'qs';
        protected 
    $pattern'#^[a-zA-Z0-9_\-\/]+$#';
        public function 
    __construct(){
            
    parent::__construct();
        }
        public function 
    parseQueryString(){
            if(
    filter_has_var(INPUT_GET$this->getKey)){
                
    $options= array('options'=>array('regexp'=>$this->pattern));
                return 
    filter_input(INPUT_GET$this->getKeyFILTER_VALIDATE_REGEXP$options);
            }    
            return 
    false;
        }
        public function 
    get(){
            
    $queryString$this->parseQueryString();
            if(!empty(
    $queryString)){
                
    $this->queryStringtrim($queryString,'/');
                return 
    explode("/",$this->queryString);
            }
            return array();
        }
    }
    /**
     * Manage the http request. 
     */
    class w_http_Request
    {
        
    /**
         * If set to true gives the absolute Url.
         * @var boolean 
         * @default false
         */
        
    public $absoluteUrlfalse;
        
    /**
         * The current site url
         * @var string
         */
        
    protected $root'';
        
    /**
        * @var w_Router
        */
        
    protected $routernull;    
        public function 
    __construct(w_Router $router=null){
            
    $this->router $router $router : new w_ExplitRouter();
            
    $removeMagicQuote= new w_utilities_RemoveMagicQuotes();
            
    $this->setRoot();
        }
        protected function 
    setRoot(){
            
    $protocol= (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == "on")?"https":"http";
            if (isset(
    $_SERVER['HTTP_HOST'])) {
                
    $base rtrim($protocol."://".$_SERVER['HTTP_HOST'], "/");
            } else {
                
    $base $protocol."://".$_SERVER['SERVER_NAME'];
            }
            
    $root rtrim(str_replace("\\""/"dirname($_SERVER['PHP_SELF'])), "/")."/";
            if(
    w_config::get('absoluteUrl')){
                
    $root$base.$root;
            }
            
    $this->root$root;    
        }
        public function 
    isXhr(){
            return (isset(
    $_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH']=='XMLHttpRequest');
        }
        public function 
    root(){
            return 
    $this->root
        }
        public function 
    url(){
            return 
    $this->root.$this->router->queryString(); 
        }
        public function 
    getRouter(){
            return 
    $this->router
        }
    }
    class 
    w_FrontController {
        
    /**
         * @var w_http_Request
         */
        
    protected $requestnull;
        
    /**
         * @var string defaultController 
         * @default controllers_Index 
         */
        
    protected $defaultController'controllers_Index';
        
    /**
         * @var reflection w_controller 
         */
        
    protected static $reflectionControllernull;
        
    /**
         * @var reflection defaultController
         */
        
    protected static $reflectionDefaultControllernull;
        
        public function 
    __construct(w_http_Request $request){
            
    $this->request$request;
            if(!
    self::$reflectionDefaultController){
                try{
                    
    self::$reflectionController= new ReflectionClass('w_Controller');
                    
    /* I'm looking for troubles for the controllers_Index class only*/
                    
    self::$reflectionDefaultController= new ReflectionClass('controllers_Index');
                }
                catch(
    ReflectionException $e){
                    throw new 
    Exception($e->getMessage().' you must set up your controllers_Index');
                }
            }
            
        }
        public function 
    run(){
            
    $controller$this->getController();
            
    // useful during developing 
            // ** remember w_config is it the case ?
            
    $this->checkController($controller);
            
    //$command= $controller->getCommand();
            //$command->execute();
            
    $controller->run();
            
    //var_dump();
        
    }
        protected function 
    getController(){
            
    $controllerName$this->request->getRouter()->controller();
            
    $args= array($this->request);
            if(
    is_null($controllerName)){
                return 
    self::$reflectionDefaultController->newInstanceArgs($args);    
            }
            try{
                
    $controllerName'controllers_'.ucfirst($controllerName);
                 
    $reflectionClass = new ReflectionClass($controllerName);
                 if(
    $reflectionClass->isSubclassOf(self::$reflectionController)){
                    return 
    $reflectionClass->newInstanceArgs($args);
                }
                return 
    self::$reflectionDefaultController->newInstanceArgs($args);
            }
            catch(
    ReflectionException $e){
               return 
    self::$reflectionDefaultController->newInstanceArgs($args);
            }
        }
        protected function 
    checkController(w_Controller $controller){
            
    $allowedCommands$controller->getAllowCommands();
            if(empty(
    $allowedCommands)){
                throw new 
    Exception($controller->getName().' must have a allowed command at least');
            }
        } 
        
    }
    abstract class  
    w_Controller 
    {
        public 
    $request=  null;
        protected 
    $allowCommands= array();
        public function 
    __construct(w_http_Request $request){
            
    $this->request$request;
        } 
        public function 
    getAllowCommands(){
            return 
    $this->allowCommands;
        }
        public function 
    getCommand(){
            
    $controllerName$this->getName();
            
    $commandName$this->request->getRouter()->command();
            
    $defaultCommand'commands_'.$controllerName.'_'.$this->getDefaultCommand();
            if(
    is_null($commandName)){
                return new 
    $defaultCommand($this->request);
            }
            if(
    in_array($commandName,$this->getAllowCommands())){
                
    $command'commands_'.$controllerName.'_'.ucfirst($commandName);
                return new 
    $command($this->request);
            }
            return new 
    $defaultCommand($this->request);
        }
        abstract public function 
    run();
        abstract public function 
    getDefaultCommand(); 
        abstract public function 
    getName();
    }
    /***************************************
    Start Application
    You could do controllers_Index extends controllers_Base extends w_Controller
    ***************************************/
    class controllers_Index extends w_Controller{
        public 
    $request=  null;
        protected 
    $allowCommands=  array('read','insert');
        public function 
    __construct(w_http_Request $request){
            
    parent::__construct($request);
        } 
        public function 
    getDefaultCommand(){
            return 
    'read';    
        }
        public function 
    run(){ 
            
    $command$this->getCommand();
            echo 
    "Run in index</br>";
            
    // if($this->isXhr())){ raw data }
            // else {view}
            
    $command->execute();    
        }
        public function 
    getName(){ 
            return 
    'index';
        } 

    class 
    controllers_Posts extends w_Controller{
        protected 
    $allowCommands=  array('read','insert');
        public function 
    __construct(w_http_Request $request){
            
    parent::__construct($request);
        } 
        public function 
    getDefaultCommand(){
            return 
    'read';    
        }
        public function 
    run(){ 
            
    $command$this->getCommand();
            echo 
    "Run in posts</br>";
            
    $command->execute();    
        }
        public function 
    getName(){ 
            return 
    'posts';
        } 
    }
    class 
    commands_Base{
        protected 
    $requestnull;
        public function 
    __construct(w_http_Request $request){
            
    $this->request$request;
        }
        public function 
    execute(){
            
    // do something may be ;)
        
    }      

    class 
    commands_index_Read extends commands_Base{
        public function 
    __construct(w_http_Request $request){
            
    parent::__construct($request);
        }
        public function 
    execute(){
            echo 
    'commands_index_Read<br>';
        }      
    }
    class 
    commands_index_Insert extends commands_Base{
        public function 
    __construct(w_http_Request $request){
            
    parent::__construct($request);
        }
        public function 
    execute(){
            echo 
    'commands_index_Insert<br>';
        }      
    }
    class 
    commands_posts_Read extends commands_Base{
        public function 
    __construct(w_http_Request $request){
            
    parent::__construct($request);
        }
        public function 
    execute(){
            echo 
    'commands_posts_Read<br>';
        }      
    }
    class 
    commands_posts_Insert extends commands_Base{
        public function 
    __construct(w_http_Request $request){
            
    parent::__construct($request);
        }
        public function 
    execute(){
            echo 
    'commands_posts_Insert<br>';
        }      
    }
    $request= new w_http_Request();
    $f= new w_FrontController($request);
    $f->run();
    ?>
    .htaccess

    PHP Code:
    RewriteEngine on
    RewriteCond 
    $!^(index\.php|images|robots\.txt)
    RewriteCond &#37;{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule 
    ^([a-zA-Z0-9_\.\-\/]+)$ index.php?qs=$
    http://localhost/posts/insert

    I'd like to know your opinion about it.

    Just still arguing with views, Db etc .....
    Bye.
    Last edited by whisher; Dec 21, 2008 at 04:02.

  2. #2
    SitePoint Enthusiast
    Join Date
    Feb 2008
    Posts
    33
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    don't like the idea of a separate class for each potential action on a single logical item.

  3. #3
    SitePoint Member
    Join Date
    Dec 2008
    Posts
    21
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    This is way more complex than something I would use:

    Request: example.org/?Clazz.method&my=input

    Handling:
    central router -> objectOfClazz.call($method,$input) -> objectOfClazz.method($input)

    Naturally, objectOfClazz would be an instance of your controller's subclass. It would inherit the default call() method from the controller, but you would be able to override it if you want something sophisticated. I'd say all of this can be implemented in 50 or 60 lines of code, if you forfeit the idea of using objects to represent configs and http requests.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •