Building Helpers in PHP 5

Tired of repetitive coding for tasks such as generating web site breadcrumbs? PHP 5 provides a number of interesting ways to reuse your code so you can let the boring stuff take care of itself. This eight-part series will show you how to create helpers to take care of repetitive tasks and free up your precious coding time for the real challenges.

When it comes to speeding up the development of web applications, experienced PHP programmers tend to be rather lazy, and I’m not using that adjective with a negative connotation. Popular concepts like “don’t reinvent the wheel” and DRY (short for “don’t repeat yourself”) help developers avoid creating PHP programs from scratch, while maintaining a high level of control over how their logic is implemented.

Naturally, as you may have guessed, the most direct and simplest application of these concepts is code reuse. This concept can be applied through a variety of custom and third-party libraries, packaged in the form of classes or functions, or a combination of both.

Undoubtedly, the ultimate implementation of code reuse is a full-featured framework. Such frameworks provide developers with a set of well-trusted classes, modules, plug-ins and helpers that permit them to build complex web-based programs very quickly and without suffering premature hair loss.

But, wait a minute! If you reread the previous sentence, you’ll notice that I subtly introduced the term “helpers.” What are they? Well, if you still haven’t coded one on your own, helpers are usually small blocks of reusable code that help programmers to perform certain repetitive tasks.

A helper usually can be structured as one single class or as a set of functions, and the things it does generally aren’t as complex as those done by a full-blown library. Common tasks that must be performed over and over again with different projects, such as building portions of a URL, generating web site breadcrumbs and formatting chunks of text, are typical functions of helpers, to cite just a few illustrative examples.

Despite its seeming simplicity, building helpers can be a pretty challenging process, particularly for beginners whom are just starting to implement the object-oriented paradigm in PHP 5. So, in this series of articles, I’m going to introduce you as gently as possible to creating different types of helpers, which hopefully will make you understand the basis of this process and encourage you to create your own.

Now, it’s time to get rid of the boring theory and start learning how to build helpers with PHP 5. Let’s begin right away!

{mospagebreak title=Building a helper in PHP 5}

To start explaining how to build a helper in PHP 5, I’m going to define a basic class, which will be responsible for applying different filters to an entered string.

The functionality of this introductory class will be progressively enhanced, so for the moment its initial signature will look as simple as this:

class TextHelper

{

// constructor (not implemented)

public function __construct(){}

 

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

public function newline_br($str)

{

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

{

return nl2br($str);

}

}

 

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

public 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>';

}

}

}

As depicted above, the brand new “TextHelper” class has been provided with a couple of public methods for replacing all of the new lines within an incoming string with”<br />'” and “<p>” tags respectively.

Also, the last of these two methods, called “newline_par(),” has an additional functionality: it permits you to assign typical “id” and “class” attributes to the paragraphs being constructed. This ability makes it suitable to be used when displaying dynamic HTML pages.

So far, everything looks good and easy to grasp, right? As you saw before, the “TextHelper” class performs a few simple text-formatting tasks, which should give you a clear idea of how to build this kind of class in PHP 5.

I have to admit, though, that the class in its current incarnation doesn’t help very much in reality. That means that it’s time to extend its existing functionality.

In the following section, I’m going to add more methods to the previous helper class. Specifically, I’m going to give it more text-formatting options. Thus, to see how these methods will be defined, click on the link shown below and keep reading.

{mospagebreak title=Extending the functionality of the text helper class}

As you saw in the previous segment, the “TextHelper” class that I just built boasts limited functionality right now. To fix this issue, I’m going to enhance its capabilities by coding some additional methods, which will be tasked with applying a few useful text-formatting filters to an inputted string.

This being explained, please pay close attention to the corresponding definitions of these additional methods, which look like this:

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

public 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 function uppercase_all($str)

{

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

{

return strtoupper($str);

}

}

 

// lowercase all characters in string

public function lowercase_all($str)

{

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

{

return strtolower($str);

}

}

// uppercase first character in string

public function uppercase_first($str)

{

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

{

return ucfirst(strtolower($str));

}

}

As you can see above, I defined four extra methods for the text helper class. They apply some trivial formatting filters to a supplied string, such as converting its new lines into ‘<div>’ tags, and upper-casing and lowercasing its characters respectively.

Regardless of the rather rudimentary logic implemented by these methods, they do demonstrate how easy it is to create a helper class. From this point onward, and by using this example class as a reference, you may want to start developing your own text helper right now.

But before you do that, I suggest you take a look at the full source code of the helper class, which looks much more functional after adding the additional methods discussed previously.

Here’s the complete class:

class TextHelper

{

// constructor (not implemented)

public function __construct(){}

 

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

public function newline_br($str)

{

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

{

return nl2br($str);

}

}

 

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

public 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 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 function uppercase_all($str)

{

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

{

return strtoupper($str);

}

}

 

// lowercase all characters in string

public function lowercase_all($str)

{

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

{

return strtolower($str);

}

}

// uppercase first character in string

public function uppercase_first($str)

{

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

{

return ucfirst(strtolower($str));

}

}

}

Well, at this point I’m pretty sure that you understand the logic behind creating this basic text helper class. So if you want to see how it can be used for filtering a few strings, in the last section of this article I’m going to set up a concrete example for you, which will demonstrate the actual capabilities of the helper.

To see how this wrapping example will be developed, click on the link shown below and read the next few lines. We’re almost finished!

{mospagebreak title=The text helper class in action}

As I said in the previous section, it’s necessary to create an example that shows how to use the “TextHelper” class that you learned before to apply the filters to a given string. Therefore, please look at the following code sample, which  illustrates how to accomplish this process in a simple manner. Here it is:

// create an instance of TextHelper class

$txthelper = new TextHelper();

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

echo $txthelper->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 $txthelper->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 $txthelper->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 $txthelper->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 $txthelper->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 $txthelper->uppercase_first(‘the shinning is a scary book of Stephen King!’);

/* displays the following

The shinning is a scary book of stephen king!

*/

Definitely, the “TextHelper” class isn’t going to change the way you develop your PHP applications, but it’ll hopefully show you how to use their methods for applying different formatting filters to a supplied literal.

Of course, as I said before, the current functionality of the class can be largely improved, but this task will be left as homework for you, so you can entertain yourself for many hours.

Final thoughts

That’s all for now. In this first article of the series, I offered a friendly introduction to building helper classes with PHP 5. As you saw earlier, this process is extremely straightforward; it’s reduced to applying the basis of the object-oriented approach and nothing else.

In the upcoming part, I’m going to explain how to take advantage of the functionality offered by the previous text helper class without creating an instance of it, simply by statically calling their methods.

Don’t miss the next tutorial!

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

antalya escort bayan antalya escort bayan Antalya escort diyarbakir escort