Generating URLs in PHP

Never hardcode URLs

It is almost never a good idea to manually write URLs on your website. Just like text strings, if for any reason you want to update them it becomes a nightmare.

<ul class="menu">
    <li><a href="/">Home</a></li>
    <li><a href="/product">Product</a></li>
    <li><a href="/service">Service</a></li>
    <li><a href="/testimonials">Testimonials</a></li>
    <li><a href="/about-us">About us</a></li>

You probably use some links on the header of your website and on the footer as well. Making changes to one requires that you update the other. In the programming world we say Don't Repeat Yourself, even though HTML is not a programming language, we still have to follow the convention to make code maintenance easier.

In a real website, the same URL can be present in more than a dozen places. The best thing to do is to have the URL saved in one place, and have the rest of the application request it from the same source.

That's why most framework use a routing file. In this file, they save all the URLs and which controller is responsible for it. In this example, I will talk about it in general without relating it to any framework.

So what we ca do instead is use an array. The array can be wrapped in a class to prevent namespace collision and also to add a small error handler or other features if necessary. Here is the overall structure.

class SiteUrl {

    private static $urls = array(
        "Home"      => "/",
        "Product"   => "/product",
        "Service"   => "/service",
        "Testimonials"  => "testimonials",
        "About"     => "/about-us",

    public static function get($urlName) {
        if (isset(self::$urls[$urlName])){
            return self::$urls[$urlName];
        echo "\nError: The url for '{$urlName}' does not exist\n";

In this class, we defined an array with all our URLs listed as a key value pair. We can use the get function to access them. If we ask for the wrong key, an error is thrown. The error handler could be improved by adding a stack trace of course. This way you can find exactly where you wrote the wrong text.

Here is how this class could be used.

<ul class="menu">
    <li><a href="<?php echo SiteUrl::get('Home');?>">Home</a></li>
    <li><a href="<?php echo SiteUrl::get('Product');?>">Product</a></li>
    <li><a href="<?php echo SiteUrl::get('Service');?>">Service</a></li>
    <li><a href="<?php echo SiteUrl::get('Testimonials');?>">Testimonials</a></li>
    <li><a href="<?php echo SiteUrl::get('About');?>">About us</a></li>

If we use the same class all over the code, then updating a URL is a matter of changing a single value in a known file and it will reflect site-wide.


There are no comments added yet.

Let's hear your thoughts

For my eyes only