Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Object Aggregation/Composition Functions

Object Aggregation/Composition Functions

Warning:

This extension is EXPERIMENTAL. The behaviour of this extension -- including the names of its functions and anything else documented about this extension -- may change without notice in a future release of PHP. Use this extension at your own risk.

Introduction

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 1622. 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 1623. 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.

Examples

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

Example 1624. 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()
   {
       
$dbh = mysql_connect();
       
mysql_select_db("storage", $dbh);
       
$serdata = serialize($this->data);
       
mysql_query("insert into vars ('$serdata',now())", $dbh);
       
mysql_close($dbh);
   }
}

?>


We then instantiate a couple of objects from the defined classes, and perform some aggregations and deaggregations, printing some object information along the way:

Example 1625. test_aggregation.php

<?php
include "storageclasses.inc";

// some utilty functions

function p_arr($arr)
{
   foreach (
$arr as $k => $v)
       
$out[] = "\t$k => $v";
   return
implode("\n", $out);
}

function
object_info($obj)
{
   
$out[] = "Class: " . get_class($obj);
   foreach (
get_object_vars($obj) as $var=>$val) {
       if (
is_array($val)) {
           
$out[] = "property: $var (array)\n" . p_arr($val);
       } else {
           
$out[] = "property: $var = $val";
       }
   }
   foreach (
get_class_methods($obj) as $method) {
       
$out[] = "method: $method";
   }
   return
implode("\n", $out);
}


$data = array(M_PI, "kludge != cruft");

// we create some basic objects
$fs = new FileStorage($data);
$ws = new WDDXStorage($data);

// print information on the objects
echo "\$fs object\n";
echo
object_info($fs) . "\n";
echo
"\n\$ws object\n";
echo
object_info($ws) . "\n";

// do some aggregation

echo "\nLet's aggregate \$fs to the WDDXStorage class\n";
aggregate($fs, "WDDXStorage");
echo
"\$fs object\n";
echo
object_info($fs) . "\n";

echo
"\nNow let us aggregate it to the DBStorage class\n";
aggregate($fs, "DBStorage");
echo
"\$fs object\n";
echo
object_info($fs) . "\n";

echo
"\nAnd finally deaggregate WDDXStorage\n";
deaggregate($fs, "WDDXStorage");
echo
"\$fs object\n";
echo
object_info($fs) . "\n";

?>


We will now consider the output to understand some of the side-effects and limitation of object aggregation in PHP. First, the newly created $fs and $ws objects give the expected output (according to their respective class declaration). Note that for the purposes of object aggregation, private elements of a class/object begin with an underscore character ("_"), even though there is not real distinction between public and private class/object elements in PHP.

$fs object
Class: filestorage
property: data (array)
   0 => 3.1415926535898
   1 => kludge != cruft
method: filestorage
method: write

$ws object
Class: wddxstorage
property: data (array)
   0 => 3.1415926535898
   1 => kludge != cruft
property: version = 1.0
property: _id = ID::9bb2b640764d4370eb04808af8b076a5
method: wddxstorage
method: store
method: _genid

We then aggregate $fs with the WDDXStorage class, and print out the object information. We can see now that even though nominally the $fs object is still of FileStorage, it now has the property $version, and the method store(), both defined in WDDXStorage. One important thing to note is that it has not aggregated the private elements defined in the class, which are present in the $ws object. Also absent is the constructor from WDDXStorage, which will not be logical to aggegate.

Let's aggregate $fs to the WDDXStorage class
$fs object
Class: filestorage
property: data (array)
   0 => 3.1415926535898
   1 => kludge != cruft
property: version = 1.0
method: filestorage
method: write
method: store

The process of aggregation is cumulative, so when we aggregate $fs with the class DBStorage, generating an object that can use the storage methods of all the defined classes.

Now let us aggregate it to the DBStorage class
$fs object
Class: filestorage
property: data (array)
   0 => 3.1415926535898
   1 => kludge != cruft
property: version = 1.0
property: dbtype = mysql
method: filestorage
method: write
method: store
method: save

Finally, the same way we aggregated properties and methods dynamically, we can also deaggregate them from the object. So, if we deaggregate the class WDDXStorage from $fs, we will obtain:

And deaggregate the WDDXStorage methods and properties
$fs object
Class: filestorage
property: data (array)
   0 => 3.1415926535898
   1 => kludge != cruft
property: dbtype = mysql
method: filestorage
method: write
method: save

One point that we have not mentioned above, is that the process of aggregation will not override existing properties or methods in the objects. For example, the class FileStorage defines a $data property, and the class WDDXStorage also defines a similar property which will not override the one in the object acquired during instantiation from the class FileStorage.

Table of Contents

aggregate_info — Gets aggregation information for a given object
aggregate_methods_by_list — Selective dynamic class methods aggregation to an object
aggregate_methods_by_regexp — Selective class methods aggregation to an object using a regular expression
aggregate_methods — Dynamic class and object aggregation of methods
aggregate_properties_by_list — Selective dynamic class properties aggregation to an object
aggregate_properties_by_regexp — Selective class properties aggregation to an object using a regular expression
aggregate_properties — Dynamic aggregation of class properties to an object
aggregate — Dynamic class and object aggregation of methods and properties
aggregation_info — Alias of aggregate_info()
deaggregate — Removes the aggregated methods and properties from an object

Code Examples / Notes » ref.objaggregation

jeb.

It is worth noting that class association does not work, even in PHP 4.3.0 - this ability is experimental. I'm assuming it was added in for the sake of forwards-compatibilty. Use object association instead for now.
Until it is implemented, you will receieve a parse error when attempting to use it.
Related bug report: http://bugs.php.net/bug.php?id=20531
Just to prevent people posting about "why it doesn't work??", etc etc etc.


greg beaver firstname

If you need to serialize an object for sessions or other purposes, and want to save aggregation state, extend it from a base class such as this one, and use $this->agg/$this->unagg instead of aggregate/deaggregate
<?php
class base
{
   var $_aggregates = array();
   
   function agg($agg)
   {
       aggregate($this,$agg);
       $this->_aggregates[$agg] = 1;
   }
   
   function unagg($agg = false)
   {
       if ($agg)
       {
            deaggregate($this,$agg);
            unset($this->_aggregates[$agg]);
       } else
       {
            deaggregate($this);
           $this->_aggregates = array();
       }
   }
}
?>


kencomer

For PHP5 applications, the all of the "aggregate" function family is now in runkit.
 http://php.net/manual/en/ref.runkit.php


Change Language


Follow Navioo On Twitter
.NET Functions
Apache-specific Functions
Alternative PHP Cache
Advanced PHP debugger
Array Functions
Aspell functions [deprecated]
BBCode Functions
BCMath Arbitrary Precision Mathematics Functions
PHP bytecode Compiler
Bzip2 Compression Functions
Calendar Functions
CCVS API Functions [deprecated]
Class/Object Functions
Classkit Functions
ClibPDF Functions [deprecated]
COM and .Net (Windows)
Crack Functions
Character Type Functions
CURL
Cybercash Payment Functions
Credit Mutuel CyberMUT functions
Cyrus IMAP administration Functions
Date and Time Functions
DB++ Functions
Database (dbm-style) Abstraction Layer Functions
dBase Functions
DBM Functions [deprecated]
dbx Functions
Direct IO Functions
Directory Functions
DOM Functions
DOM XML Functions
enchant Functions
Error Handling and Logging Functions
Exif Functions
Expect Functions
File Alteration Monitor Functions
Forms Data Format Functions
Fileinfo Functions
filePro Functions
Filesystem Functions
Filter Functions
Firebird/InterBase Functions
Firebird/Interbase Functions (PDO_FIREBIRD)
FriBiDi Functions
FrontBase Functions
FTP Functions
Function Handling Functions
GeoIP Functions
Gettext Functions
GMP Functions
gnupg Functions
Net_Gopher
Haru PDF Functions
hash Functions
HTTP
Hyperwave Functions
Hyperwave API Functions
i18n Functions
IBM Functions (PDO_IBM)
IBM DB2
iconv Functions
ID3 Functions
IIS Administration Functions
Image Functions
Imagick Image Library
IMAP
Informix Functions
Informix Functions (PDO_INFORMIX)
Ingres II Functions
IRC Gateway Functions
PHP / Java Integration
JSON Functions
KADM5
LDAP Functions
libxml Functions
Lotus Notes Functions
LZF Functions
Mail Functions
Mailparse Functions
Mathematical Functions
MaxDB PHP Extension
MCAL Functions
Mcrypt Encryption Functions
MCVE (Monetra) Payment Functions
Memcache Functions
Mhash Functions
Mimetype Functions
Ming functions for Flash
Miscellaneous Functions
mnoGoSearch Functions
Microsoft SQL Server Functions
Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
Mohawk Software Session Handler Functions
mSQL Functions
Multibyte String Functions
muscat Functions
MySQL Functions
MySQL Functions (PDO_MYSQL)
MySQL Improved Extension
Ncurses Terminal Screen Control Functions
Network Functions
Newt Functions
NSAPI-specific Functions
Object Aggregation/Composition Functions
Object property and method call overloading
Oracle Functions
ODBC Functions (Unified)
ODBC and DB2 Functions (PDO_ODBC)
oggvorbis
OpenAL Audio Bindings
OpenSSL Functions
Oracle Functions [deprecated]
Oracle Functions (PDO_OCI)
Output Control Functions
Ovrimos SQL Functions
Paradox File Access
Parsekit Functions
Process Control Functions
Regular Expression Functions (Perl-Compatible)
PDF Functions
PDO Functions
Phar archive stream and classes
PHP Options&Information
POSIX Functions
Regular Expression Functions (POSIX Extended)
PostgreSQL Functions
PostgreSQL Functions (PDO_PGSQL)
Printer Functions
Program Execution Functions
PostScript document creation
Pspell Functions
qtdom Functions
Radius
Rar Functions
GNU Readline
GNU Recode Functions
RPM Header Reading Functions
runkit Functions
SAM - Simple Asynchronous Messaging
Satellite CORBA client extension [deprecated]
SCA Functions
SDO Functions
SDO XML Data Access Service Functions
SDO Relational Data Access Service Functions
Semaphore
SESAM Database Functions
PostgreSQL Session Save Handler
Session Handling Functions
Shared Memory Functions
SimpleXML functions
SNMP Functions
SOAP Functions
Socket Functions
Standard PHP Library (SPL) Functions
SQLite Functions
SQLite Functions (PDO_SQLITE)
Secure Shell2 Functions
Statistics Functions
Stream Functions
String Functions
Subversion Functions
Shockwave Flash Functions
Swish Functions
Sybase Functions
TCP Wrappers Functions
Tidy Functions
Tokenizer Functions
Unicode Functions
URL Functions
Variable Handling Functions
Verisign Payflow Pro Functions
vpopmail Functions
W32api Functions
WDDX Functions
win32ps Functions
win32service Functions
xattr Functions
xdiff Functions
XML Parser Functions
XML-RPC Functions
XMLReader functions
XMLWriter Functions
XSL functions
XSLT Functions
YAZ Functions
YP/NIS Functions
Zip File Functions
Zlib Compression Functions
eXTReMe Tracker