PHP Decorator Writer Script
I am starting to use decorat开发者_如何学Pythonors in PHP more often these days to modify an object's behavior at run-time. My problem is primarily one of laziness, we have many legacy classes with tons of methods and the thought of having to re-write/override all of them for each decorator class makes me sad. Does anyone know of a command line utility that exists that would write these decorators for me?
Or maybe there's a better way to go about this?
From the question I understand you are too lazy to add the other methods, e.g. those that do not modify the decorated instance. For this purpose, you can use use the magic method __call
public function __call($method, $args) {
return call_user_func_array(
array($this->decoratedInstance, $method),
$args
);
}
You can also add __callStatic
, __get
and __set
as needed. But note that the magic interceptors always incur some performance penalty. If you have a lot of nested decorators, this might be noticable. When in doubt, benchmark.
The GOF recommends that all of the classes in this pattern derive from a single abstract component class. You could derive a class from an existing class to add this functionality in a DynamicComponent clasto the same effect. You derive inner objects from this class. This class is where magic methods can be used to dynamically handle properties and route messages. You would need __get(), _set(),_call() and perhaps__construct(). I use a factory method with protected constructors to simulate multiple inheritance. The factory returns a stand alone component or a wrapped component(usually as directed by a collection builder like a tree builder which gets it's data from a database for example).
The wrapping functionality happens in an abstract class also derived from the common component class.
You provide implementations of each method in the common interface. These overriding functions synchronize the data in the inner item and the outer item and provide the wiring to pass unhandled messages through to the inner item. In effect, every class involved in this pattern automatically receives basic __get() and __set() functions from the parent and extended ones from the inner_item. These are linked in the abstract class to send messages to their inner_item counterparts. The concrete wrapper gets the component interface for free from it's parent and can focus on the added functionality. If you wanted to get rid of the common parent, then the common interface would need to be re-implemented in every concrete wrapper class. Another benefit is the ability to add functions like compare and __toString() to the base class. The objects can be used completely interchangeably in functions like usort() and other list/tree/stack/cue/array/whatever structures because they don't just look like the same interface, they are the same type!
精彩评论