Method Chaining in PHP 5

Method chaining is a useful technique that helps you to write more compact and powerful code. In this first part of a series that introduces you to this programming methodology, you’ll learn how to define and use chainable methods in PHP 5. The process is quite simple to grasp, even if you have only an intermediate background in using the object-oriented paradigm.

Over the course of the last few years PHP has reinvented itself; that’s why it’s the mature language that we see nowadays. The most significant change introduced by the PHP development team is the release of PHP 5, which incorporates a robust object model, a good exception handling mechanism, type hinting, the filter library, and many other features that you’ve probably used hundreds of times before.

While it’s true that PHP 5 does allow you to implement the object-oriented paradigm in a much more efficient and elegant manner, other fundamental concepts inherent to software programming can be applied to both PHP 4 and PHP 5 similarly.

To cite a few examples, common design patters like Factory, Singleton and Model-View-Controller (add your own to the list) can be implemented pretty easily in both versions of PHP, since they have to do more with proven programming methodologies than with the language’s intrinsic features.

One great technique that can be used when developing PHP applications is popularly known as method chaining. For those just learning PHP, it may sound intimidating, particularly if they’re not familiar with classes and objects and their methods, obviously. But the truth is that method chaining is an approach that can be mastered with minor efforts.

But, what is method chaining? Well, let me introduce you to the subject gently with a simple example that you’ll quickly grasp. Say that you’re building a MySQL abstraction class that implements some methods that will be used for performing queries against a selected database table.

In a typical situation, there will be only one method that will run SELECT statements, which should be used in conjunction with common query modifiers (such as WHERE, LIKE, LIMIT and ORDER BY SQL clauses) to perform conditional queries. However, it’s possible to implement multiple methods instead, where each one be will be responsible only for executing raw SELECTS, WHERE and ORDER BY clauses, and so forth.

With these methods coded in that way, it’s feasible to call them chained according to specific needs, and get a result set which can be processed in other clever ways. This chaining process can be easily accomplished by making the methods  return an instance of the MySQL abstraction class to calling code. Simple and effective.

High-quality frameworks like Kohana and CodeIgniter use method chaining within their database classes. In fact, Kohana will let you use method chaining with many other classes as well. Method chaining makes the code more compact and robust.

So, assuming that you’re interested in learning how to use method chaining within your own PHP applications, in this series of articles I’m going to create some examples that will show you how useful this approach can be. I’m going to start by developing a trivial string processor class to demonstrate the implementation of this approach. When I complete this application, I’ll build more complex programs. Now, let’s start discovering the real power behind method chaining in PHP 5!

{mospagebreak title=Building a simple string processor}

As I stated in the introduction, the best way to understand how to chain methods of a class is by way of a basic example. Thus, with that idea in mind, I’m going to build a simple string processor class that will be tasked with applying different filters to an input string, such as trimming white spaces, removing tags, capitalizing and lowercasing its characters and so forth. However, and here’s where method chaining comes in, the methods responsible for performing these tasks will be completely “chainable.”

Take a look at the initial definition for the aforementioned string processor class:

// define ‘StringProcessor’ class

class StringProcessor

{

private $str = ”;

private static $instance = NULL;

 

// constructor

public function __construct($str = ‘This is a default string’)

{

$this->str= $str;

}

 

// trim white space from input string

// chainable

public function trim_space()

{

$this->str = trim($this->str);

return $this;

}

 

// uppercase input string

// chainable

public function str_upper()

{

$this->str = strtoupper($this->str);

return $this;

}

 

// get input string

public function get_string()

{

return $this->str;

}

}

As you can see, the above “StringProcessor” class looks extremely simple. It implements only three basic methods, apart from the constructor. The first one trims white space from an inputted string; the second one is responsible for capitalizing its characters, and the last one returns the string in question.

As I said before, the logic of these methods is very easy to grasp. If you take a closer look at the first two, though, you’ll see that they return an instance of the class to calling code. What does this mean in simple terms? Well, they can be chained and used together to process an input string.

The best way to understand how these methods can be chained is by means of an example, so I coded it for you. Pay close attention:

 

$strproc = new StringProcessor(‘ Hello, this is a simple example of method chaining in PHP ‘);

// process string by chaining 3 methods

echo $strproc->trim_space()->

str_upper()->

get_string();

/*

displays the following

HELLO, THIS IS A SIMPLE EXAMPLE OF METHOD CHAINING IN PHP

*/

See how simple it is to chain the three methods implemented by the “StringProcessor” class to parse a trivial string? I guess you do. In this particular case, first the inputted string is trimmed, then it is upper cased, and finally it is echoed to the browser.

Of course, I’m not sating that you have to code all of your PHP classes using method chaining, but the above example shows in a nutshell how compact the whole code looks.

So far, so good. Now that you hopefully have a clearer idea of the logic that stands behinds utilizing chainable methods, it’s time to continue adding more methods to the “StringProcessor” class, which logically will be chainable as well.

To see how these brand new methods will be implemented, click on the link below and read the following section.

{mospagebreak title=Coding another chainable method}

Since my purpose here is to extend the functionality of the string processor in the previous section, I’m going to implement yet another chainable method. In this case, it will be tasked with lowercasing the characters of an inputted string.

Having explained that, here’s the enhanced version of the “StringProcessor” class, after including the method previously mentioned:

class StringProcessor

{

private $str = ”;

private static $instance = NULL;

 

// constructor

public function __construct($str = ‘This is a default string’)

{

$this->str= $str;

}

 

// trim white space from input string

// chainable

public function trim_space()

{

$this->str = trim($this->str);

return $this;

}

 

// uppercase input string

// chainable

public function str_upper()

{

$this->str = strtoupper($this->str);

return $this;

}

 

// lowercase input string

// chainable

public function str_lower()

{

$this->str = strtolower($this->str);

return $this;

}

 

// get input string

public function get_string()

{

return $this->str;

}

}

Here you have it. Now the above class implements a new method called “str_lower()" that’s charged with lowercasing the inputted string accepted by the class. Of course, the most relevant point to spot here is that this method is also chainable, meaning that it’s possible to use it in conjunction with the previous ones to parse a sample string.

This process is illustrated by the code sample below.

$strproc = new StringProcessor(‘ HELLO, THIS IS A SIMPLE EXAMPLE OF METHOD CHAINING IN PHP ‘);

// process string by chaining 3 methods

echo $strproc->trim_space()->

str_lower()->

get_string();

/*

displays the following

hello, this is a simple example of method chaining in php

*/

From the previous example, it’s clear to see how easy it is to code and use the “str_lower()” method defined earlier. Also, you should notice how compact and tight the code is when an instance of the “StringProcessor” class is utilized to make the sample string all lower case.

At this point, I’m pretty sure that you grasped the logic implemented by the “str_lower()” method, as well as the way it’s been turned into a chainable interface component. Therefore, in the last segment of this tutorial I’m going to extend the functionality of the string processor even more, by means of another chainable method.

To learn more about how this will be accomplished, go ahead and read the next few lines.

{mospagebreak title=Removing unwanted tags from input strings}

As I stated in the previous section, I’d like to finish this first chapter of the series by showing you how to provide the “StringProcessor” class with yet another chainable method. As you’ll see in a moment, it will be tasked with removing unwanted PHP and HTML tags from an input string.

The current definition of the class after implementing this whole new method looks like this:

class StringProcessor

{

private $str = ”;

private static $instance = NULL;

 

// constructor

public function __construct($str = ‘This is a default string’)

{

$this->str= $str;

}

 

// trim white space from input string

// chainable

public function trim_space()

{

$this->str = trim($this->str);

return $this;

}

 

// uppercase input string

// chainable

public function str_upper()

{

$this->str = strtoupper($this->str);

return $this;

}

 

// lowercase input string

// chainable

public function str_lower()

{

$this->str = strtolower($this->str);

return $this;

}

 

// remove eventual HTML and PHP tags from input string

// chainable

public function remove_tags()

{

$this->str = strip_tags($this->str);

return $this;

}

// get input string

public function get_string()

{

return $this->str;

}

}

Definitely, the implementation of the above “remove_tags()” method is very simple to follow. It’s merely a proxy method for the native “strip_tags()” native PHP function. But naturally, the most interesting facet of it rests on its ability to be chained to other methods, as demonstrated by the following code sample:

$strproc = new StringProcessor(‘ <p>Hello, this is a simple example of method chaining in PHP</p> ‘);

// process string by chaining 3 methods

echo $strproc->trim_space()->

remove_tags()->

get_string();

/*

displays the following

hello, this is a simple example of method chaining in php

*/

Now, the string processor class is capable of performing quite a few useful tasks on a given string, such as trimming white spaces, lowercasing and upper casing its characters, and finally removing tags by means of some chainable methods, whose implementation is really easy to grasp.

Of course, the class itself is not suited for production use, since it’s only a starting example that shows how to chain methods in PHP 5. However, and this would be homework for you, I suggest you try adding more chainable methods to the class, to give you more practice in this useful programming methodology.

Final thoughts

In this first installment of the series, I provided you with a hopefully gentle introduction to defining and using chainable methods in PHP 5. As you saw for yourself before, the whole process is quite simple to grasp, even if you have only an intermediate background in using the object-oriented paradigm.

Also, as you may have noticed, the string processor class built previously defines a static property called “$intance,” which has remained unused so far. Well, the reason for this is that I plan to create a factory method for the class that only returns singletons of it, and that also will be chainable.

This topic will be covered in depth in the next part of the series. Thus, you don’t have any excuses to miss it!

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

chat sex hikayeleri Ensest hikaye