Home arrow PHP arrow Page 2 - Implementing Factory Methods in PHP 5

The simplest object constructor - PHP

If you’ve ever developed desktop applications using mature object-oriented languages like C++ and Java, then it’s possible that you’ve found yourself saying a few funny phrases such as “I need to implement a factory method within this class,” or in the worst case: “this class needs to implement a factory method, but I don’t have a single clue about how to do that.” Surprisingly, you can implement these factory methods pretty quickly and easily in PHP 5, as this six-part series will show you.

TABLE OF CONTENTS:
  1. Implementing Factory Methods in PHP 5
  2. The simplest object constructor
  3. Defining factory methods
  4. Factoring web form element objects
By: Alejandro Gervasio
Rating: starstarstarstarstar / 3
November 24, 2009

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

In the introduction, I explained that a factory method is in most cases responsible for creating objects that are returned to client code. Of course, this concept is true, but it doesn’t reflect the full reality of the factoring process. The most basic way to spawn objects in PHP 5 is by means of the “new” keyword.

Actually, “new” is a language construct and not a method, but since it’s mandatory to use it for creating instances of classes, it’s worth spending a few moments looking at it. But, wait a minute! What about constructors? Well, because of their suggestive name, you might think that these are the ones that really take care of creating objects, which is a wrong, misleading concept.

When implemented, constructors are only methods called after object creation that quite often perform some useful initialization tasks. They don't create any objects automatically, however, unless they contain the logic required to do that. Without diving into the depths of the C language, which as you know is the driving force behind PHP, it is necessary to understand that the “new” construct is used to create class instances, and then, if a constructor method has been defined in the originating class, the program flow will be delegated to this particular method. It’s that simple, really.

However, to clarify the difference between the “new” construct and a constructor method, below I defined a simple class that reads from and writes data to a target file, which looks like this:

class FileProcessor

{

private $fileName = 'dafault.txt';

private $data = 'Sample data';

 

// implemented constructor

public function __construct($data = '', $fileName = '')

{

if ($data != '')

{

$this->data = $data;

}

if ($fileName != '')

{

$this->fileName = $fileName;

}

}

 

// read data from target file

public function read()

{

return file_get_contents($this->fileName);

}

 

// write data to target file

public function write()

{

file_put_contents($this->fileName, $this->data);

}

}

As seen above, understanding how this example class works isn’t brain surgery. It defines two main methods, called “read()” and “write()” respectively, where the first obviously fetches data from a specified text file, and the second one puts this data into that targeted file.

The most important detail to notice here, though, is that the class implements its constructor, which simply assigns new values to the $data and $fileName properties. So far, there’s nothing special about this method, except that it demonstrates the actual role it plays when an instance of the “FileProcessor” class is created. Consider the following script:

$fileProc = new FileProcessor('This string will be saved to the target file');

// write data to target file

$fileProc->write();

// read and display data from target file

echo $fileProc->read();

In this example, after a new file processor object has been created via the “new” keyword, the constructor is called with an incoming argument. However, as I said before, this method doesn’t build any objects; it only performs the assignment process shown before.

Taking the example a bit further, it would be perfectly possible to create a file processor object using the default values assigned to its properties, even if the originating class were defined as follows:

class FileProcessor

{

private $fileName = 'dafault.txt';

private $data = 'Sample data';

 

// read data from target file

public function read()

{

return file_get_contents($this->fileName);

}

 

// write data to target file

public function write()

{

file_put_contents($this->fileName, $this->data);

}

}

 

// create new file processor object

$fileProc = new FileProcessor();

// write data to target file

$fileProc->write();

// read and display data from target file

echo $fileProc->read();

There you have it. The above code sample demonstrates in a nutshell that the $fileProc object always gets created, even when no constructor method exists. While this example may look rather primitive at first sight, it shows the differences between using the “new” construct and implementing class constructors.

So far, so good. At this point, I took a quick look at the simplest way to create factory objects in PHP, via the corresponding “new” keyword, a process that  you’ve surely grasped in a snap. Therefore, it’s time to start explaining how to build real factory methods within classes.

However, this topic will be covered in the section to come. So, click on the link below and read the next few lines.



 
 
>>> More PHP Articles          >>> More By Alejandro Gervasio
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PHP ARTICLES

- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: