INTERNALS OF SESSIONS

18 May

INTERNALS OF SESSIONS

When the session_start is called, PHP is looking for an argument from the client (sent via POST, GET or Cookie) with the name of session.name to retrieve the session ID.

If it finds a valid session ID (there are some syntactical restrictions), it tries to retrieve the session data from the storage (session.save_handler) to store it in $_SESSION.

If it can’t find an ID or the configuration forbids its usage (see session.use_cookies, session.use_only_cookies and session.use_trans_sid), PHP generates a new ID using a hash function (session.hash_function) on data of a source that generates random data (session.entropy_file).

At the end of the runtime, it stores the $_SESSION data in the designated storage.

1. Will session works, if cookies are disabled?
NO. In this case each call to session_start will generate a new ID as it can’t find the previous ID.

MVC architecture in PHP development

19 Jan

MVC stands for Model-View-Controller. It is a type of architecture for developing software, recently pretty popular in web applications development. In short, the three things are pretty simple. Model is what interacts with the database, it would be the backend class code for an object-oriented language like PHP, Ruby on Rails, or C++. View is basically the user interface. Controller is the logic that operates everything in between.

They are easy to explain, but sometimes the concept is a little abstract and it’s hard to grasp for someone who doesn’t know what MVC is to begin with. To be honest, all my years in web development I never really understood exactly what MVC is, until recently when I started doing development in Ruby on Rails. In this article, I hope to explain MVC architecture development in PHP terms, so the average web apps programmer may benefit from understanding this powerful architecture.

MVC and PHP development

The reason I mentioned Ruby on Rails is because you really have to understand how to develop an application with the MVC architecture to do anything at all on RoR. (Next time, I will write another article on RoR — but this time, I’ll talk about PHP development.)

The Model-View-Controller separation actually makes a lot of sense, it is actually natural for a developer to divide his/her code that way when working on a reasonably large application. Java has classes, JSP and struts; Ruby on Rails has a built-in MVC structure; but even when PHP doesn’t have anything like that, it doesn’t mean you can’t do it.

The Model

The MVC structure is meant for reasonably-sized applications, using object-oriented coding. The Model part, in a PHP app, would usually be a class (or multiple classes). Fairly often, the class is a representation of a table you store in the database — member variables are the data columns, and member methods are operations that can be done. As an example, you might have a User class, having variables such as username, password, email address, and other things. Some of its methods might be a new user creation function, a login function, an authentication function, and a logout function.

Later on, we will see how User objects will be used in the Controller part of your application. The Model, in essence, tells you what methods are available — what can you do to the data in the database. I thought I should just clarify (if it wasn’t clear already) — this should be all PHP code, just as what you should do in OO-programming even without MVC. There should be no HTML or any kinds of outputs (redirection, etc.) here. If doing an action means that a redirection is needed or some output is needed, pass it as an argument or a return value. (It’s fairly basic programming practices, but you’d be surprised how many web apps programmers didn’t graduate with a CS degree..)

Here’s an example of the Model part of your code. Of course, there will be many more classes in a real application. This is just the code is the simplest form, without a lot of the details.

class User
{
   var $username;
   var $password;
   var $email;
   function User($u, $p, $e) // constructor
   {
      $this->username = $u;
      $this->password = $p;
      $this->email = $e;
   }
   function create()
   {
      // creates user in the db
   }
   function login()
   {
      // checks against db, does login procedures
   }
   static function authenticate($u, $p)
   {
      // checks against db
   }
   function logout()
   {
      // does logout procedures
   }
}

The View

The View, in the simplest words, is the user interface. However, it doesn’t mean it would be just straight HTML. Minimal PHP logic will need to be used in your application’s interface a lot of times. For example, if you were to have the main logged-in page say, “Hello, [username]!” You would certainly need some PHP code to handle that, right? That is all part of the View. Of course, all the CSS, Javascript would be part of this too.

It is important that whatever PHP code in here is only what needs to be used to display the interface correctly. No additional “action” code belongs to the View — that is the Controller’s job, which we’ll see next.

This was easy to understand, but for clarification’s sake, let’s see an example anyway. Of course, the following isn’t even valid XHTML 1.0 (it lacks a DOCTYPE, for instance), but this is just an example.

<?php
require_once('User.php');
// makes sure user isn't already logged in
if (User::authenticate($_COOKIE['username'] )
{
   header(”Location:/main.php”);
   exit();
}
?>
<html>
<head><title>Please login</title></head>
<body>
<h1>Login</h1>
<?
if ($_GET['error'] == 1)
{
   echo ‘Login incorrect. Please try again.<br />’;
}
?>
<form action=”login_action.php” method=”post”>
User: <input type=”text” name=”username” /><br />
Pass: <input type=”password” name=”password” /><br />
<input type=”submit” value=”Login” />
</form>
</body>
</html>

The Controller

Sometimes it is confusing to understand what the Controller needs to do, if you weren’t working on an actual application and just reading a book/an article. It would seem like the Model and the View are all you need. So let’s go back to a concrete PHP example.

Now imagine you have a login page setup. The login HTML form has to submit to somewhere, right? (Even if you’re using AJAX) You don’t submit directly to the Model class file (say, User.php), because that file only contains the class code, and no actual procedural code is there, so it won’t do anything. You certainly don’t submit directly back to the View file (say, login.php), even if it ends with a .php extension! Because its job is only to display the interface.

This is what the Controller is. Your form will submit to a file, say, login_action.php. In this file, you create an instance of the User class, running whatever initialization you need, and calling the appropriate methods that need to be run (login).

Some developers fall into the temptation to display outputs from the Controller, because it’s convenient. Imagine, if you had a login form, how easy is it to just print “Login incorrect” directly from the Controller PHP code? (assuming you aren’t using AJAX, for this particular example) It is an option, and I will tell you that many scripts do just that. However, to truly utilize a MVC structure’s advantage, the Controller (like the Model) should not display any HTML outputs, but rather use redirection. You may use cookies/sessions, database storage, flat file caching, or query string to the View file to store the states of your application; and then you should always let the View take care of displaying outputs, using these stored states.

Now let’s see an example of a Controller code.

<?php
require_once('User.php');
// in reality, a lot more error checking needs to be done.
$currentuser = new User($_POST['username'], $_POST['password'], ”);
if ($currentuser->login())
{
   // set cookies for login info
   header(”Location:/main.php”);
   exit();
}
else
{
   header(”Location:/login.php?error=1″);
   exit();
}
?>

Conclusion

Using the MVC structure, code becomes a lot easier to understand. For other developers to join in to understand your code, as well as for yourself in the future when you come back to it after a while. Development is also a lot easier because you know exactly where to look for what piece of code. If you were going to change some message displaying in the interface, you only need to go to the View. If your database structure sees a change, such as passwords now encrypting in a different way, you only need to change your Model. The MVC architecture is very powerful and makes your object-oriented web apps development a lot more efficient.

Create a PHP web crawler or scraper in 5 minutes

19 Jan

Utilizing the PHP programming language we show you how to create an infinitely extendable web crawler in under 5 minutes, collecting images and links.

The Crawler Framework

First we need to create the crawler class as follows:

<?php
class Crawler {

}

?>

We then will create methods to fetch the web pages markup, and to parse it for data that we are looking at collecting. The only public methods will be getMarkup() and get() as the parsing methods will generally be used privately for the crawler, however the visibility is set to protected since you never know who will want to extend its functionality.

<?php
class Crawler {

protected

$markup = '';

public function

__construct($uri) {

}

public function

getMarkup() {

}

public function

get($type) {

}

protected function

_get_images() {

}

protected function

_get_links() {

}
}

?>

Fetching Site Markup

The constructor will accept a URI so we can instantiate it such as new Crawler(‘http://vision-media.ca&#8217;); which then will set our $markup property using PHP’s file_get_contents() function which fetches the sites markup.

<?php
public function __construct($uri) {
$this->markup = $this->getMarkup($uri);
}

public function

getMarkup($uri) {
return
file_get_contents($uri);
}
?>

Crawling The Markup For Data

Our get() method will accept a $type string which essentially will simply be used to invoke another method actually doing the processing. As you can see below we construct the method name as a string, then make sure it is available so now developers can utilize this simply by invoking $crawl->get(‘images’);

We set visibility for _get_images() and _get_links() to protected so that developers will use our public get() method rather than getting confused and trying to invoke them directly.

Each protected data collection method simply uses the PCRE (Perl Compatible Regular Expressions) function preg_match_all() in order to return all tags within the markup that are accepted using our patterns of /<img([^>]+)\/>/i and /<a([^>]+)\>(.*?)\<\/a\>/i. For more information on regular expressions visit http://en.wikipedia.org/wiki/Regular_expression

<?php
public function get($type) {
$method = "_get_{$type}";
if (
method_exists($this, $method)){
return
call_user_method($method, $this);
}
}

protected function

_get_images() {
if (!empty(
$this->markup)){
preg_match_all('/<img([^>]+)\/>/i', $this->markup, $images);
return !empty(
$images[1]) ? $images[1] : FALSE;
}
}

protected function

_get_links() {
if (!empty(
$this->markup)){
preg_match_all('/<a([^>]+)\>(.*?)\<\/a\>/i', $this->markup, $links);
return !empty(
$links[1]) ? $links[1] : FALSE;
}
}
?>

Final PHP Web Crawler Code And Usage

<?php
class Crawler {

protected

$markup = '';

public function

__construct($uri) {
$this->markup = $this->getMarkup($uri);
}

public function

getMarkup($uri) {
return
file_get_contents($uri);
}

public function

get($type) {
$method = "_get_{$type}";
if (
method_exists($this, $method)){
return
call_user_method($method, $this);
}
}

protected function

_get_images() {
if (!empty(
$this->markup)){
preg_match_all('/<img([^>]+)\/>/i', $this->markup, $images);
return !empty(
$images[1]) ? $images[1] : FALSE;
}
}

protected function

_get_links() {
if (!empty(
$this->markup)){
preg_match_all('/<a([^>]+)\>(.*?)\<\/a\>/i', $this->markup, $links);
return !empty(
$links[1]) ? $links[1] : FALSE;
}
}
}

$crawl = new Crawler('http://vision-media.ca');
$images = $crawl->get('images');
$links = $crawl->get('links');
?>

Using POST method in XMLHTTPRequest(Ajax)

19 Jan

Usually only the GET method is used while creating Ajax apps. But there are several occasions when POST is necessary when creating a ajax request. This could be for several reasons. For example, POST request are considered more secure than GET request as creating a POST request is relatively harder than creating a GET request.

Requirements

  • Create a XMLHTTPRequest Object that uses the POST method.
  • See if the arguments passed to it appear in the ‘$_POST‘ array in PHP.

Code

XMLHTTPRequest Object

For the sake of simplicity, we are going to create the XMLHTTPRequest object using the Firefox supported ‘ XMLHttpRequest()’ function. I believe that you know the proper way of creating a cross-browser XMLHttpRequest object. If not, learn that first.

var http = new XMLHttpRequest();

Using GET method

Now we open a connection using the GET method.


var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("GET", url+"?"+params, true);
http.onreadystatechange = function() {//Call a function when the state changes.
	if(http.readyState == 4 && http.status == 200) {
		alert(http.responseText);
	}
}
http.send(null);

I really hope that this much is clear for you – I am assuming that you know a bit of Ajax coding. If you don’t, please read a ajax tutorial that explains these parts before continuing.

POST method

We are going to make some modifications so POST method will be used when sending the request…


var url = "get_data.php";
var params = "lorem=ipsum&name=binny";
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

http.onreadystatechange = function() {//Call a function when the state changes.
	if(http.readyState == 4 && http.status == 200) {
		alert(http.responseText);
	}
}
http.send(params);

The first change(and the most obvious one) is that I changed the first argument of the open function from GET to POST. Also notice the difference in the second argument – in the GET method, we send the parameters along with the url separated by a ‘?’ character…

http.open("GET",url+"?"+params, true);

But in the POST method we will use just the url as the second argument. We will send the parameters later.

http.open("POST", url, true);

Some http headers must be set along with any POST request. So we set them in these lines…

http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

With the above lines we are basically saying that the data send is in the format of a form submission. We also give the length of the parameters we are sending.

http.onreadystatechange = function() {//Call a function when the state changes.
	if(http.readyState == 4 && http.status == 200) {
		alert(http.responseText);
	}
}

We set a handler for the ‘ready state’ change event. This is the same handler we used for the GET method. You can use the http.responseText here – insert into a div using innerHTML(AHAH), eval it(JSON) or anything else.

http.send(params);

Finally, we send the parameters with the request. The given url is loaded only after this line is called. In the GET method, the parameter will be a null value. But in the POST method, the data to be send will be send as the argument of the send function. The params variable was declared in the second line as “lorem=ipsum&name=binny” – so we send two parameters – ‘lorem’ and ‘name’ with the values ‘ipsum’ and ‘binny’ respectively.

That’s it. If you wish to see the working of this script, I have set up a demo page for Ajax using post.

Libraries

The above given methods are the manual way of doing things – you can automate this using the hundreds of Ajax libraries out there.

jx


jx.load("get_data.php?lorem=ipsum&name=binny",handlerFunction,"text","POST");

Prototype

var myAjax = new Ajax.Request('get_data.php?lorem=ipsum&name=binny',{
	method: 'post',
	onComplete:handlerFunction
});

Dojo Toolkit

dojo.io.bind({
	url:        "get_data.php?lorem=ipsum&name=binny",
	mimetype:   "text/plain",
	method:		"POST",
	load:handlerFunction
});

Update Multiple Page Elements Using The XMLHTTPRequest Object and JavaScript

19 Jan

In the development of Ajax application many times we will encounter following issues.

  • The requiremnt to update multiple text boxes simultaneously.
  • Fill more that one dropdown list.
  • Update a combination of text boxes, dropdown lists and div tags.
  • Call different web pages and different webservices at the same time.

Imagine the case of a financial data site (such as a stock market info site) with various regions of the page used for displaying data any taking user inputs. We may want to populate fill numerous div tags, textboxes and dropdown lists with real time data. If we loop the several requests and we will also have to check for timeout, if timeout occurs and no data is returned, then we will have to fire the same request again. It may end up that we have made 10 requests and 4-5 requests simply timeout because of network problems. If we dont loop then we will either get whole data or nothing (in which case there is only one more request to be made).

In this article we will discuss the XMLHTTPRequest object and JavaScript and develop a JavaScript class which can asychronously update multiple HTML elements. Also this class can be extended as per the requirements. I have used ASP.NET as the platform in this example but it does as the solution is just Javascript it can be applied to any web development platform.

Regarding classes in JavaScript, technically there is no ‘class’ in JavaScript but we can use a function as a class.

Consider the following code :

function testClass()
{
this.Msg = “Hello”;
this.showMsg = function()
{
alert(this.Msg);
}
}

var obj = new testClass();
obj.Msg = “HI”;
obj.showMsg();

In above script if we remove obj.Msg = “HI”; we will get an alert with text Hello.

We will now develop our JavaScript class step-by-step:

  1. Include JS file and add the following code:

function AjaxClass()
{
this.Method = “GET”;//OR “POST”
this.Async = true; //OR false (asynchronous or synchronous call)
this.request = null;
this.init = function()
{
if (window.XMLHttpRequest) // if Mozilla, Safari etc
this.request = new XMLHttpRequest();
else if (window.ActiveXObject)
{ // if IE
try
{
this.request = new    ActiveXObject(“Msxml2.XMLHTTP”);
}
catch (e)
{
try
{
this.request = new ActiveXObject(“Microsoft.XMLHTTP”);
}
catch (e){}
}
}

if(this.request)
{
this.request.onreadystatechange=this.handleResponse;
//we will develope this.handleResponse function in step 3
this.request.open(this.Method, this.url , this.Async);
this.request.send(null);
}
}
}

Here we have created an XMLHTTPRequest object which is simply used to send a call to the server. The default method is GET (this.Method = “GET”) and calling type is Ascynchronous (this.Async = true)

  1. In this step we will develop simple logic which will allow us to dynamically call Ajax function created in Step 1.

For this one JSON (http://www.json.org/) object as follows.

this.JSONArray = {  “Method” : “POST”, //Method type
“Async”  : true, //Call type
“CallPage” : “CallPage.aspx”, //page or webservice
“Querystring” : “”, //Query string
“dependentType” : null,//[0,1,2,3] for isEdit
“isEdit”: [
{
“textBoxId” : null, //0 then this element
“dropDownId” : null, //1 then this element
“default” : null, //2 then this element
“misc”:null //3 then this element
}
]

};

In above script we can set the default values for all elements. We will use these values to set response from the server to textboxes,drop down lists,Div tags, td tags etc. Using “CallPage” : “CallPage.aspx” we can define default server page and while calling Ajax function we can change this value to web method or to any other web page.
As we will proceed in this article we will examine how to change all the above values and how can we use it to update multiple elements.Also we will see that how to extend the class.

  1. Recall from Step 1 : this.request.onreadystatechange = this.handleResponse;

In this step we will develop this.handleResponse function and in this function we will use the JSON object defined in Step 2. Whenever this.handleResponse function gets called script loses the focus of  this. To keep track of this object we will asign it to some variable. i.e var self = this; // To lose of focus of the element

In this function we will be able to receive data from server. Once we receive the data we can manipulate it. This function will handle the responses from web services as well as from web pages. The web service always returns a response in the form of XML whereas the response from the webpage can be any format defined by web developer.

The function will be as follows:

var self = this; // To handle lose of focus
this.handleResponse = function()
{
if(self.request.readyState == 4 && self.request.status == 200)
{
if (window.ActiveXObject) // for IE
{
var doc=new ActiveXObject(“Microsoft.XMLDOM”);
doc.async=”false”;
doc.loadXML(self.request.responseText);
}
// code for Mozilla, Firefox, Opera, etc.
else
{
var parser=new DOMParser();
var doc=parser.parseFromString(self.request.responseText,”text/xml”);
}
try
{
var data  = “”;
if(doc.documentElement) //Response from webservice
data = doc.documentElement.childNodes[0].nodeValue;
else data = self.request.responseText; //from web page
//data contains response text from the server

//At this point we have response from serve
//so here we will write our function to    //manipulate the data. We will develop it in
//4th step.
}
catch(e) {}
}

In the the 1st step we had:

if(this.request)
{
this.request.onreadystatechange=this.handleResponse;
this.request.open(this.Method, this.url , this.Async);
this.request.send(null);
}

We will now modify this so that we can directly use the JSON array which we defined in 2nd step:

if(this.request)
{
this.request.onreadystatechange=this.handleResponse;
this.request.open(this.JSONArray.Method, this.url , this.JSONArray.Async);
this.request.send(null);
}

While developing Ajax applications we ned to be aware of the following issues regarding domains:

  • URL for XMLHTTPRequest object should belong to same domain.
  • Firefox and other browser doesn’t allow cross domain communication.
  • IE will show warning for cross domain communication.

Thus our this.url = “http://myDomain/mysite/” + this.JSONArray.CallPage + this.JSONArray.Querystring;

e.g. “http://localhost/Demo/CallPage.aspx?”+this.JSONArray.Querystring;
Also whenever we want to call web methods like above example, we need to set following protocols under <webServices> in web.config file.

<webServices>
<protocols>
<add name=”HttpGet”/>
<add name=”HttpPost”/>
</protocols>
</webServices>

  1. Up to this point we have finished with development of the Ajax logic which will return a response. So now we need to develop logic for updating the HTML controls.

In this.handleResponse (step 3) we have seen that we get response in the “data” variable in JavaScript.

So now we have response from the server we will add following logic:

switch(self.JSONArray.dependentType)
{
case 0:
PopulateControls(self.JSONArray.isEdit[0].textBoxId,data);
//simple call to JS function
break;
case 1:
PopulateControls(self.JSONArray.isEdit[0].dropDownId,data);
break;
}


self.JSONArray.isEdit[0].textBoxId
will contain the id of the text box in which we need to update. And data is the response from the server. In our switch we have simply used the elements of JSON object developed in Step 2.

We will now focus on initiating a request and setting the elements of the JSON objects.

First simply create object of our AjaxClass().

var obj = new AjaxClass(); //Object creation
obj.JSONArray.Method = “GET”; //Setting Method
obj.JSONArray.isEdit[0].textBoxId=”txt1″;//Textboxid for response
obj.JSONArray.dependentType=0;//0->Textbox,1->drop downlist,
//2->tagId,3->Misc and so on
obj.init();//Initiate the AjaxCall

If obj.JSONArray.dependentType=1 then our switch case will not work for the textbox, but it will work for a dropdown list (check above switch case). This means we will have to set the dropdown in the JSON object:

obj.JSONArray.isEdit[0].dropDownId=”ddl1″;

In this way we can define our own set of HTML controls to be updated.

In the same way we can also change all the default settings in JSON object of that class.

e.g.

obj.JSONArray.Method = “GET”;
obj.JSONArray.CallPage = “Mywebservice/webMethod”;
obj.JSONArray.Querystring= “My querystring”;

For this URL will be : this.url = this.url + this.JSONArray.CallPage + this.JSONArray.Querystring ;

In case of a web service we will have to set the CallPage element as we did in the above example.

For multiple textboxes use: obj.JSONArray.isEdit[0].textBoxId=”txt1$txt2$txtn”;//$ is a delimiter
While sending data from the server send it with the same delimiter,in such a way when we split obj.JSONArray.isEdit[0].textBoxId and response data on $; we will receive data and the appropriate textBoxId.

Now that we have different types like “txtbox(es) + drop down list(s) + div” in such case we can use “misc” option of isEdit element of JSON object.

And we can define our  PopulateControls function the way we want. For ASP.NET we could also integrate ICallback logic for large data transfers.

You can download the demo code here . This contains an ASP.NET project with the following files:

  • XMLHTTPJsClass.js this file contains our AjaxClass() and funtion to populate textbox(es).
  • Demo.js this file contains 3 js function which initiates AjaxRequest with customization of  request. Here you can find web page and webservice calls.
  • Default.aspx page
  • Webservice.asmx page.


Getting started with AJAX using PHP

19 Jan

AJAX stands for Asynchronous JavaScript And XML. Any server side technology that supports JavaScript also supports AJAX. AJAX is a browser technology, and is therefore independent of web server platforms.

In this article we will learn about what AJAX is, how it works, and how can we use AJAX with PHP. Please remember, AJAX is not a programming language, so you don’t have to learn any new technology. AJAX can be implemented by using existing standards (JavaScript and XML) in a different way.

If we are using PHP or any server side technology and need to extract data from storage on a server (eg a database or a file), we will have to make an HTTP request (either POST or GET) to get the data. Once the data is received the the web page will need to be reloaded to show the data. Using AJAX technology we can request and receive the data from server in background and then display it on the page without a reload. AJAX uses HTTP requests for this. With AJAX, JavaScript communicates directly with the server, through the JavaScript XMLHttpRequest object (XML over HTTP). With an HTTP request, a web page can make a request to, and get a response from a web server without reloading the page.
The XMLHttpRequest object is supported in Internet Explorer 5.0+, Safari 1.2, Mozilla 1.0 / Firefox, Opera 8+, and Netscape 7. But the creation of XMLHttpRequest object is different in Internet Explorer than the other browsers. I will discuss this later. To use AJAX to request a data from the server we need to do the following.

1. Create an XMLHttpRequest object.
2. Then using this object, request data from the server.
3. JavaScript will then monitor for the changing of state of the request.
4. If the response is successful, then the content from the data store requested will be returned as response (response can be in the form of a String or XML).
5. Use the response in your web page.

1. Create an XMLHttpRequest object

JavaScript has a built-in XMLHttpRequest object. You can use that for Firefox, Safari, and Opera. For Internet Explorer use the ActiveXObject, there is also a difference between IE 5.0 and IE 6.0+ in how to create the object. The following codes creates an XMLHttpRequest for all browsers:

var req;

if(window.XMLHttpRequest){
//For Firefox, Safari, Opera
req = new XMLHttpRequest();
}
else if(window.ActiveXObject){
//For IE 5
req = new ActiveXObject(“Microsoft.XMLHTTP”);
} else if(window.ActiveXObject){
//For IE 6+
req = new ActiveXObject(“Msxml2.XMLHTTP”);
}
else{
//Error for an old browser
alert(‘Your browser is not IE 5 or higher, or Firefox or Safari or Opera’);
}

Here, first we are using the built-in JavaScript function XMLHttpRequest() for creating an XMLHttpRequest for Firefox, Safari and Opera. If the browser does support window.ActiveXObject, then it is Internet Explorer. For IE versions 5.0+, use new ActiveXObject(“Microsoft.XMLHTTP”) and for IE 6.0+ use new ActiveXObject(“Msxml2.XMLHTTP”). If the browser does not support the built-in JavaScript function XMLHttpRequest() or ActiveXObject, then it does not support AJAX. You can also use JavaScript try-catch blocks for the same output.

var req;
try
{
// Firefox, Opera, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject(“Msxml2.XMLHTTP”);
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject(“Microsoft.XMLHTTP”);
}
catch (e)
{
alert(‘Your browser is not IE 5 or higher, or Firefox or Safari or Opera’);
}
}
}

In JavaScript, if statements within a try section fail, then the execution resumes from the corresponding catch block. Here first we are trying to get create a XMLHttpRequest using the built-in function, and if it fails then we will try using ActiveXObject(“Msxml2.XMLHTTP”), and if it fails also we will try ActiveXObject(“Microsoft.XMLHTTP”). If all these fail, then we will alert the user that his/her browser does not support AJAX.

2. Request for a web page

After creating the XMLHttpRequest we now need to send the web request using the open method. We also need to specify the HttpRequest method, GET or POST. Use the following code to send the request.

req.open(“GET”,”somedata.php”);
req.send(null);

Here, req is the XMLHttpRequest object. It will request to the server for somedata.php using GET method. The open function also has a third parameter, an optional boolean parameter. You should set that to true :

req.open(“GET”,”somedata.php”,true);
req.send(null);

Both of the above is correct.

3. Monitor for the response of the request

You will need to monitor for the state of the request. For doing this you can assign a function to req.onreadystatechange (Here, req is the XMLHttpRequest object), like below.

req.onreadystatechange=function()
{
if(req.readyState==4 && req.status == 200)
{
var resp = req.responseText;
}
}

Or like this,

req.onreadystatechange = handleResponse;

function handleResponse(){
if(req.readyState == 4 && req.status == 200){
//returned text from the PHP script
var response = req.responseText;
}
}

The readyState property holds the status of the server’s response. Each time the readyState changes, the onreadystatechange function will be executed. Here are the possible values for the readyState property:
State Description
0 The request is not initialized
1 The request has been set up
2 The request has been sent
3 The request is in process
4 The request is complete

And status is the status of the HTTP Request, like 500 Internal Server Error, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found etc. 200 means no error.

4. Get the response

The response will be as string or as XML. The data sent back from the server can be retrieved with the responseText property as string. Use responseXML for getting the response as XML.

5. Use the response on your web page

You can use the response you got from the XMLHttpRequest in your web page/application. You can either set a value of a text field or use the returned HTML from the web request as innerHTML for a <div></div> tag or <span></span> tag (See below for the implementation of this)

Using AJAX with PHP

I usually place all the AJAX related functions in one JavaScript (ajax.js), and later add the JavaScript in my PHP pages. My ajax.js looks like below.

function createRequestObject(){

var req;

if(window.XMLHttpRequest){
//For Firefox, Safari, Opera
req = new XMLHttpRequest();
}
else if(window.ActiveXObject){
//For IE 5+
req = new ActiveXObject(“Microsoft.XMLHTTP”);
}
else{
//Error for an old browser
alert(‘Your browser is not IE 5 or higher, or Firefox or Safari or Opera’);
}

return req;
}

//Make the XMLHttpRequest Object
var http = createRequestObject();

function sendRequest(method, url){
if(method == ‘get’ || method == ‘GET’){
http.open(method,url,true);
http.onreadystatechange = handleResponse;
http.send(null);
}
}

function handleResponse(){
if(http.readyState == 4 && http.status == 200){
var response = http.responseText;
if(response){
document.getElementById(“ajax_res”).innerHTML = response;
}
}
}

Now I add a <script></script> tag in my PHP pages like following to access the JavaScript functions.

Then I create a function called sendReq() as shown above for preparing the URL to the PHP page to get some data from the database. If you look into the ajax.js, you will see that I’m assigning the output of the PHP page to a <div> tags innerHTML. My div tag has the id=’ajax_res’.

<div align=”center” class=”black” id=”ajax_res”>
<img src=”wt_bg.jpg”>
</div>

After calling the sendReq function with a value of ‘success’, it will connect to the server for sending a request to the URL get_lcm.php?status=success, then get the data from the database using the value ‘success’, and set the innerHTML attribute of the div tag whose id is ‘ajax_res’ according to the response. Initially my div tag shows an image, but after AJAX responds successfully this image will be replaced with the response. You can also get the response as the value of an input text.

My get_lcm.php looks like this.

<?php
include_once(“create_table.php”);

if(!empty($status)){
echo “<strong>Search Result for Status: “.$status.”</strong><br><br>”;

$ct = new createtable(“select * from lcm where state=$status”);

$ct->table_viewer();
}
?>

I used one of my PHP classes ‘create_table.php’ for creating a table from SQL queries. ‘create_table.php’ has a function, table_viewer(), to print the SQL output as a HTML table. I will discuss about this class and some other data abstraction classes I used in some later articles, if necessary.

I had the following HTML code for calling the AJAX function using the sendReq() as described earlier.

<a class=”none” href=”#” onClick=”sendReq(1)”>ACTIVE</a>

If a user clicks the above hyperlink, then the JavaScript function sendReq is invoked using the value of status equal to 1. After that the webpage with URL get_lcm.php?status=1 will be invoked. This PHP will get the information from database and shows the result as table. This result will then be displayed within the <div> tag.

Using AJAX from PHP is very easy as described here. All you need is the JavaScript functions for sending the XMLHttpRequest and then handle the Http Response. It will simplify development is you place all your AJAX related code in a single JavaScript file and reference it from anywhere you need AJAX.

There is another way of getting the same result from PHP without using the XMLHttpRequest object. But I personally do not like the concept, because it is missing one of the main ingredients of Asynchronous JavaScript And XML (AJAX), XML. This concept is good for the old browsers with no supports for XMLHttpRequest object, but as all the newer versions are supporting XMLHttpRequest object you can use AJAX for the common browsers.

Design Patterns in PHP

19 Jan


v\:* {behavior:url(#default#VML);}
o\:* {behavior:url(#default#VML);}
w\:* {behavior:url(#default#VML);}
.shape {behavior:url(#default#VML);}
<!– /* Font Definitions */ @font-face {font-family:Courier; panose-1:2 7 4 9 2 2 5 2 4 4; mso-font-alt:”Courier New”; mso-font-charset:0; mso-generic-font-family:modern; mso-font-format:other; mso-font-pitch:fixed; mso-font-signature:3 0 0 0 1 0;} @font-face {font-family:Verdana; panose-1:2 11 6 4 3 5 4 4 2 4; mso-font-charset:0; mso-generic-font-family:swiss; mso-font-pitch:variable; mso-font-signature:536871559 0 0 0 415 0;} @font-face {font-family:”Lucida Console”; panose-1:2 11 6 9 4 5 4 2 2 4; mso-font-charset:0; mso-generic-font-family:modern; mso-font-pitch:fixed; mso-font-signature:-2147482993 6144 0 0 31 0;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-parent:””; margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; font-size:12.0pt; font-family:”Times New Roman”; mso-fareast-font-family:”Times New Roman”;} h1 {mso-margin-top-alt:auto; margin-right:0in; mso-margin-bottom-alt:auto; margin-left:0in; mso-pagination:widow-orphan; mso-outline-level:1; font-size:16.5pt; font-family:Arial; color:black; font-weight:bold;} p {mso-margin-top-alt:auto; margin-right:0in; mso-margin-bottom-alt:auto; margin-left:0in; mso-pagination:widow-orphan; font-size:12.0pt; font-family:”Times New Roman”; mso-fareast-font-family:”Times New Roman”;} code {mso-ansi-font-size:11.0pt; mso-bidi-font-size:11.0pt; font-family:Courier; mso-ascii-font-family:Courier; mso-fareast-font-family:”Times New Roman”; mso-hansi-font-family:Courier; mso-bidi-font-family:”Courier New”;} pre {margin:0in; margin-bottom:.0001pt; mso-pagination:widow-orphan; tab-stops:45.8pt 91.6pt 137.4pt 183.2pt 229.0pt 274.8pt 320.6pt 366.4pt 412.2pt 458.0pt 503.8pt 549.6pt 595.4pt 641.2pt 687.0pt 732.8pt; font-size:10.0pt; font-family:”Courier New”; mso-fareast-font-family:”Times New Roman”;} span.atitle1 {mso-style-name:atitle1; mso-ansi-font-size:19.0pt; mso-bidi-font-size:19.0pt; font-family:Arial; mso-ascii-font-family:Arial; mso-hansi-font-family:Arial; mso-bidi-font-family:Arial; font-weight:bold;} @page Section1 {size:8.5in 11.0in; margin:1.0in 1.25in 1.0in 1.25in; mso-header-margin:.5in; mso-footer-margin:.5in; mso-paper-source:0;} div.Section1 {page:Section1;} /* List Definitions */ @list l0 {mso-list-id:1565407075; mso-list-template-ids:26618656;} @list l0:level1 {mso-level-tab-stop:.5in; mso-level-number-position:left; text-indent:-.25in;} ol {margin-bottom:0in;} ul {margin-bottom:0in;} –>
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:”Table Normal”;
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-parent:””;
mso-padding-alt:0in 5.4pt 0in 5.4pt;
mso-para-margin:0in;
mso-para-margin-bottom:.0001pt;
mso-pagination:widow-orphan;
font-size:10.0pt;
font-family:”Times New Roman”;
mso-ansi-language:#0400;
mso-fareast-language:#0400;
mso-bidi-language:#0400;}

Design patterns were introduced to the software community in Design Patterns, by Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides (colloquially known as the “gang of four”). The core concept behind design patterns, presented in the introduction, was simple. Over their years of developing software, Gamma et al found certain patterns of solid design emerging, just as architects designing houses and buildings can develop templates for where a bathroom should be located or how a kitchen should be configured. Having those templates, or design patterns, means they can design better buildings more quickly. The same applies to software.

Design patterns not only present useful ways for developing robust software faster but also provide a way of encapsulating large ideas in friendly terms. For example, you can say you’re writing a messaging system to provide for loose coupling, or you can say you’re writing an observer, which is the name of that pattern.

It’s difficult to demonstrate the value of patterns using small examples. They often look like overkill because they really come into play in large code bases. This article can’t show huge applications, so you need to think about ways to apply the principles of the example — and not necessarily this exact code — in your larger applications. That’s not to say that you shouldn’t use patterns in small applications. Most good applications start small and become big, so there is no reason not to start with solid coding practices like these.

Now that you have a sense of what design patterns are and why they’re useful, it’s time to jump into five common patterns for PHP V5.

The factory pattern

Many of the design patterns in the original Design Patterns book encourage loose coupling. To understand this concept, it’s easiest to talk about a struggle that many developers go through in large systems. The problem occurs when you change one piece of code and watch as a cascade of breakage happens in other parts of the system — parts you thought were completely unrelated.

The problem is tight coupling. Functions and classes in one part of the system rely too heavily on behaviors and structures in other functions and classes in other parts of the system. You need a set of patterns that lets these classes talk with each other, but you don’t want to tie them together so heavily that they become interlocked.

In large systems, lots of code relies on a few key classes. Difficulties can arise when you need to change those classes. For example, suppose you have a User class that reads from a file. You want to change it to a different class that reads from the database, but all the code references the original class that reads from a file. This is where the factory pattern comes in handy.

The factory pattern is a class that has some methods that create objects for you. Instead of using new directly, you use the factory class to create objects. That way, if you want to change the types of objects created, you can change just the factory. All the code that uses the factory changes automatically.

Listing 1 shows an example of a factory class. The server side of the equation comes in two pieces: the database, and a set of PHP pages that let you add feeds, request the list of feeds, and get the article associated with a particular feed.


Listing 1. Factory1.php

                
<?php
interface IUser
{
  function getName();
}
 
class User implements IUser
{
  public function __construct( $id ) { }
 
  public function getName()
  {
    return "Jack";
  }
}
 
class UserFactory
{
  public static function Create( $id )
  {
    return new User( $id );
  }
}
 
$uo = UserFactory::Create( 1 );
echo( $uo->getName()."\n" );
?>

An interface called IUser defines what a user object should do. The implementation of IUser is called User, and a factory class called UserFactory creates IUser objects. This relationship is shown as UML in Figure 1.


Figure 1. The factory class and its related IUser interface and user class
The factory class and its related IUser interface and user class

If you run this code on the command line using the php interpreter, you get this result:

% php factory1.php 
Jack
%

The test code asks the factory for a User object and prints the result of the getName method.

A variation of the factory pattern uses factory methods. These public static methods in the class construct objects of that type. This approach is useful when creating an object of this type is nontrivial. For example, suppose you need to first create the object and then set many attributes. This version of the factory pattern encapsulates that process in a single location so that the complex initialization code isn’t copied and pasted all over the code base.

Listing 2 shows an example of using factory methods.


Listing 2. Factory2.php

                
<?php
interface IUser
{
  function getName();
}
 
class User implements IUser
{
  public static function Load( $id ) 
  {
        return new User( $id );
  }
 
  public static function Create( ) 
  {
        return new User( null );
  }
 
  public function __construct( $id ) { }
 
  public function getName()
  {
    return "Jack";
  }
}
 
$uo = User::Load( 1 );
echo( $uo->getName()."\n" );
?>

This code is much simpler. It has only one interface, IUser, and one class called User that implements the interface. The User class has two static methods that create the object. This relationship is shown in UML in Figure 2.


Figure 2. The IUser interface and the user class with factory methods
The IUser interface and the user class with factory methods

Running the script on the command line yields the same result as the code in Listing 1, as shown here:

% php factory2.php 
Jack
%

As stated, sometimes such patterns can seem like overkill in small situations. Nevertheless, it’s still good to learn solid coding forms like these for use in any size of project.

The singleton pattern

Some application resources are exclusive in that there is one and only one of this type of resource. For example, the connection to a database through the database handle is exclusive. You want to share the database handle in an application because it’s an overhead to keep opening and closing connections, particularly during a single page fetch.

The singleton pattern covers this need. An object is a singleton if the application can include one and only one of that object at a time. The code in Listing 3 shows a database connection singleton in PHP V5.


Listing 3. Singleton.php

                
<?php
require_once("DB.php");
 
class DatabaseConnection
{
  public static function get()
  {
    static $db = null;
    if ( $db == null )
      $db = new DatabaseConnection();
    return $db;
  }
 
  private $_handle = null;
 
  private function __construct()
  {
    $dsn = 'mysql://root:password@localhost/photos';
    $this->_handle =& DB::Connect( $dsn, array() );
  }
  
  public function handle()
  {
    return $this->_handle;
  }
}
 
print( "Handle = ".DatabaseConnection::get()->handle()."\n" );
print( "Handle = ".DatabaseConnection::get()->handle()."\n" );
?>

This code shows a single class called DatabaseConnection. You can’t create your own DatabaseConnection because the constructor is private. But you can get the one and only one DatabaseConnection object using the static get method. The UML for this code is shown in Figure 3.


Figure 3. The database connection singleton
The database connection singleton

The proof in the pudding is that the database handle returned by the handle method is the same between two calls. You can see this by running the code on the command line.

% php singleton.php 
Handle = Object id #3
Handle = Object id #3
%

The two handles returned are the same object. If you use the database connection singleton across the application, you reuse the same handle everywhere.

You could use a global variable to store the database handle, but that approach only works for small applications. In larger applications, avoid globals, and go with objects and methods to get access to resources.

The observer pattern

The observer pattern gives you another way to avoid tight coupling between components. This pattern is simple: One object makes itself observable by adding a method that allows another object, the observer, to register itself. When the observable object changes, it sends a message to the registered observers. What those observers do with that information isn’t relevant or important to the observable object. The result is a way for objects to talk with each other without necessarily understanding why.

A simple example is a list of users in a system. The code in Listing 4 shows a user list that sends out a message when users are added. This list is watched by a logging observer that puts out a message when a user is added.


Listing 4. Observer.php

                
<?php
interface IObserver
{
  function onChanged( $sender, $args );
}
 
interface IObservable
{
  function addObserver( $observer );
}
 
class UserList implements IObservable
{
  private $_observers = array();
 
  public function addCustomer( $name )
  {
    foreach( $this->_observers as $obs )
      $obs->onChanged( $this, $name );
  }
 
  public function addObserver( $observer )
  {
    $this->_observers []= $observer;
  }
}
 
class UserListLogger implements IObserver
{
  public function onChanged( $sender, $args )
  {
    echo( "'$args' added to user list\n" );
  }
}
 
$ul = new UserList();
$ul->addObserver( new UserListLogger() );
$ul->addCustomer( "Jack" );
?>

This code defines four elements: two interfaces and two classes. The IObservable interface defines an object that can be observed, and the UserList implements that interface to register itself as observable. The IObserver list defines what it takes to be an observer, and the UserListLogger implements that IObserver interface. This is shown in the UML in Figure 4.


Figure 4. The observable user list and the user list event logger
The observable user list and the user list event logger

If you run this on the command line, you see this output:

% php observer.php 
'Jack' added to user list
%

The test code creates a UserList and adds the UserListLogger observer to it. Then the code adds a customer, and the UserListLogger is notified of that change.

It’s critical to realize that the UserList doesn’t know what the logger is going to do. There could be one or more listeners that do other things. For example, you may have an observer that sends a message to the new user, welcoming him to the system. The value of this approach is that the UserList is ignorant of all the objects depending on it; it focuses on its job of maintaining the user list and sending out messages when the list changes.

This pattern isn’t limited to objects in memory. It’s the underpinning of the database-driven message queuing systems used in larger applications.

The chain-of-command pattern

Building on the loose-coupling theme, the chain-of-command pattern routes a message, command, request, or whatever you like through a set of handlers. Each handler decides for itself whether it can handle the request. If it can, the request is handled, and the process stops. You can add or remove handlers from the system without influencing other handlers. Listing 5 shows an example of this pattern.


Listing 5. Chain.php

                
<?php
interface ICommand
{
  function onCommand( $name, $args );
}
 
class CommandChain
{
  private $_commands = array();
 
  public function addCommand( $cmd )
  {
    $this->_commands []= $cmd;
  }
 
  public function runCommand( $name, $args )
  {
    foreach( $this->_commands as $cmd )
    {
      if ( $cmd->onCommand( $name, $args ) )
        return;
    }
  }
}
 
class UserCommand implements ICommand
{
  public function onCommand( $name, $args )
  {
    if ( $name != 'addUser' ) return false;
    echo( "UserCommand handling 'addUser'\n" );
    return true;
  }
}
 
class MailCommand implements ICommand
{
  public function onCommand( $name, $args )
  {
    if ( $name != 'mail' ) return false;
    echo( "MailCommand handling 'mail'\n" );
    return true;
  }
}
 
$cc = new CommandChain();
$cc->addCommand( new UserCommand() );
$cc->addCommand( new MailCommand() );
$cc->runCommand( 'addUser', null );
$cc->runCommand( 'mail', null );
?>

This code defines a CommandChain class that maintains a list of ICommand objects. Two classes implement the ICommand interface — one that responds to requests for mail and another that responds to adding users. The UML is shows in Figure 5.


Figure 5. The command chain and its related commands
The command chain and its related commands

If you run the script, which contains some test code, you see the following output:

% php chain.php 
UserCommand handling 'addUser'
MailCommand handling 'mail'
%

The code first creates a CommandChain object and adds instances of the two command objects to it. It then runs two commands to see who responds to those commands. If the name of the command matches either UserCommand or MailCommand, the code falls through and nothing happens.

The chain-of-command pattern can be valuable in creating an extensible architecture for processing requests, which can be applied to many problems.

The strategy pattern

The last design pattern we will cover is the strategy pattern. In this pattern, algorithms are extracted from complex classes so they can be replaced easily. For example, the strategy pattern is an option if you want to change the way pages are ranked in a search engine. Think about a search engine in several parts — one that iterates through the pages, one that ranks each page, and another that orders the results based on the rank. In a complex example, all those parts would be in the same class. Using the strategy pattern, you take the ranking portion and put it into another class so you can change how pages are ranked without interfering with the rest of the search engine code.

As a simpler example, Listing 6 shows a user list class that provides a method for finding a set of users based on a plug-and-play set of strategies.


Listing 6. Strategy.php

                
<?php
interface IStrategy
{
  function filter( $record );
}
 
class FindAfterStrategy implements IStrategy
{
  private $_name;
 
  public function __construct( $name )
  {
    $this->_name = $name;
  }
 
  public function filter( $record )
  {
    return strcmp( $this->_name, $record ) <= 0;
  }
}
 
class RandomStrategy implements IStrategy
{
  public function filter( $record )
  {
    return rand( 0, 1 ) >= 0.5;
  }
}
 
class UserList
{
  private $_list = array();
 
  public function __construct( $names )
  {
    if ( $names != null )
    {
      foreach( $names as $name )
      {
        $this->_list []= $name;
      }
    }
  }
 
  public function add( $name )
  {
    $this->_list []= $name;
  }
 
  public function find( $filter )
  {
    $recs = array();
    foreach( $this->_list as $user )
    {
      if ( $filter->filter( $user ) )
        $recs []= $user;
    }
    return $recs;
  }
}
 
$ul = new UserList( array( "Andy", "Jack", "Lori", "Megan" ) );
$f1 = $ul->find( new FindAfterStrategy( "J" ) );
print_r( $f1 );
 
$f2 = $ul->find( new RandomStrategy() );
print_r( $f2 );
?>

The UML for this code is shown in Figure 6.


Figure 6. The user list and the strategies for selecting users
The user list and the strategies for selecting users

The UserList class is a wrapper around an array of names. It implements a find method that takes one of several strategies for selecting a subset of those names. Those strategies are defined by the IStrategy interface, which has two implementations: One chooses users randomly and the other chooses all the names after a specified name. When you run the test code, you get the following output:

% php strategy.php 
Array
(
    [0] => Jack
    [1] => Lori
    [2] => Megan
)
Array
(
    [0] => Andy
    [1] => Megan
)
%

The test code runs the same user lists against two strategies and shows the results. In the first case, the strategy looks for any name that sorts after J, so you get Jack, Lori, and Megan. The second strategy picks names randomly and yields different results every time. In this case, the results are Andy and Megan.

The strategy pattern is great for complex data-management systems or data-processing systems that need a lot of flexibility in how data is filtered, searched, or processed.

Conclusions

These are just a few of the most common design patterns used in PHP applications. Many more are demonstrated in the Design Patterns book. Don’t be put off by the mystique of architecture. Patterns are great ideas you can use in any programming language and at any skill level.

Design Patterns in PHP – Factory Method and Abstract Factory

(Page 1 of 5 )

Normally, in object oriented programming, object creation is not difficult. But what if your object needs to be created based on different conditions or other matters of context? Then you will spend hours in debugging and updating–unless you know about design patterns. David Fells explains how they work, and uses the creation of a maze to illustrate his points.

Overview

In object oriented programming, object creation – also known as instantiation – is an implied requirement. Objects must at some point be created for use. Obviously, creating objects is not a difficult task and most languages, PHP included, have simple and intuitive syntax for doing so.

When developing larger, more complex systems though, object creation can become difficult. There are situations where different objects may need to be created based on different conditions or based on the context of the object creating it. Creating objects of concrete types explicitly in code can make these situations a nightmare when it comes time to make revisions and additions. When a new class is introduced, you get to follow a trail of code and commence the hours of debugging that will inevitably follow such an endeavor. This is where design patterns come in.

This article will discuss the usage of Factory Method [DP107] and Abstract Factory [DP87] as they pertain to developing applications in PHP using object oriented programming techniques.

Design Patterns in PHP – Factory Method and Abstract Factory – Factory Method

The first pattern used to simplify object instantiation is the Factory Method pattern. The Factory Method pattern defines an interface for object creation but defers the actual instantiation to subclasses. Take, for example, an application that processes Electronic Funds Transfers (ETFs). There are numerous types of ETFs including virtual check, credit card, wire transfer and so on. Using a non-pattern based approach, the application code requesting an ETF object would need to know precisely what subclass of ETF is needed, and it would need to know the context in which that type of ETF is requested. We would end up with code looking something like this:

switch ($etfType) {
case ETF_VIRTUALCHECK :
$etf = new VirtualCheck();
$etf->processCheck();
break;
case ETF_CREDITCARD :
$etf = new CreditCard();
$etf->chargeCard();
break;
case ETF_WIRETRANSFER :
$etf = new WireTransfer();
$etf->chargeCard();
break;
}

Any time we want to add another ETF, we would have to manually update this switch statement anywhere it appeared. We would also have to update any other conditional code that appears. The CreditCard class hinted at above offers the same problem as the ETF itself in that each credit card type (VISA, MasterCard, AMEX) has its own validation scheme and many types have different numerical formats. We would see a similar switch statement to determine what type of credit card we were dealing with either in the CreditCard class constructor or in the switch statement above creates the CreditCard object.

By implementing the Factory Method, we code our application so it only expects a class that conforms to an interface – that is, it has certain methods and properties that can be used to submit an ETF and check whether it failed or succeeded. This promotes loose coupling in the application because you are not binding a concrete subclass to application code. The result is a great increase in flexibility and maintainability. It is easy to add new ETF subclasses and implement them because you are not hard coding the application to expect a specific subclass, just a class with a specific interface. Look at this example.

class ETF {
var $data;
function ETF($data) {
$this->data = $data;
}
function process() {}
function getResult() {}
}

class VirtualCheck extends ETF {}
class WireTransfer extends ETF {}

class ETFFactory {
function createETF($data) {
switch ($data[‘etfType’]) {
case ETF_VIRTUALCHECK :
return new VirtualCheck($data);;
case ETF_WIRETRANSFER :
return new WireTransfer($data);
default :
return new ETF($data);
}
}
}

$data = $_POST;
$etf = ETFFactory::createETF($data);
$etf->process();

This is a crude implementation but the intent should be clear. Assume the contents of $_POST represent everything you need for the type of ETF that is happening, including a ‘etfType’ that says what sort of ETF you are using. This would come from the user making a selection in a form and filling out the correct information. This implementation provides numerous advantages over the first.

1. Data validation can be left entirely to the subclasses and occur without interaction from calling code.

2. Calling code only needs to know of one way to get an ETF object.

3. Creation logic is encapsulated – the ETFFactory decides what concrete class to create based on the contents of $data[‘etfType’]. Calling application code knows nothing of concrete subclasses of ETF.

4. If special measures need to be taken, such as creating a specific type of credit card object, this can take place in one location without the calling application code being involved.

Using this approach consolidates creation logic in a single class – ETFFactory. This eliminates duplication in code when an object is created in multiple locations. With the first method, if a class name is changed or a new ETF class is added, we have to modify the ETF creation code everywhere it appears in our application. With the Factory Method implementation, this is not the case. Our calling application code knows of only ETFFactory and ETF. Subclasses of ETF provide the required specialized behaviors to process themselves in the appropriate way but the calling code needs only to use the process() method.

Design Patterns in PHP – Factory Method and Abstract Factory – Abstract Factory

The Abstract Factory pattern provides an interface for creating families of related or dependent objects without specifying their concrete classes [DP87]. This pattern takes the abstraction displayed in the example above to the next level by providing a common factory interface for a given family of objects. The code that actually uses the factory to create objects only expects an object that conforms to the interface of the abstract factory and does not know any details about concrete factory classes.

Using the example from Design Patterns, consider a game that creates a maze. We have a method that knows what to do to create a maze and it will instantiate all the objects we need to construct the maze – components such as rooms, doors and walls. The example below defines the classes involved – method code is left out deliberately since it is not important to this discussion.

class MapSite {
function enter() {}
}

define(‘North’, 0);
define(‘East’, 1);
define(‘South’, 2);
define(‘West’, 3);

class Room extends MapSite {
var $mapSite = array();
var $roomNumber;

function Room($roomNumber) {}
function getSide($direction) {}
function setSide($direction, $mapSite) {}
}

class Wall extends MapSite {
function Wall() {}
function enter() {}
}

class Door extends MapSite {
var $room1;
var $room2;
var $isOpen;

function Door() {}
function enter() {}
function otherSideFrom($room);
}

class Maze {
function Maze() {}
function addRoom($room) {}
// Etc…
}

class MazeGame {
function createMaze() {
$aMaze = new Maze();
$room1 = new Room(1);
$room2 = new Room(2);
$aDoor = new Door($room1, $room2);

$room1->setSide(North, new Wall());
$room1->setSide(East, $aDoor);
$room1->setSide(South, new Wall());
$room1->setSide(West, new Wall());

$room2->setSide(North, new Wall());
$room2->setSide(East, new Wall());
$room2->setSide(South, new Wall());
$room2->setSide(West, $aDoor);

$aMaze->addRoom($room1);
$aMaze->addRoom($room2);
}
}

In this example, we define a MapSite class that will act as a base class for anything that could apear in a maze, such as a door, a room, or a wall. We then define the constants North, East, South, and West to be used for tracking the sides or orientation of these MapSite objects. Following the constant definitions are the definitions for the Wall, Room and Door classes. These objects should be obvious in intent.

The setSide() method of the Room class expects the direction of the side and the object to be placed there – any object derived of the class MapSite. This would typically be a Wall or a Door, but it could support more objects easily. The constructor of the Door class expects two Room objects – the door must be aware of the rooms it is connecting. Next we define the Maze class, which is used to represent our actual maze object in code. We use the addRoom() method to attach rooms to the maze.

Finally, we look at the MazeGame class and its createMaze() method. The createMaze() method creates a maze object, two rooms and a door, then defines what objects occupy the sides of the two rooms and attaches them to our Maze object. At this point, we have successfully created a Maze and put some rooms into it.

Design Patterns in PHP – Factory Method and Abstract Factory – Drawbacks of the Example

Now that you understand the example case, we need to talk about the drawbacks with the implementation used in this example. The main roadblock with using this implementation is that the MazeGame object is hard coded to create specific classes of objects – that is, it creates Maze, Wall, Door and Room directly without use of any factory methods. We can improve this design by refactoring our createMaze method to use a MazeFactory object for object instantiation. Here is an example.

class MazeFactory {
function MazeFactory() {}
function createMaze() { return new Maze(); }
function createRoom($roomNumber) { return new Room($roomNumber); }
function createDoor($room1, $room2) { return new Door($room1, $room2); }
function createWall() { return new Wall(); }
}

class MazeGame {
function createMaze() {
$factory = new MazeFactory();
$aMaze = $factory->makeMaze();
$room1 = $factory->makeRoom(1);
$room2 = $factory->makeRoom(2);
$aDoor = $factory->makeDoor($room1, $room2);

$room1->setSide(North, $factory->makeWall());
$room1->setSide(East, $aDoor);
$room1->setSide(South, $factory->makeWall());
$room1->setSide(West, $factory->makeWall());

$room2->setSide(North, $factory->makeWall());
$room2->setSide(East, $factory->makeWall());
$room2->setSide(South, $factory->makeWall());
$room2->setSide(West, $aDoor);

$aMaze->addRoom($room1);
$aMaze->addRoom($room2);
}
}

This method is significantly better because it moves creational knowledge out of the createMaze() method and into the MazeFactory class. This will work fine if we only want to use one family of Maze objects, but what if we want to create subclasses of Wall, Door and Room to allow different behaviors? The examples given in Design Patterns use enchanted rooms and rooms with bombs as examples.

An enchanted room could have special behaviors, such as requiring conditions to be met before a door could be opened or closed. A room with a bomb would know what conditions caused a bomb to detonate and would track whether or not the bomb had gone off. If the bomb had gone off, it would keep up with damage to walls from the bomb. If we wanted to use these classes, we would have to parameterize our factory object to check some sort of input condition to know which family of objects to create.

This is where the Abstract Factory pattern comes in. This pattern uses the Factory Method pattern to handle actual object instantiation, but the value of the Abstract Factory pattern comes at a higher level. We code our calling code not only to use factory methods for object creation but to expect a factory object that conforms to a certain interface. This means that we can use different factories – all based on a single abstract factory interface – to create different families of objects. Calling code would only need to expect a class that derives from the original MazeFactory class.

For brevity’s sake we will not type out the code to define the subclasses of Room, Wall, and Door, but we will define the subclasses of the MazeFactory object that are used to create enchanted mazes and mazes with bombs in them.

class EnchantedMazeFactory extends MazeFactory {
function makeRoom($roomNumber) { return new EnchantedRoom($roomNumber); }
function makeDoor($room1, $room2) { return new EnchantedDoor($room1, $room2); }
}

class BombedMazeFactory extends MazeFactory {
function makeRoom($roomNumber) { return new RoomWithABomb($roomNumber); }
function makeWall() { return new BombedWall(); }
}

We can now use different concrete factory classes to create different families of products – in this case, different types of Doors, Walls, and Rooms. We are now left with one last problem – createMaze(), at last glance, is hard coded to create a MazeFactory object. Since createMaze() only needs to create the objects themselves through a standard factory interface, there is no need for the method to ever actually create the factory. We should pass the factory in as an argument to createMaze() and then let the method do its work.

class MazeGame {
function createMaze($factory) {
$aMaze = $factory->makeMaze();
$room1 = $factory->makeRoom(1);
$room2 = $factory->makeRoom(2);
$aDoor = $factory->makeDoor($room1, $room2);

$room1->setSide(North, $factory->makeWall());
$room1->setSide(East, $aDoor);
$room1->setSide(South, $factory->makeWall());
$room1->setSide(West, $factory->makeWall());

$room2->setSide(North, $factory->makeWall());
$room2->setSide(East, $factory->makeWall());
$room2->setSide(South, $factory->makeWall());
$room2->setSide(West, $aDoor);

$aMaze->addRoom($room1);
$aMaze->addRoom($room2);
}
}

Now in our createMaze() method, no assumptions are made about the type of factory we need. Some other code that is responsible for figuring out what type of factory to create would actually instantiate the MazeFactory and pass it to createMaze(), as in the following example.

$game = new MazeGame();
$game->createMaze(new EnchantedMazeFactory());

After all is said and done, we have created (with a little help from Design Patterns) a very flexible set of classes for producing mazes. It should be noted that in an actual implementation, createMaze() would be using data of some kind to determine what components are required in the maze and the method calls on the various MapSite objects would not be hard coded as they are in the example.

Design Patterns in PHP – Factory Method and Abstract Factory – Conclusion

The Factory Method and Abstract Factory patterns allow us to build a great deal of flexibility into our applications by abstracting the process of object instantiation and by helping consolidate creational knowledge in the appropriate classes. The Factory Method pattern teaches us how to use methods for object creation rather than directly instantiating objects through client code. This lets the factory method itself do any work it needs to do in creating the object – work that could involve contextual considerations or initializing certain resources in the object. The Abstract Factory class teaches us how to create groups of related objects with a common interface, creating client code that expects neither a specific type of object nor a specific type of factory.

One of the most important concepts in good object oriented design is “design to an interface, not an implementation.” What this means is that you should code your application to expect standard sets of object behaviors but not to expect specific object types. This results in a system of objects that know as little as possible about one another and, so long as the interfaces to these classes do not change, the internals of the classes can vary without adversely affecting other classes in the system.

In the final createMaze() example above, we see this in action on two levels. First, we pass any MazeFactory type object to the method, which is used to instantiate various MapSite objects and load them into a Maze. Second we are working with the Maze and MapSite objects without worrying about their specific class, just their interface – we know a Room needs a room number when we create it and we know we can enter a room. It does not matter to the client code that the room may be an EnchantedRoom or a RoomWithABomb – all it needs to know is how to create it and how to use it. This is the very definition of programming to an interface. The opposite case is true with the first maze example where createMaze() directly creates specific Room, Door, and Wall objects.

The use of these two patterns is a good starting point for programmers just beginning to learn about patterns and good object oriented design. This is the first in what will be a series of articles on design patterns with PHP examples and is intended for developers who are somewhat new to design patterns. Thanks for reading and please don’t forget to leave some feedback in the comments section!