The Abstract Collection
I discovered something cool the other day while playing around with a PHP class that was designed to hold a bunch of items of a certain type. Essentially it is a way to get around PHP’s lack of strict type enforcement of class members. The class itself was abstract so the implementation would most likely do the dirty work of controlling what goes in and what goes out.
It looked a little like this:
<?php abstract class Collection { protected $collectionItems = array(); public function __set($name, $value) { $this->collectionItems[$name] = $value; } public function __get($name) { if (array_key_exists($name, $this->collectionItems)) { return $this->collectionItems[$name]; } else { return null; } } } ?>
The Collection class uses the magic __get and __set interceptor methods to capture any alien data going in and coming out of any class that inherits from it. By its nature (and hopefully as it’s name would suggest) this class is useful when storing a bunch of similar items in one area.
<?php class Configuration extends Collection { public function __set($name, ConfigurationItem $value) { parent::set($name, $value); } } ?>
The Configuration class extends Collection and therefore inherits all of it’s functionality. The __set method is overridden to provide functionality specific to this implementation. In this case, typehinting is used in order to insure that only items of the type ConfigurationItem are set inside.
It certainly is an interesting pattern. I can’t say that it’s particularly useful to me at the moment, but it’s definitely something that comes in very handy with a few edge cases. Sure, it doesn’t really hack around strict type enforcement. An obvious limitation is that only one type of data fits into a class. Still I’m sure it can be useful at times.