Forum und email

Object Aggregation/Composition Functions

Warning

Это расширение является ЭКСПЕРИМЕНТАЛЬНЫМ. Поведение этого расширения, включая имена его функций и относящуюся к нему документацию, может измениться в последующих версиях PHP без уведомления. Используйте это расширение на свой страх и риск.

Введение

In Object Oriented Programming, it is common to see the composition of simple classes (and/or instances) into a more complex one. This is a flexible strategy for building complicated objects and object hierarchies and can function as a dynamic alternative to multiple inheritance. There are two ways to perform class (and/or object) composition depending on the relationship between the composed elements: Association and Aggregation.

An Association is a composition of independently constructed and externally visible parts. When we associate classes or objects, each one keeps a reference to the ones it is associated with. When we associate classes statically, one class will contain a reference to an instance of the other class. For example:

Example#1 Class association

<?php
class DateTime {
   
   function 
DateTime() 
   {
       
// empty constructor
   
}

   function 
now() 
   {
       return 
date("Y-m-d H:i:s");
   }
}

class 
Report {
   var 
$_dt;
   
// more properties ...

   
function Report() 
   {
       
$this->_dt = new DateTime();
       
// initialization code ...
   
}

   function 
generateReport() 
   {
       
$dateTime $this->_dt->now();
       
// more code ...
   
}

   
// more methods ...
}

$rep = new Report();
?>
We can also associate instances at runtime by passing a reference in a constructor (or any other method), which allow us to dynamically change the association relationship between objects. We will modify the example above to illustrate this point:

Example#2 Object association

<?php
class DateTime {
   
// same as previous example
}

class 
DateTimePlus {
   var 
$_format;
   
   function 
DateTimePlus($format="Y-m-d H:i:s"
   {
       
$this->_format $format;
   }

   function 
now() 
   {
       return 
date($this->_format);
   }
}

class 
Report {
   var 
$_dt;    // we'll keep the reference to DateTime here
   // more properties ...

   
function Report() 
   {
       
// do some initialization
   
}

   function 
setDateTime(&$dt
   {
       
$this->_dt =& $dt;
   }

   function 
generateReport() 
   {
       
$dateTime $this->_dt->now();
       
// more code ...
   
}

   
// more methods ...
}

$rep = new Report();
$dt = new DateTime();
$dtp = new DateTimePlus("l, F j, Y (h:i:s a, T)");

// generate report with simple date for web display
$rep->setDateTime(&$dt);
echo 
$rep->generateReport();

// later on in the code ...

// generate report with fancy date
$rep->setDateTime(&$dtp);
$output $rep->generateReport();
// save $output in database
// ... etc ... 
?>

Aggregation, on the other hand, implies encapsulation (hidding) of the parts of the composition. We can aggregate classes by using a (static) inner class (PHP does not yet support inner classes), in this case the aggregated class definition is not accessible, except through the class that contains it. The aggregation of instances (object aggregation) involves the dynamic creation of subobjects inside an object, in the process, expanding the properties and methods of that object.

Object aggregation is a natural way of representing a whole-part relationship, (for example, molecules are aggregates of atoms), or can be used to obtain an effect equivalent to multiple inheritance, without having to permanently bind a subclass to two or more parent classes and their interfaces. In fact object aggregation can be more flexible, in which we can select what methods or properties to "inherit" in the aggregated object.

Примеры

We define 3 classes, each implementing a different storage method:

Example#3 storage_classes.inc

<?php
class FileStorage {
    var 
$data;

    function 
FileStorage($data
    {
        
$this->data $data;
    }
    
    function 
write($name
    {
        
$fp fopen(name"w");
        
fwrite($fp$this->data);
        
fclose($data);
    }
}

class 
WDDXStorage {
    var 
$data;
    var 
$version "1.0";
    var 
$_id// "private" variable

    
function WDDXStorage($data
    {
        
$this->data $data;
        
$this->_id $this->_genID();
    }

    function 
store() 
    {
        if (
$this->_id) {
            
$pid wddx_packet_start($this->_id);
            
wddx_add_vars($pid"this->data");
            
$packet wddx_packet_end($pid);
        } else {
            
$packet wddx_serialize_value($this->data);
        }
        
$dbh dba_open("varstore""w""gdbm");
        
dba_insert(md5(uniqid(""true)), $packet$dbh);
        
dba_close($dbh);
    }

    
// a private method
    
function _genID() 
    {
        return 
md5(uniqid(rand(), true));
    }
}

class 
DBStorage {
    var 
$data;
    var 
$dbtype "mysql";

    function 
DBStorage($data
    {
        
$this->data $data;
    }

    function 
save() 
    {