"Virtual properties"
Jeff Moore posted an article on procata.com about getters, setters and real properties. I fully agree with him. Especially the usage of interceptors (__get()/__set()/__isset()/__call()) makes your API a lot more readable and comfortable, while maintaining the purpose behind getters and setters: Checking the correctness of values assigned to a property and wrapping around retrieval mechanisms for a property. I personally call the way of maintaining value-correctness for properties through interceptors virtual properties, which fits quite nice I think.
In eZ Components we make heavy use of this methodology, especially with our option classes. This allows nice looking code like:
$dialog->options->text = "Test text";
While the $dialog object ensures that it's $options property holds nothing but instances of the option class. The latter one ensures, that its $text property has a correct value at any time. If this is violated anywhere, an exception is thrown. I think this is much more intuitive and comfortable than
$dialog->getOptions()->setText( "Test text" );
If you are interessted in this topic, you should buy the upcoming issue of the German "PHP Magazin", which will contain an article about these techniques and some more advanced.
Comments