Blog

Url Routing with PHP – Part Two

Posted by:

This is the second part of a series, I assume you have read Url Routing with PHP – Part One as it covers the basics that I’ll build on in Part Two.

Requirements

  • Apache with mod_rewrite enabled
  • PHP

Assign Responsibilities

The first problem I want to address is that there are two different things going on with the script in part one. 1. The parsing of the URL to obtain a command array and 2. The actual dispatch of the command by the switch statement. I want to create an architecture that easily allows changing the way incoming URLs are formatted, and also the substitution of alternative dispatch schemes.

Standardized Command Objects

To achieve this goal, I create a standard command object. This will allow changing the way the urls are interpreted or dispatched as long as the interpreter creates command objects and the dispatcher accepts them.

  1. class Axial_Command
  2.         {
  3.         var $commandName = ;
  4.         var $parameters = array();
  5.        
  6.         function Axial_Command($commandName,$parameters)
  7.                 {
  8.                 $this->commandName = $commandName;
  9.                 $this->parameters = $parameters;
  10.                 }
  11.         function getCommandName()
  12.                 {
  13.                 return $this->commandName;
  14.                 }
  15.         function getParameters()
  16.                 {
  17.                 return $this->parameters;
  18.                 }
  19.         }

Interpreting URLs

Next we need a class that handles interpreting the incoming URL and creating a command object. The following class uses the same method as in part one and creates commands based on a simple format for the incoming URL, a command followed by its parameters separated by forward slashes.

  1. class Axial_UrlInterpreter
  2.         {
  3.  
  4.         function Axial_UrlInterpreter()
  5.                 {
  6.                 $requestURI = explode(‘/’, $_SERVER[‘REQUEST_URI’]);
  7.                 $scriptName = explode(‘/’,$_SERVER[‘SCRIPT_NAME’]);
  8.                         for($i= 0;$i < sizeof($scriptName);$i++)
  9.                                 {
  10.                                 if ($requestURI[$i] == $scriptName[$i])
  11.                                         {
  12.                                         unset($requestURI[$i]);
  13.                                         }
  14.                                 }
  15.                 $commandArray = array_values($requestURI);
  16.                 $commandName = $commandArray[0];
  17.                 $parameters = array_slice($commandArray,1);
  18.                 $this->command = new Axial_Command($commandArray[0],$parameters);
  19.                      }
  20.        
  21.         function getCommand()
  22.                 {
  23.                 return $this->command;
  24.          }
  25.         }

Dispatching Commands

And finally we can pass the command object to the dispatcher. In order to keep the code simple I use a switch statement that includes different scripts based on the command. There are many other methods that could be used in fact thats the point the of architecture I’m presenting.

  1. class Axial_CommandDispatcher
  2.         {
  3.         var $command;
  4.         function Axial_CommandDispatcher($command)
  5.                 {
  6.                 $this->command = $command;
  7.                 }
  8.  
  9.         function Dispatch()
  10.                 {
  11.                 switch ($this->command->getCommandName())
  12.                         {
  13.                         case ‘commandOne’ :
  14.                                 include(‘commandone.php’);
  15.                                 break;
  16.                         case ‘commandTwo’ :
  17.                                 include(‘commandtwo.php’);
  18.                                 break;
  19.                         case :
  20.                                 include(‘root.php’);
  21.                                 break;
  22.                         default:
  23.                                 include(‘default.php’);
  24.                                 break;
  25.                         }
  26.                 }
  27.         }

Put it all together

In the first part of this series I used an .htaccess file to redirect to index.php. The same .htaccess is all we need now. Our new index.php will look a bit different though. With the changes from part one made we can now substitute different classes to handle the interpretation of URLs or command dispatching easily.

  1. include(‘axial.command.php’);
  2. include(‘axial.urlinterpreter.php’);
  3. include(‘axial.commanddispatcher.php’);
  4. $urlInterpreter = new Axial_UrlInterpreter();
  5. $command = $urlInterpreter->getCommand();
  6. $commandDispatcher = new Axial_CommandDispatcher($command);
  7. $commandDispatcher->Dispatch();

Try it out

You can visit examples.phpaddiction.com/urlrouter/part_2/ to see it in action and download the sample code.

Next up

In the next part of this series I will explore some ways to get rid of the switch statement in the dispatcher and create a small framework to hang your code from.

62


About the Author

Discussion

  1. L!MP  April 6, 2007

    replace

    $this->command = new Axial_Command($commandArray[0],$parameters);

    to

    $this->command = new Axial_Command($commandName ,$parameters);

  2. Doug Hill  April 7, 2007

    Sure, either way works, It is quicker to leave out the array access and perhaps the clearer style, thanks for the pointer.

  3. Roman  April 8, 2007

    I use $_SERVER['PATH_INFO']. This way I only get what is past the script path.

  4. Doug Hill  April 9, 2007

    Roman: I decided against using PATH_INFO since it wouldn't allow for separators other than forward slashes "/". I wanted the entire URL after the script not just the directories. Also I found that support for PATH_INFO wasn't the same across PHP versions.

  5. Tom  May 18, 2009

    I dont understand why is a url router?

    Here an example of an url router:

    $listRoutes = array(
    "home" => "",
    "articleHome" => "articles",
    "news" => "articles/news",
    "category" => "articles/",
    "article" => "articles//article-.html"
    );

    foreach ($listRoutes AS $name => $route)
    {
    if (strpos($route,'<') === false)
    {
    echo "Static $name: ".(match_static_route($url,$route) ? 'Yes' : 'No');
    }
    else
    {
    echo "Dynamic $name: ".(count($r = match_dynamic_route2($url,$route)) != 0 ? 'Yes':'No')." — ";
    print_r($r);
    }
    }

    function match_static_route($url,$route)
    {
    return $url == $route;
    }

    function match_dynamic_route2($url,$route)
    {
    $result = array();

    $route = str_replace("/","\/",$route);
    $route = str_replace("<","(?P",">[^\/]*)",$route);

    if (preg_match("/$route$/",$url,$matches) > 0)
    {
    foreach ($matches AS $key=>$value)
    {
    if (!is_numeric($key))
    {
    $result[$key] = $value;
    }
    }
    }

    return $result;
    }

    You can exploit the parameters on $r.

  6. Carlo  June 25, 2009

    Please can you Tom from the previous comment or someone else explain to me the point?

    What does that mean "you can exploit". Also the introducing sentence is not quite clear for me, I am not english.

    But I see in the code some interesting point, so I'd like to understand the whole thing

    Thank You
    Carlo

  7. Johan Hultin  June 28, 2009

    I don't really like the whole thing with cases there, I'd say it's quite static and should be worked on to be more dynamic, I will work on it and see if I find any neat solution

  8. stunaz  July 29, 2009

    There is a bug on that script.
    we can see it on the example. while testing the link with two parameters, the css style disappear.
    how can we fix that?

  9. stunaz  July 29, 2009

    i mean in the example that we download from the link

  10. vulo  October 5, 2009

    While using the url router,
    in the functions that I am using instead of variables I get

    AC_RunActiveContent.js
    Scripts
    robots.txt, loaded into the urls – array
    and the the actual url (for example – events, ot contacts)

    Also I think it is reloading the page every time. with these values into the urls – array

    Have anyone idea why this is happening.
    Regards
    Vulo

  11. IT Support London  November 24, 2009

    i cant get the code to work arghhhh!

  12. Anonymous  May 29, 2010

    Great Article.

    //
    // Shorter way of parsing the path.
    //
    array_diff (
    explode('/', $_SERVER['REQUEST_URI']),
    explode('/', $_SERVER['SCRIPT_NAME'])
    );

  13. Laptop Repair London  August 16, 2011

    Been looking for ways to go around with some codes putting URL to PHP codes, thanks for the codes. Surely helped a lot.

  14. Sepehr  October 27, 2011

    Thank you "Anonymous" for shorter way of parsing the path.
    And of course thanks to the author!

  15. wuttdan  April 4, 2012

    Great.

  16. David  April 16, 2012

    The problem is, what if the user accesses http://localhost/index.php

  17. Ben  February 20, 2013

    What about URis like this? /command/action?state=somethingInHere&facebook=true

    I neet it, to authenticate with facebook

  18. SEO Free Lancer Mumbai  October 14, 2014

    This is my first time go to see at here and i am truly pleassant to read all at alone place.

  19. accessoire wiko iggy  October 15, 2014

    This is yet another advantage to owning this type of furniture for your patio area.
    Well, this is a must read article for all those looking for wrought iron fencing, garden sheds and outdoor furniture.
    Next think about dryer banks and how they'll blend in within the theme of
    your salon, modern versions are ever so stylish and they come in a
    range of options from suppliers of Salon Furniture.

  20. Hardquotes  November 12, 2014

    You could certainly see your enthusiasm within the article you write.

    The arena hopes for more passionate writers like
    you who are not afraid to mention how they believe. Always go after
    your heart.

  21. chris ashenden athletic greens  November 21, 2014

    If embarking on a homemade raw food diet for your pet (sometimes referred to
    as BARF), thoroughly research the area first as nutritional balance is essential.
    Doing a lot of small things, can make a huge difference
    in the quality of your life. Green superfoods, for example, are often some of the best when it comes to your health.

  22. clash of clans tips and cheats 2014  December 4, 2014

    The application for the Clash Meet Up SF2013!

  23. leasing samochodowy dla nowych firm  December 7, 2014

    You should never tell your dealer that you want to lease the
    car. However, there are certain limits and guidelines regarding how a
    client may use the car. Whether it’s a business or personal
    car leasing, throughout the duration of your contract hire,
    we make it as simple and as straight forward as you want
    it.

  24. champ man 15 triche  December 14, 2014

    There is obviously any good gear shift on the console that
    gives you that arcade feel if you are really in the driving action in your PS2.
    For addition, it is possible to talk about to count the total quantity of
    Battle Droids. Sir Tet is another name with the Tetris game about the
    Zune. With 10 environments and 4 degrees of difficulty,
    this can be a must for any fan with the original.
    When middle aged mums and dads, aunties and businessmen start showing their kids their tatts, there is only 1
    outcome. Don't underestimate the strength of writing simple musical parts (there is no need to create things like "Twinkle, Twinkle, Little Star" naturally – I don't
    mean 'that' form of simple). Parents must accept and adapt to
    the fact technology is an essential in life which is just not likely to switch at any time soon.
    The most enticing element of RPGs is when they allow player
    are now living in a virtual world his or her character
    and control the outcome and pace of the game.
    MMORPG games feature tutorial quests to the beginner to assist them
    get acquainted using the different types of quest and associated tactics and strategies.
    Customization within farmville is in fact really fun. The
    rise in popularity of flash games can be due to the belief
    that they can be purchased in a wide range of
    categories like adventure, action, role playing
    games, simulations, educational, puzzle games, 2D and 3D games, single and multiple
    player games. 1 factor a large amount of new Wii owners are
    no doubt questioning is how to backup Wii games. You wouldn't want to ruin your outfit in case you get too jittery.

    It's no longer cool seeing that everyone's getting inked
    , accordingly the volume of people who have tattoo regret is
    increasing as well. It was a statement from the conservative suit wearing white middle aged culture which was (which is) found so commonly inside the western world.
    It takes a couple of hours to obtain a Wii game burned.

    Killing zombies or shooting at virtual terrorists can be a
    fun-to never mention safe-method for one to release their pent
    up frustrations. To tower fan, as an example, even though the
    basic functions of the fan tower principle models
    resemble, but in some appearance details, major manufacturers will probably
    be under full fighting techinques, so that products can clearly identify the consumers.

    Older adults who are significantly less actives since they used to be may can enjoy more sit-down type
    games including charades, and trivia games. Color is another factor
    inside the game because other than matching clothes, there ought to be complementary colors of
    what Barbie is wearing. Tasks include delivering
    food products on the market and feeding animals. Your awesome Xbox skins are generally made out of cast
    vinyl films manufactured with the help of your special process.
    Free online games can a welcome distraction for an otherwise monotonous day.
    However, most ads are relevant on the content, and they
    are safe. So, you are able to decide which games are ideal for your
    youngster easily.

  25. health fitness classifieds  December 16, 2014

    I like the valuable information you supply to your articles.
    I will bookmark your weblog and take a look at again right here regularly.

    I am reasonably certain I'll be told lots of new stuff proper here!

    Best of luck for the following!

  26. Pokemon X Y gratuit  December 18, 2014

    Normally I don't read article on blogs, but I wish to
    say that this write-up very pressured me to check out and do so!
    Your writing style has been amazed me. Thanks, quite great
    post.

  27. Norberto  December 20, 2014

    Wireless Green Pads generally depends upon the customers can use and
    offering them probably the most realistic alternatives might entice big inflow of customers.

  28. pernikahan  January 1, 2015

    Oh my goodness! Amazing article dude! Many thanks, However I am
    going through difficulties with your RSS. I don't know why I cannot join it.
    Is there anyone else getting the same RSS problems?
    Anyone that knows the answer will you kindly respond?

    Thanks!!

  29. boom beach guide  January 2, 2015

    Thankfulness to my father who stated to me about this blog, this
    blog is really awesome.

  30. gabinet kosmetyczny kielce  January 4, 2015

    Pretty part of content. I just stumbled upon your blog and in accession capital to claim that I
    get actually enjoyed account your weblog posts.
    Anyway I will be subscribing on your feeds and even I fulfillment you get
    entry to constantly quickly.

  31. home builders  January 7, 2015

    There are three kinds of home builders now. There is the "top end custom new home builders", the "creation contractor", and the "small, hands on contractor".

    While there are hybrid vehicles and variants within these three groups, these are the fundamental
    kinds at function today. The trick for the prospective buyer would
    be to recognize which might be the best match for their pocketbook and home-style needs.

  32. Raleigh  January 7, 2015

    You can certainly see yiur skills in the article you
    write. The arena hopes for even more passionate writers such
    as you who aren't afraid too say hhow they believe.

    At all times goo after your heart.

  33. web marketing association  January 8, 2015

    I blog quite often and I truly appreciate your content.
    Your article has truly peaked my interest. I'm going to book mark your site and keep checking for new information about once
    a week. I subscribed to your RSS feed too.

  34. Ty Rhame  January 9, 2015

    From March 1st to April 15th mainly during tax season, a certified professional
    tax preparer in a forty five day period could make as much at
    $7,500 which is very good. Think about how "Just do it"
    defines Nike's philosophy on playing sports, or Avis's "We try harder" defines customer services operations.
    Take some time to truly explore the idea of starting your own tax preparation company.

  35. Deanne  January 16, 2015

    Awesome! Its truly amazing post, I have got much clear idea concerning from this paragraph.

  36. yatko.com  January 19, 2015

    That is a good tip especially to those new to the blogosphere.
    Brief but very precise information… Many thanks for sharing this one.
    A must read article!

  37. Andre  February 1, 2015

    These 2 cold-sore solutions aree available with no issues to put into play.

    A sore that is cold. Will definitely you obtain gone this Will mouthwash on lesions that are
    cold provide a useful solution?

  38. information management  February 4, 2015

    Most of the businesses are implementing enterprise Resource Planning program to streamline their processes
    that are internal as well as to get a smooth flow of information within the companies' many functional sections.
    A great deal of time, efforts and cash are involved in the ERP implementation procedure.

    The price of ERP execution depends and changes on many variables.
    The measurement of the business process' complexity
    and the company also decide the expense of ERP implementation. ERP involves a huge investment as well
    as a proper investigation of the prices must be
    achieved before the enactment. The execution of ERP comprises several procedures which
    add to the expense of ERP implementation. The ERP advisor provides the services in a price that
    is high and also it is also an important determinant of the ERP costs.

  39. English schools in Abu Dhabi  February 5, 2015

    Starting on your first-year of British schools in Abu Dhabi is both
    stressful and exciting. Nevertheless, it could also
    be daunting. Should you come prepared, then you certainly wont have to
    fear the experiences that are fresh. You will know exactly what to expect from Primary schools in Abu Dhabi life before you ever get there in case you do a little research.
    This report can allow you to get started.

  40. kendrick lamar  February 6, 2015

    You've decided you want to download music, but maybe you are looking at what to do.
    This post will surely help out you. You will be educated by the following guidance
    about how to download kendrick lamar new song.

    Always be sure that your music is downloaded by you from a lawful site.
    If you download music illegally, you can face harsh penalties.
    Oftentimes you can be penalized up to $500 per tune.
    The musicians deserve to be paid-for the music they make,
    so download only lawful duplicates of the tunes that you simply love.

  41. read more  February 6, 2015

    If you have kids who play with video games, then you understand
    how difficult it is to take them away from the television. Their eyes
    could be pasted to the display for hours while they play with their preferred games.
    Then this post has some tips for you, in case you need help
    regulating your kids' movie game moment.

  42. antalya rus escort  February 7, 2015

    For most up-to-date news you have to pay a visit internet and on internet I found this site
    as a finest site for newest updates.

  43. signage auckland  February 10, 2015

    Whenever you are operating at a place that is prone to accidents,
    you require you to be guided by signs auckland with all your tasks.

    You still require the health and shop signs or
    planks although most companies would offer good instruction in the various procedures and jobs.
    Indications and the security symbols can be demanding to remember, especially if you will find several signs to be remembered.

    In a normal manufacturing situation, the worker class has
    to be told concerning the security measures and also the security gear which they have to consider while they
    are in perform.

  44. watch series  February 11, 2015

    It's a shame yyou don't have a donate button! I'd without a doubt donate tto this outstanding
    blog! I suppose for now i'll settle for bookmarking and adding your RSS feed to my Google account.
    I look fprward to new updates and will share
    this website with my Facebook group. Chat soon!

  45. business process outsourcing  February 11, 2015

    In other failures, when an ERP does not deliver business benefits,
    it called a dead loss. In most cases, company seeking to implement an ERP
    has some idea concerning the regions that can gain upon ERP
    implementation. Boost inventory turns, or when a business
    is not able to reduce inventory by 6%, or reduce
    the number or decrease business risks it needs to be termed as a failed implementation. Just writing a PO or an Indent can not be consider achievement.
    That is setting the bar too low yourself together with for ERP.

  46. pd drumband  February 12, 2015

    Actually when someone doesn't understand after that its
    up to other visitors that they will assist, so here it occurs.

  47. kitchen plans  February 12, 2015

    In case you're sick and tired of looking at the exact same old walls in your house consider interior decoration!
    Offering any room in your home a make-over may be satisfying, interesting and also economically efficient.
    Look at these hints to enable you to plan and create
    your kitchen design ideas nz thoughts with
    style.

  48. indian takeaway auckland  February 12, 2015

    After you've made a decision to start a restaurant
    company you are going to have to pick out an area wherever your fresh venture may prosper.
    Place is of great importance to a restaurant business' stability.
    There are a lot of other things to consider while you realize that you require
    a restaurant place that is good with lots of space like indian restaurant.
    These offers a list of selection criteria that can be employed to assess how
    great a place that is specific is.

  49. outdoor furniture nz  March 3, 2015

    Have you been exhausted from searching for outdoor furniture nz and coming home empty-handed?
    Must you accept items that do not fit your style? Learning the best way
    to find good outdoor furniture nz at an excellent price is
    exactly what you have to do. This short article provides you with
    the information you need if so,.

  50. sound hire surrey  March 3, 2015

    You most likely immediately feel of a person starting an event
    when you hear about keynote speakers. It is since the name has been produced from the musical expression 'keynote', which indicates the base that underlines all music
    created. Now, keynote speakers are getting to be extremely popular among companies.
    Nearly all managers are hiring someone to talk not simply at events that are major but
    additionally in their own offices. Based on the purpose that must be served, these speakers vary.

    As an example, a business may sound hire surrey, an inspirational presenter and maybe even possibly also a significant key-note speaker.

  51. gift baskets  March 3, 2015

    Gift containers may remain well-liked and also a great idea to give as a gift.
    Folks love to receive gift baskets. Creating your
    own chocolate-lover gift basket is easy and cheap.

  52. Kendrick lamar new album  March 3, 2015

    Music downloads can really be fun to work with but you need to learn how to
    proceed first to make them perform for you personally.

    Here are several great tips if it is what you're wanting to work with you can follow.

    Just take it one step at a time plus you'll
    do fine.

  53. radiologist auckland  March 4, 2015

    The various benefits of the middleman world of sciences has been the improvement as well as invention of a
    few of the most revolutionary instruments and technologies which have actually given a fantastic jump in each sense of the word to the
    world of technologies and sciences. One such technique that is certainly the effect of
    such inter-disciplinary attempts and has been really useful in managing and diagnosing variety of ailments that were not considered easy to handle
    till day is ultrasound scan's method. The technique of auckland
    xray services involves study in addition to use
    of imaging technologies as treat different disorders so that you can diagnose as well.
    A few of these imaging technologies which can be employed are computed axial tomography
    (CT), magnetic resonance imaging (MRI), positron emission tomography
    (PET), and ultra sound.

  54. online jewellery shopping India  March 10, 2015

    They are usually made with extra pizaz and shimmer exceeding other
    makes of handbags. They can be tied, pinned with a piece of jewellery,
    or secured with specially designed scarf pins. Good fashion shoes transform the wearer's
    personality.

  55. kitchens nz  March 11, 2015

    Tactile and visual interest can be added by combining styles and textures to your chamber.
    Varying textures create interest and depth while patterns provide pieces for example wood
    furniture with a contrast. You need to mix your colors and patterns up if you're attempting to make your room look better.

  56. seo Saudi Arabia  March 12, 2015

    We are convinced this is only one of the very most important query
    which many companies find hard to get replies to.
    Obviously, there are equally advantages & disadvantages of design a website all on your own and getting it done by a
    professional, as it really is mentioned, "Every coin has two sides".
    Therefore here, we will discuss regarding precisely the same.
    But before we begin the discussion, it is to be recalled and that means
    you need to have a good concept about the assertion of your company, trade name or the
    vision that you just wish to get communicated
    when any one of your current or portential clients see your site that internet designing is an art.
    Them should impress in all manners. Edge of web design Jeddah on your own

  57. www.EverMoney.co.uk  March 12, 2015

    Automobile insurance is required by state law for several drivers to own. That
    is lucky for motorists, as automobile insurance provides protection for just about any costs which will
    come from auto accidents. There are if you would like advice which will help you select the one that
    is right, then continue reading this informative article and many suppliers for car insurance.

  58. trailer  March 13, 2015

    As an owner-operator or small fleet owner, having a truck that is semi will not make you any cash without having lots to carry.
    What this means is you have to additionally consider renting
    or buying a trailer. Before we go into our hints about what to check for before making such a purchase,
    you will also need to look at the type of weight you
    will be taking!

  59. small dog crate  March 13, 2015

    Canine crate-training is vital for a dog along with
    a puppy and you will realize that it is worth the time and
    also the effort that you just commit to it. Crate training a puppy may
    take from day-to weeks depending on the time
    of your dog, past experiences and nature. It is crucial to offer your dog crates for sale that she is able to use during her lifetime.

    This functions as your pet 's harbor. Dogs do possess the right to privacy
    also, so crate training your pet is hardly unimportant. As an owner, you will need to limit
    the accessibility while it's off leash before the home principles are realized.

  60. shop signs  March 14, 2015

    Charitable organizations usually have trouble marketing because they've restricted
    budgets, and sometimes they they do not even have
    a storefront. Most nonprofits possess some type of business
    vehicle (also when it's only a worker private car), plus it's pretty-affordable
    to promote on such a car. This kind of marketing not only develops knowledge and curiosity in the
    cause the supports that are charitable, but it's also a terrific way to to search
    out possible subscribers, sponsors or donors.

  61. Prayers for understanding Jerusalem  March 14, 2015

    As the admin of this site is working, no hesitation very shortly it will be renowned,
    due to its feature contents.

  62. best android phone verizon july 2012  March 14, 2015

    It's almost exactly the same size as the Galaxy S5, a little bit larger than the iPhone 6,
    and a good quarter-inch shorter compared to the HTC One M8 or LG G3.

Add a Comment