Simple PHP url dispatcher
PHP maps filenames into urls, this is a very handy feature and many applications simply use that for all their request handling needs. Practical as it can be, it’s quite limited.
Mapping url patterns into functions or Object methods is simple and easy. I’ll comment as I go…
//defining what url patterns get mapped into what funcitons. //if no route is provided 'default' route is used $routes = array( "default" => "sayhello", "hello" => "sayhello", "sum" => "computesum" ); /** *Dispatch function - delegates action to other function and passes parameters to it */ function dispatch(){ global $routes; //stear clear, allow only leters, numbers and slashes if(!empty($raw_route) and preg_match('/^[\p{L}\/\d]++$/uD', $_SERVER["PATH_INFO"]) == 0){ die("Invalid URL"); } //extract parameters $url_pieces = explode("/",$_SERVER["PATH_INFO"]); $action = $url_pieces[1]; $params = array(); if(count($url_pieces)>2){ $params = array_slice($url_pieces, 2); } //when no action is passed default action is performed if(empty($action)){ $action="default"; } //make sure the route is defined if(!in_array( $action, array_keys($routes))){ die("Nothing to see here"); } //all checked, execute requested funcion with provided parameters $action_function = $routes[$action]; $action_function($params); } //just an example function sayhello(){ echo "Hello to you too!"; } //another example function computesum(){ $params = func_get_arg(0); $sum = 0; $i=0; foreach($params as $par){ $par = intval($par); $sum += $par; if ($i !=0){echo " + ".$par;} else{echo $par;} $i++; } echo " = " . $sum; } //run the whole thing dispatch(); |
paste this into a file, for example dispatcher.php, put it on your server then try out urls like:
http://example.com/dispatcher.php/sum/1/2/3/4/10
http://example.com/dispatcher.php/hello
http://example.com/dispatcher.php
The file name can be removed if your server hasĀ supportĀ for url rewriting.
Related Posts:
Tags: dispatcher, php, url
July 18th, 2012 at 00:22
I am planing on getting the windows of my entire house tinted with a tint that blocks out 99% uv rays and 65% of heat. Will that qualify for a tax credit?
November 7th, 2012 at 07:01
NM/
April 20th, 2013 at 11:25
http://oxdvd.net/cat16-sub42.html