Simple PHP Routing

Does it need more work?

  • Yeah

    Votes: 5 100.0%
  • Nah

    Votes: 0 0.0%

  • Total voters
    5
Status
Not open for further replies.

GarettM

Posting Freak
Aug 5, 2010
833
136
Simple PHP Router
A Simple PHP Router to use in your web projects

About

I created this router for HybridCMS but i felt others should be able to use this router.
If there is issues i might not be able to provide help i am new to regex and i am not sure if this is the most
efficient way of doing this.
Features
  • Static Routing
Notes
  • When routing to a function in a controller the parameter will be an array
  • To specify a string you MUST use [string]
  • To specify a integer you MUST use [int]
  • Wildcards are not yet supported but will be included soon
How to use
PHP:
<?php
require_once( dirname(__FILE__) . '/router.php' );

Router::GET('/', function() {
   return require('template/welcome.php');
});
Router::POST('/login', function() {
   // handle logig
});
Router::GET('/login', function() {
   return require('template/login.php');
});

Router Class
PHP:
<?php
/**
*    Simple PHP Router
*
*    @author     GarettMcCarty <[email protected]> DB:GarettisHere
*    @version    1.0.0
*    @link       http://github.com/GarettMcCarty/HybridCMS
*    @license    Attribution-NonCommercial 4.0 International
*/

class Router
{
    protected static $regex  = ['[string]' => '([^/]+)', '[int]' => '(\d+)', '[*]' => '(.*?)'];
    protected static $routes = [];

    // GET Helper
    public static function GET($uri, $callback)
    {
            return self::addRoute('GET', $uri, $callback);
    }
    // POST Helper
    public static function POST($uri, $callback)
    {
            return self::addRoute('POST', $uri, $callback);
    }

    public static function addRoute($method, $uri, $callback)
    {
        $uri = str_ireplace(array_keys(self::$regex), array_values(self::$regex), $uri);
        self::$routes[$uri] = sprintf('~^/index.php%s$~', $uri);

        $request = filter_input(INPUT_SERVER, 'REQUEST_URI');

        if(strpos($request, 'index.php') == false)
        {
            $request  = sprintf('/index.php%s', $request);
        }

        if($method != filter_input(INPUT_SERVER, 'REQUEST_METHOD'))
        {
            return;
        }

        if(array_key_exists($uri, self::$routes))
        {
            if(preg_match(self::$routes[$uri], $request, $matches) !== false)
            {
                if(count($matches) > 0 && $matches[0] == $request)
                {
                    if(is_callable($callback))
                    {
                        if(isset($matches[1]))
                        {
                            echo $callback($matches[1]);
                        } else {
                            echo $callback();
                        }
                    } else {
                        if(stripos($callback, '@'))
                        {
                            $data = explode('@', $callback);
                            $controller = "\application\controller\{$data[0]}";

                            if(isset($matches[1]))
                            {
                                $matches = array_shift($matches);
                                call_user_func_array(array(new $controller, $data[1]), $matches);
                            } else {
                                call_user_func(array(new $controller, $data[1]));
                            }
                        } else {
                            throw new \InvalidArgumentException('Routes must use a controller or a callable function.');
                        }
                    }
                }
            }

        }
    }
}

Here are some routes i have personally tested
PHP:
Router::GET('/', function()
{
    return "Welcome Everyone";
}
Router::GET('/hi/[string]', function($name)
{
    return sprintf('Hey %s!', $name);
});
 
Last edited:

brsy

nah mang
May 12, 2011
1,530
272
For learning purposes only.
Ah, that would make sense. I couldn't find a real world application for this. Also, if it's for educational purposes, some comments would be nice so people who aren't that good at PHP can actually understand what the hell they're reading.
 

Jian

Resident Weeb
Contributor
Sep 2, 2011
687
437
This is only used in frameworks, so having it in your cms with no use for extending the functionality makes this virtually useless. And correct me if I'm wrong, but don't you need htaccess for this to work on php?
 

GarettM

Posting Freak
Aug 5, 2010
833
136
This is only used in frameworks, so having it in your cms with no use for extending the functionality makes this virtually useless. And correct me if I'm wrong, but don't you need htaccess for this to work on php?
You need some kind of url rewrite if you want to hide "/index.php/" from the url address. To answer your question no your not required to use mod_rewrite but you will lose the abbility to have cleaner urls

Example with url rewrite

Example with OUT url rewrite
 
Last edited:
Status
Not open for further replies.

Users who are viewing this thread

Top