note 86206 added to class.arrayobject
| From: | tony at tonyandcarol dot com | Date: | Wed, 08 Oct 2008 02:49:22 +0000 |
| Subject: | note 86206 added to class.arrayobject | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-145150@lists.php.net to get a copy of this message | ||
My need was to create a java-like collection where I could store objects by their DB primary keys
while having the standard stack capabilities of adding, retrieving, and removing objects from
collection. ArrayObject didn't quite do what I need it to do so I extended it a little.
class GenericCollection extends ArrayObject{
private $data;
function __construct(){
$this->data = new ArrayObject();
}
function addObject($_id, $_object){
$_thisItem = new CollectionObject($_id, $_object);
$this->data->offSetSet($_id, $_thisItem);
}
function deleteObject($_id){
$this->data->offsetUnset($_id);
}
function getObject($_id){
$_thisObject = $this->data->offSetGet($_id);
return $_thisObject->getObject();
}
function printCollection() {
print_r($this->data);
}
}
class CollectionObject {
private $id;
private $object;
function __construct($_id, $_object){
$this->id = $_id;
$this->object = $_object;
}
function getObject(){
return $this->object;
}
function printObject() {
print_r($this);
}
}
Call it like so:
$u1 = new User/Data/Object (); //whatever, just an object.
$myCollection = new GenericCollection();
$myCollection->addObject(1, $u1);
print_r($myCollection->getObject(1));
Now you have a simple and functional collection framework. Add methods in for specific types of
sorting, we just didn't need anything other than primary key access. And you can add
introspection into the collection object if you need to track what kind of an object it is.
tony@tonyandcarol.com
----
Server IP: 64.71.164.2
Probable Submitter: 71.125.62.17
----
Manual Page -- http://www.php.net/manual/en/class.arrayobject.php
Edit -- https://master.php.net/note/edit/86206
Del: integrated -- https://master.php.net/note/delete/86206/integrated
Del: useless -- https://master.php.net/note/delete/86206/useless
Del: bad code -- https://master.php.net/note/delete/86206/bad+code
Del: spam -- https://master.php.net/note/delete/86206/spam
Del: non-english -- https://master.php.net/note/delete/86206/non-english
Del: in docs -- https://master.php.net/note/delete/86206/in+docs
Del: other reasons-- https://master.php.net/note/delete/86206
Reject -- https://master.php.net/note/reject/86206
Search -- https://master.php.net/manage/user-notes.php