[ Team LiB ] Previous Section Next Section

Cleaning Up Using Destructors

In Hour 9, we saw that PHP 5 provides the __construct() method to help us set up an object upon instantiation. Objects have their allotted span, and PHP 5 provides us with a means of easing their passing as well as welcoming their arrival. The __destruct() method is automatically called when an object is about to be expunged from memory. This generally happens when no part of your script process holds a reference to the object any longer. The process enables you to handle any last-minute clean-up that your object might need to take care of, such as closing database handles.

In Listing 17.5, we set up another Item scenario. We invent an ItemUpdater class. In theory, this class generates objects responsible for saving Item objects. An Item object will hold a reference to its own updater. Such structures are useful ways of ensuring that objects focus on their core responsibilities. Item objects are responsible for managing information concerning shop items. ItemUpdater objects are responsible for saving Item objects. All that an Item object knows about an ItemUpdater is that it has an update() method. It does not know whether it is going to be saved to an XML file by XmlItemUpdater or to a database by MysqlItemUpdater.

Listing 17.5 Cleaning Up with the __destruct Method (PHP 5 Only)
 1: <?php
 2:
 3: class ItemUpdater {
 4:   public function update( Item $item ) {
 5:     print "updating.. ";
 6:     print $item->name;
 7:   }
 8: }
 9:
10: class Item {
11:   public $name = "item";
12:   private $updater;
13:
14:   public function setUpdater( ItemUpdater $update ) {
15:     $this->updater=$update;
16:   }
17:   function __destruct() {
18:     if ( ! empty( $this->updater )) {
19:       $this->updater->update( $this );
20:     }
21:   }
22: }
23:
24: $item = new Item();
25: $item->setUpdater( new ItemUpdater() ) ;
26: unset( $item );
27: ?>

We create an ItemUpdater class on line 3. It has a single method, update() which demands an Item object. In our example, it merely writes a message to the browser announcing its intention of saving the Item it has been passed. We create an Item class on line 10 containing a setUpdater() method on line 14.

setUpdater() simply caches an ItemUpdater object for later use. On line 17, we define our __destruct() method. It tests whether an ItemUpdater object has been cached in the $updater property. If an ItemUpdater object is available, we call its update() method.

We test our classes on line 24 by creating a new Item object, setting an ItemUpdater object. We then cruelly unset the Item object, effectively destroying it. When this code is run, the __destruct() method is called, invoking the ItemUpdater object's update method. The following is written to the browser:


updating.. item


    [ Team LiB ] Previous Section Next Section