PHPRO.ORG

This easy to use class takes its input from the query string in a URL and parses the parts into an array of fragments. Each fragment can be accessed with the fragment method and supplying a key. This is most useful when using urls with mod_rewrite to form urls like this:
http://example.com/cart/category/product/item/1234.php The URL query string is exploded and each fragment is held in the fragments array.

The class uses the singleton design pattern, so that it can be made globally available in scripts.



<?php

class uri 
{
    
/*
     * @var array $fragments
     */
    
public static $fragments = array();

    
/*
    * @var object $instance
    */
    
private static $instance null;

    
/**
     *
     * Return URI instance
     *
     * @access public
     *
     * @return object
     *
     */
    
public static function getInstance()
    {
         if(
is_null(self::$instance))
         {
             
self::$instance = new uri;
         }
        return 
self::$instance;
    }


    
/**
     *
     * @the constructor is set to private so
     * @so nobody can create a new instance using new
     *
     */
    
private function __construct()
    {
        
/*** put the string into array ***/
        
self::$fragments =  explode('/'$_SERVER['QUERY_STRING']);
    }

    
/**
     * @get uri fragment 
     *
     * @access public
     *
     * @param string $key:The uri key
     *
     * @return string on success
     *
     * @return bool false if key is not found
     *
     */
    
public function fragment($key)
    {
        if(
array_key_exists($keyself::$fragments))
        {
            return 
self::$fragments[$key];
        }
        return 
false;
    }


    
/**
     *
     * @__clone
     *
     * @access private
     *
     */
    
private function __clone()
    {
    }
}

?>

Example Code


<?php

    
/*** retrieve a URI instance ***/
    
$uri uri::getInstance();

    
/*** show the second segment ***/
    
echo $uri->fragment(1);

?>