Wrapping Factory

Russian Dolls

This is a general purpose implementation of the Adapter and Decorator design patterns.It allows you to wrap objects inside other objects just like the famous Russian Dolls. Each new layer (wrapping) can add or remove functionality (attributes/methods) to/from the object.

How it works

Each wrapping must extend the WrappingAbstract class which only passes calls to methods or attributes to the wrapped object. The wrapped object can be another wrapping or another type of object. After you apply all the wrapping layers you get a stack of objects each one inside another. The public object (the outermost layer of the wrapping).

The WrappingFactory class stores the definitions of the wrapping layers and the order in which layers are applied but it’s your job to decide if you want to apply the wrapping to an object.

When it can be used

The sky is the limit. Well, not really (see the limitations)

MVC example. Let’s say you have a Model object (as defined by the MVC pattern) that have some methods (like save()) that you want not be available when you pass the Model to the View. So, before passing the Model to the View you wrap it inside an another object that will prevent the execution of the save() method. Or you don’t want certain users access to certain parts of the object (eg: you show only 500 characters from the article for anonymous users).

WordPress example. I am not a master of the WordPress architecture but at it’s base you have entries (which can be pages, posts or attachments). By default wordpress “decorates” the posts with categories, tags and attachments and pages have aditional functionality because they can belong to a parent page. If you were to think of a content piece in its most simple form and try to apply the wrapping pattern you would see a page as basic piece of content wrapped inside objects that offer tree structure functionality, a post would be basic piece of content wrapped inside a layer that give you access to tags, wrapped inside another layer that gives you access to categories etc.

Limits

Each wrapping can only access public methods/attributes of the wrapped object. Sometimes when you write a wrapper class you may forget that a method you’re trying to use may be private in the wrapped object and  you will need to either redefine that method inside the wrapper or make it public on the wrapped object.

Because of the limitations of __get() and __set() you won’t be able to access array-type attributes of your wrapped object

Files available on GitHub. https://github.com/adrianmiu/WrappingFactory