The design of PHP collection

Source: Internet
Author: User
Design of PHP Collection class

Use. NET development has been for many years, recently contacted PHP, found that PHP is not fun. However, it is found that there are no collection classes, only arrays, and arrays are strong. Here I use an array to wrap the collection into a collection, with the following code:

Class Collection{private $_members=array ();p ublic  function AddItem ($obj, $key =null) {if ($key) {if (Isset ($this- >_members[$key]) {Throw  New Exception ("key \" $key \ "already in use!");} else{$this->_members[$key]= $obj;} else{$this->_members[]= $obj;}} Public Function RemoveItem ($key) {if (Isset ($this->_members[$key])) {unset ($this->_members[$key]);} Else{throw New Exception ("Invalid Key \" $key \ "!");}} Public Function GetItem ($key) {if (Isset ($this->_members[$key]) {return $this->_members[$key];} Else{throw New  exception ("Invalid Key \" $key \ "!");}} Public Function Keys () {return Array_keys ($this->_members);} Public Function Legth () {return sizeof ($this->_members);} Public function exists ($key) {return (Isset ($this->_members[$key]);}}
Now let's test whether this collection works.

We first set up a collection element class course:

Class  course{private $_id;private $_coursecode;private $_name;  Public function __construct ($id, $courseCode, $name) {$this->_id= $id; $this->_coursecode= $courseCode; $this- >_name= $name;} Public Function GetName () {return $this->_name;} Public Function GetID () {return $this->_id;} Public Function Getcoursecode () {return $this->_coursecode;} Public Function __tostring () {return $this->_name;}}
The test code is as follows:

$courses =new Collection (), $courses->additem (New Course (1, "001", "Language"), 1), $courses->additem (New Course (2, "002 "," mathematics "), 2); $obj = $courses->getitem (1);p rint $obj;
I think this collection class should be able to meet the needs of our daily development.
But we are. NET has an object deferred loading, for example, if there is student this object, it should have a lot of course, but we want to access course before the course will not load. That is, when instantiating student, the number of course is 0, and when we need to course, it actually reads the corresponding data from the database. Is that we need to make collection an inert instantiation.

The modified collection code is as follows:

Class Collection {Private $_members = array ();               Collection members private $_onload;     Holder for callback function Private $_isloaded = false; Flag This indicates whether the callback//has been invoked public function AddItem ($o      BJ, $key = null) {$this->_checkcallback (); _checkcallback is defined a little later if ($key) {if (Isset ($this->_members[$key])) {Throw n EW keyinuseexception ("Key \" $key \ "already in use!");}      else {$this->_members[$key] = $obj;    }} else {$this->_members[] = $obj;        }} Public Function RemoveItem ($key) {$this->_checkcallback ();    if (Isset ($this->_members[$key])) {unset ($this->_members[$key]);    } else {throw new keyinvalidexception ("Invalid key \" $key \ "!");}}        Public Function GetItem ($key) {$this->_checkcallback (); if (Isset ($this->_members[$key]) {return $this->_members[$key];  } else {throw new keyinvalidexception ("Invalid key \" $key \ "!");}}    Public Function keys () {$this->_checkcallback ();  Return Array_keys ($this->_members);    } public Function Length () {$this->_checkcallback ();  return sizeof ($this->_members);    Public function exists ($key) {$this->_checkcallback ();  Return (Isset ($this->_members[$key]));     }/** * Use this method to define a function to being * invoked prior to accessing the collection.   * The function should take a collection as a * its sole parameter. */Public Function Setloadcallback ($functionName, $objOrClass = null) {if ($objOrClass) {$callback = Array ($objO    Rclass, $functionName);    } else {$callback = $functionName; }//make sure the Function/method is valid if (!is_callable ($callback, False, $callableName)) {throw new Ex                           Ception ("$callableName is not callable". "As a parameter to onload");    return false;  } $this->_onload = $callback;  }/** * Check to see if a callback have been defined and if so, * whether or not it has already been called.   If not, * invoke the callback function. */Private Function _checkcallback () {if (Isset ($this->_onload) &&! $this->_isloaded) {$this->_      IsLoaded = true;    Call_user_func ($this->_onload, $this); }  }}
The required student are as follows:

Class Coursecollection extends Collection {public Function AddItem (Course $obj, $key =null) {Parent::additem ($obj, $key);}} Class Student{private $_id;private $_name;public $course;p ublicfunction __construct ($id, $name) {$this->_id= $id; $ This->_name= $name; $this->course=new coursecollection (); $this->course->setloadcallback (' loadCourses ' , $this);} Public Function GetName () {return $this->_name;} Public Function GetID () {return $this->_id;} Public Function __tostring () {return $this->_name;} Public Function loadcourses (Collection $col) {$col->additem (new Course (1, "001", "Language"), 1); $col->additem (new Course (2, "002", "math"), 2);}}
The calling code is as follows:

$student =new Student (1, "Majiang");
Print $student->getname ();
Print $student->course->getitem (1);


  • Related Article

    Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.