PHP Decorator Writer Script

I started using decorators in PHP more often to change the behavior of an object at runtime. My problem in the first place is laziness, we have many heritage classes with many methods, and the thought of having to rewrite / redefine all of them for each decorator class makes me sad. Does anyone know of a command line utility that exists that will write these decorators for me?

Or maybe there is a better way to do this?

+4
source share
2 answers

From the question that I understand, you are too lazy to add other methods, for example. those that do not alter the decorated specimen. For this purpose you can use the __call magic method

 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 magic interceptors always carry a performance penalty. If you have a lot of nested decorators, this may be noteworthy. If in doubt, a guideline.

+3
source

GOF recommends that all classes in this template be derived from a single abstract component class. You can get a class from an existing class to add this functionality to the DynamicComponent file with the same effect. You are extracting internal objects from this class. In this class, magic methods can be used to dynamically manage properties and routing messages. You will need the functions __get (), _set (), _ call () and possibly__construct (). I use a factory method with protected constructors to simulate multiple inheritance. factory returns a stand-alone component or a wrapped component (usually, as directed by the collector, for example, a tree builder, which, for example, receives data from a database).

Transfer functionality occurs in an abstract class, also derived from a common component class.

You provide implementations of each method in a common interface. These overriding functions synchronize data in the internal element and the external element and provide wiring for transferring raw messages to the internal element. In fact, each class participating in this template automatically gets the main functions __get () and __set () from the parent and extended from inner_item. They are bound in an abstract class to send messages to their inner_item instances. A particular shell gets a component interface that is free of it, and can focus on added functionality. If you want to get rid of the common parent, then the common interface will need to be reinstalled in each concrete wrapper class. Another advantage is the ability to add functions such as compare and __toString () to the base class. Objects can be used completely interchangeably in functions such as usort () and other list / tree / stack / cue / array / whatever structures, because they are not just similar to the same interface, they are of the same type!

0
source

All Articles