Scripts

URL rewrite zonder mod_rewrite class

Ik heb deze class geschreven als reactie op de tutorial van Boaz over deze methode ( http://www.phphulp.nl/php/tutorials/8/629/ ) Hij had een klein voorbeeldje hoe je uit $_SERVER['PATH_INFO'] mbv explode() een url als http://www.site.nl/index.php/controller/blog/action/edit/id/30/ makkelijk kon 'parsen' naar een array Daar heb ik een simpele class omheen gebouwd die gebruik maakt van Singleton, zodat de url maar één keer geparsed wordt en dan de parameters worden opgeslagen. Met de magic method __get() kan je ze er dan weer simpel uit halen.

url-rewrite-zonder-modrewrite-class
<?php

final class Request {

	// object instance
    private static $instance;
    
    /**
     * In this var are the parameters stored
     *
     * @var array
     */
    static private $params = array();
    
	/**
	 * prevent direct access and cloning
	 * 
	 */
    private function __construct(){}
    private function __clone(){}

	/**
	 * create an instance of self
	 *
	 * @return Request
	 */
    public function getRequest() {
        if (!self::$instance instanceof self) {
            self::$instance = new self();
            self::parseUrl();
        }
        return self::$instance;
    }
    
    /**
     * This method will parse the url and put it as an array
     * in self::$params.
     *
     */
    private function parseUrl(){
		$pathInfo = explode('/', trim($_SERVER['PATH_INFO'], '/'));
		
		$myPath = array();
		for($i=0, $count=count($pathInfo); $i+1<$count && $count>1; $i+=2) {
			$myPath[(string) $pathInfo[$i]] = (string) $pathInfo[$i+1];
		}
		self::$params = $myPath;
    }
    
    /**
     * This function will return one of the items 
     *
     * @param string $key 
     * @param mixed $default
     * @return string/mixed. 
     */
    public function getParam($key, $default = null){
		$key = (string) $key;
    	if(isset(self::$params[$key])){
			return self::$params[$key];
		}
    	return $default;
	}
    
	/**
	 * A magic method wich does the same as self::getParam()
	 *
	 * @param string $key
	 * @return string
	 */
	public function __get($key){
		return self::getParam($key);
	}    
    
	/**
	 * This method will return all the values of self::$params
	 *
	 * @return unknown
	 */
    public function getParams(){
    	return self::$params;
    }
}

var_dump(Request::getRequest()->index);
var_dump(Request::getRequest()->getParams());

?>

Reacties

0
Nog geen reacties.