The Collection class is a very useful object-oriented alternative to the traditional array and one that you could usefully employ in virtually any application you might build. It provides careful management of its members and a consistent API that makes writing code that uses the class easy.

Subclassing Collection and overriding the addItem() method to include a type hint on the first parameter allows you to control the type of objects that are added to the collection. Although not strictly necessary, this approach provides an extra level of error checking.

By wrapping all calls to addItem(), getItem(), and removeItem() in try...catch blocks, you have complete control over any errors that may occur in those methods. Be sure to handle these errors with something a bit more graceful than the call to die() shown in the examples.

Callbacks are an incredibly powerful technique that you can use to implement lazy instantiation, which conserves system resources and ensures that you're manipulating only the data that it is absolutely necessary to manipulate. When you have a complex hierarchy of objects, you can use callbacks to automatically handle the instantiation of child objects and defer the creation of those not absolutely necessary for the current application activity. Make sure that you understand how this works and see whether you can find other uses for this technique.

Professional PHP5 (Programmer to Programmer Series)
Professional PHP5 (Programmer to Programmer Series)
Year: 2003
Pages: 182 © 2008-2017.
If you may any questions please contact us: