Developing a URL Handling Helper Class in PHP 5

In this third installment of a series on building helpers in PHP 5, I will provide you with the basic pointers for building a URL-handling helper class. The code examples, though simple, should serve to demonstrate how to create a helper that generates dynamic URLs.

Undeniably, helper classes are one of the most useful resources found in a PHP developer’s toolbox. They present several distinctive characteristics that make them look quite different from a typical full-blown library: on the one hand, they’re built as small packages of logically-related methods, while on the other hand their functionality may be so remarkable, that they become a fundamental block in the development of web applications.

Fortunately, building helper classes with PHP 5 is a pretty straightforward process that can be tackled with only an average background in object-oriented programming. So, if you’re a PHP developer who’s searching for a friendly guide that shows you how to create different kinds of helpers through a hands-on approach, then this series of articles may be the material that you need.

And now that you know what to expect from this group of tutorials, it’s time to review the concepts that were deployed in the previous one. In that second part of the series I explained how to improve the use of a basic text helper class by declaring all of its methods static, with the exception of the constructor.

In doing so, it was possible to take full advantage of the class without having to spawn any instances of it. Logically, a similar result can be obtained by declaring the class abstract, but as you know, abstract classes are intended to be inherited by children, while helpers generally aren’t conceived that way.

So far, so good. At this point, I’ve summarized the topics discussed in the last article, so it’s time to talk about the subject of this one. Since it’s a common practice to build helpers that manipulate URLs in different ways, in the next few lines I’m going to show you how to create a class whose main task will be dynamically generating URLs via a basic API.

Want to learn how this brand new helper class will be developed? Then start reading right now!

{mospagebreak title=Review: the previous TextHelper class}

Before I proceed to develop the URL-handling helper class that I just mentioned in the introduction, it’d be helpful to recall the signature and text helper created in the preceding article, so you can quickly grasp how it was defined and how it can be used for filtering strings.

Having said that, here’s the full source code of the text helper class, so examine it closely:

class TextHelper

{

// constructor not implemented

public function __construct(){}

 

// convert new lines to ‘<br />’ tags

public static function newline_br($str)

{

if (is_string($str) AND empty($str) === FALSE)

{

return nl2br($str);

}

}

 

// convert new lines to ‘<p>’ tags in string

public static function newline_par($str, $id = ”, $class = ”)

{

if (is_string($str) AND empty($str) === FALSE)

{

if ($id != ”)

{

$id = ‘ id="’ . $id . ‘"';

}

if ($class != ”)

{

$class = ‘ class="’ . $class . ‘"';

}

return ‘<p’ . $id . $class . ‘>’ . str_replace("n", ‘</p><p>’, $str) . ‘</p>';

}

}

 

// convert new lines to ‘div’ tags in string (id and class attributes can also be specified)

public static function newline_div($str, $id = ”, $class = ”)

{

if (is_string($str) AND empty($str) === FALSE)

{

if ($id != ”)

{

$id = ‘ id="’ . $id . ‘"';

}

if ($class != ”)

{

$class = ‘ class="’ . $class . ‘"';

}

return ‘<div’ . $id . $class . ‘>’ . str_replace("n", ‘<div></div>’, $str) . ‘</div>';

}

}

 

// uppercase all characters in string

public static function uppercase_all($str)

{

if (is_string($str) AND empty($str) === FALSE)

{

return strtoupper($str);

}

}

 

// lowercase all characters in string

public static function lowercase_all($str)

{

if (is_string($str) AND empty($str) === FALSE)

{

return strtolower($str);

}

}

// uppercase first character in string

public static function uppercase_first($str)

{

if (is_string($str) AND empty($str) === FALSE)

{

return ucfirst(strtolower($str));

}

}

}

If you’re familiar with building PHP programs using an object-oriented approach, then you shouldn’t have major problems understanding how the above "TextHelper" class does its thing. As you can see, it has some simple methods for applying different formatting processes to an inputted string.

However, the most important thing to note here is that since those methods have been declared static, they also can be called out of the object scope. The following examples show how to invoke the methods in question without creating any instances of the text helper class. Here they are:

// convert new lines to ‘<br />’ tags

echo TextHelper::newline_br(‘The shinning ‘ . "n" . ‘is a scary book of Stephen King!’);

/*displays the following

The shinning <br />

is a scary book of Stephen King!

*/

 

// convert new lines to ‘<p>’ tags

echo TextHelper::newline_par(‘The shinning ‘ . "n" . ‘is a scary book of Stephen King!’, ‘pid’, ‘pclass’);

/*

displays the following

<p id="pid" class="pclass">The shinning </p><p>is a scary book of Stephen King!</p>

*/

 

// convert new lines to ‘<div>’ tags

echo TextHelper::newline_div(‘the shinning ‘ . "n" . ‘is a scary book of Stephen King!’, ‘divid’, ‘divclass’);

/* displays the following

<div id="divid" class="divclass">the shinning <div></div>is a scary book of Stephen King!</div>

*/

 

// uppercase sample string

echo TextHelper::uppercase_all(‘The shinning is a scary book of Stephen King!’);

/* displays the following

THE SHINNING IS A SCARY BOOK OF STEPHEN KING!

*/

 

// lowercase sample string

echo TextHelper::lowercase_all(‘The shinning is a scary book of Stephen King!’);

/* displays the following

the shinning is a scary book of stephen king!

*/

 

// uppercase first character in sample string

echo TextHelper::uppercase_first(‘the shinning is a scary book of Stephen King!’);

/* displays the following

The shinning is a scary book of stephen king!

*/

Aside from bringing up some great memories from my distant childhood (yeah, Stephen King was my favorite writer by that time), the examples shown previously show how to use the text helper in a more efficient way.

Since these examples speak for themselves, I’m not going to waste your time explaining how they work. Instead, I’m going to continue discovering more useful things about building helper classes.

Therefore, in accordance with the concepts deployed in the introduction, in the following section I’m going create another helper class, which will be tasked with generating dynamic URLs.

To learn more about how this class will be built, click on the link that appears below and keep reading.

{mospagebreak title=Building a URL-handling helper class}

In reality, building a helper class that generates URLs dynamically is normally a no-brainer process, but in this specific case it’ll be even simpler. The class that I’m planning to develop will be a simple wrapper for most of the elements of the $_SERVER superglobal PHP array.

Now that I’ve explained how this URL-handling helper class is going to work, I suggest that you look at its signature, which has been listed below. Here it is:

class URLHelper

{

// constructor not implemented

public function __construct(){}

 

// get web server root

public function get_document_root()

{

return $_SERVER['DOCUMENT_ROOT'];

}

 

// get script URL

public function get_script_url()

{

return $_SERVER['PHP_SELF'];

}

 

// get script query string

public function get_query_string()

{

return $_SERVER['QUERY_STRING'];

}

 

// get request URI

public function get_request_uri()

{

return $_SERVER['REQUEST_URI'];

}

 

// get script file name

public function get_script_filename()

{

return $_SERVER['SCRIPT_FILENAME'];

}

 

// get request method

public function get_request_method()

{

return strtolower($_SERVER['REQUEST_METHOD']);

}

}

Certainly, the definition of the above "URLHelper" class confirms exactly what I said a few lines before, because its methods are simple proxies for many of the values stored on the native $_SERVER PHP array. Naturally, it’s possible to implement more complex methods, for instance, for building the breadcrumbs for a web site, but for the moment I’m going to keep the functionality of this URL helper class rather simple.

Having shown how this sample class looks, I’m going to code a few hands-on examples to demonstrate how to perform some basic tasks using some of the class’s methods.

As usual, to see how these examples will be created, please read the section to come.

{mospagebreak title=Putting the URL helper class into action}

Now that there’s a URL helper class available for testing purposes, it’d be useful to see how it can be put into action, right? With that idea in mind, below I coded a group of examples that show precisely how to use the helper for retrieving URL-related information about a PHP script running on a Windows web server.

Here are the corresponding code samples:

$urlhelper = new URLHelper();

echo $urlhelper->get_document_root();

/*

// displays the following

C:/Program Files/Apache Group/Apache2/htdocs

*/

 

echo $urlhelper->get_request_method();

/*

displays the following

get

*/

 

echo $urlhelper->get_query_string();

/*

displays the following

fname=Alejandro&lname=Gervasio

*/

 

echo $urlhelper->get_request_uri();

/*

displays the following

/helpers/helper_example.php

*/

 

echo $urlhelper->get_script_filename();

/*

displays the following

C:/Program Files/Apache Group/Apache2/htdocs/helpers/helper_example.php

*/

 

echo $urlhelper->get_script_url();

/* displays the following

/helpers/helper_example.php

*/

As you can see above, the methods of the URL helper class have been utilized for retrieving some typical values about the script being executed, such as the request URI and the script’s URL, the root of the web server and the eventual query string, and so forth, assuming that these parameters are available to be fetched from the web host.

Again, it’s feasible to add more methods to the helper that perform more complicated tasks, but I guess the class in its current version should be enough to demonstrate how to create a URL helper in PHP 5.

Finally, feel free to edit all of the examples shown in this tutorial, particularly if you’re planning to include different kinds of helper classes in your own framework.

Final thoughts

That’s about it. In this third installment of the series, I provided you with the basic pointers for building a URL-handling helper class. Of course, the methods of this sample class should be improved to fit the requirements of production environments, but they should serve to demonstrate how to create a helper that generates dynamic URLs.

In the next article, I’m going to enhance the signature of this class by declaring its methods static, which is pretty similar to the process covered in the preceding tutorial.

Don’t miss the upcoming tutorial!

[gp-comments width="770" linklove="off" ]

chat