Tag Archive for 'PHP prototype design pattern'

PHP Prototype Design Pattern Part I: How to Clone

cloneClone My Instance

The Prototype Design Pattern is a creational one that I’ve been warming up to lately. Basically, the purpose of the Prototype pattern is to reduce the cost of instantiating objects through the use of cloning. So, the first thing we need to do is to understand how to use cloning in PHP and what it does.

Fortunately, PHP has a __clone() function built right into it, and it makes creating a Prototype design pattern a lot easier than languages where you have to write your own clone function. So, this post will just look at how the __clone() function works and how it saves resources in programming.

Before we get going, go ahead and play the example (and meet the lovely Ada Lovelace) and download the source code:
Take a look at the listings, and you’ll see where the __clone() function is located. Also, see how it is used to create a cloned instance.

A Class with a Clone Within

To clone an object in PHP, you need to create the Class you plan to clone with the __clone() function inside. So for ClassA to be cloned by $objectB, I need to include the __clone function inside ClassA. The instantiation process would look like the following:

$objectA = new ClassA();
$objectB = clone $objectA;

To get started, then, we’ll need to create a class that contains a __clone() function. This will be an abstract class, and the __clone() function will be abstract as well.

< ?php
abstract class CloneMachine
	protected $designation;
	public function showHelp($designate)
		echo "<img src='ada.png'/>";
		echo "<br />$this->designation <p></p>";
	abstract function __clone();

Continue reading ‘PHP Prototype Design Pattern Part I: How to Clone’