Memcache module provides handy procedural and object oriented interface to memcached, highly effective caching daemon, which was especially designed to decrease database load in dynamic web applications.
Memcached is a high-performance, distributed memory object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load.
The Memcache module also provides a session handler (memcache).
Lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed.
storing the instances in a map, so you get the same instance the next time you ask for an instance with same parameter (compare with a singleton pattern)
using lazy initialization to instantiate the object the first time it is requested (lazy initialization pattern).
The intuitive naming of Patterns gives a clue as to the meaning of a Transfer Object. In short a Transfer Object bundles data into a single, easy to transport object. The Transfer Object can sometimes be referred to as the Data Transfer Object (as in POEAA). Both names refer to the same Design Pattern.
There are a number of reasons why a Transfer Object is useful. By grouping related sets of data in a single object, it reduces the complexity of passing such data into methods by removing long parameter lists. Long parameter lists are often termed a "code smell" since they can be confusing and parameter order must be maintained even if a value is not used. As a return value from a method, a Transfer Object also enables multiple values be returned.
Of course this can be easily accomplished in PHP by an array. While a Transfer Object may resemble an array, it has other features that ultimately make it more useful:
A Transfer Object has a class type which can help enforce an interface by using PHP5's Type Hinting.
It's preset properties will always be available (with default values). One can even prevent the setting of new public properties.
It is possible to perform additional actions in a Transfer Object upon setting a new value via PHP5's Magic Methods.
Definition
Definition: The Transfer Object allows the encapsulation of multiple known values in a single object that supports basic data storage and retrieval functionality.
Implementation for PHP5
Implementing a Transfer Object is quite simple. A distinction should however be made between a Transfer Object and the very similar Value Object. The values in a Transfer Object are not immutable, i.e. they can be changed via a public interface (getters and setters) or by defining the Transfer Object's properties as public or using Magic Methods to simulate public properties in the interface. Often the two Pattern titles are used interchangeably although there are differences in their respective goals.
An example of a Transfer Object might be an object which stores the data associated with a row in a database table. Rather than passing each database value individually to other objects' methods, one need only pass the representative Transfer Object. This simplifies operations quite a bit and removes a lot of complexity from a class interface if used wisely.
Moreover, since a Transfer Object has a specific class type. An accepting method can restrict a parameter to only accept the expected Transfer Object by using Type Hinting.
A simple PHP5 Transfer Object:
Note that the properties are defined as public. For this Transfer Object, the client code can use the properties directly without accessors. Since a Transfer Object by definition is not designed to hold arbirary properties (created by client code), the Registry Pattern is more suited for such a purpose or one can even fall back on an array. While a Registry is agnostic to its contents, a Transfer Object's property names (or alternatively the matching setters/getters) form part of its testable interface.
A Unit Test (using SimpleTest) for the above simple Transfer Object would contain:
It's worth noting that the most common alternative to a Transfer Object is a simple array. An array and a simple Transfer Object share similar characteristics. A Transfer Object however has a class type and will always contain specific properties (optionally with default values). Additionally a Transfer Object can perform it's own private internal operations on incoming and outgoing data by using the PHP5 Magic Methods: __set() and __call() to overload the public properties.
Let's consider our previous User Row example. As the User Row Transfer object is passed around our application and other classes may alter the original data. This changed data will need to be stored to the database. To prevent unnecessary SQL update operations, we would like if the Transfer Object could inform the application whether it's data has been changed (i.e. dirty) or unchanged (i.e. clean).
For the example below we'll make use of PHP5's Magic Methods in order to control the value of an additional private property - isDirty. Other objects will be able to retrieve the value of isDirty by calling the isDirty() method.
The differences from our simple prior example are not all that complex assuming you are familiar with PHP5's overloading[1] magic methods. The use of the Magic Methods sets up access to private member properties (the private $data array) while upholding the interface that properties are publicly accessible.
Overloading with magic methods lets us use the class in the same way as the first example only this time the Transfer Object can check whether it's default values have changed by setting the value of the isDirty property to TRUE. There are no public properties since magic functions cannot overload a property which is already defined - hence they are moved to a private array. As a last step we add a public getter method to retrieve the isDirty value.
The use of magic methods which rely solely on a defined private array of possible values also has an additional effect: it prevents the setting of any new public properties by client code. In effect the magic methods version is limited to the defined properties - no new ones can be set.
In both cases, the classes can be used in the following way.
Output:
Padraic mypassword myemail mywebsite
As with our simple Transfer Object, we can verify that the complex version follows an identical interface as the simple version by writing a Unit Test to verify the expected behaviour of the class. The Unit Test is identical to the last version, except that we additionally ensure the isDirty property value is set to TRUE when a value is changed from the defaults (set via the constructor when a User_Row object is instantiated.
As we previously noted. A Transfer Object has a class type - an array has no specific type except the generic "array" (from PHP 5.1). This difference is one further advantage of using this pattern instead of an array. If you take the following client code, any attempt to pass a parameter which is not an object of the type User_Row to the constructor will result in a fatal error. This safety net feature ensures client code adheres to this class's interface and is not capable of passing other object types or arrays. For example, our User_Row_Printer class below only knows how to work with User_Row objects - giving it any other object might result in unexpected output or a fatal error.
Implementing a PHP4 Transfer Object is not as effective as in PHP5. The lack of property visibility keywords (private, protected and public) mean that property access cannot be restricted. This rules out effective getters and setters which might replace the PHP5 use of the magic methods __get() and __set(). Getters and setters can be implemented, but without access keywords the client is free to ignore them and access the object properties directly.
Still, the basic structure remains the same and type hinting (if desireable) can be implemented within any method by making an is_a() check against the lowercased class type of the relevant Transfer Object being passed as a parameter to the method.
A simple Transfer Object example for PHP4:
Unit Testing of the PHP4 version is largely similar to the PHP5 Unit Tests (minus the PHP5 syntax differences).
The Transfer Object is a simple Design Pattern. At first glance it can easily be mistaken for a glorified array but there are a number of important differences. Unlike an array, a Transfer Object has a specific type which allows a class's method be restricted to only accepting a specific Transfer Object through Type Hinting. While an array can have any number of additional fields appended, a Transfer Object can have a fixed number of properties enforced (see PHP5 complex example code). As a result, Transfer Objects of the same type can always be handled in the exact same way. Another difference is that a Transfer Object can perform its own internal operations when values are set. The PHP5 examples above illustrate how a User_Row object can track whether it's default values have changed since the object was created thereby allowing client code (perhaps a Data Access class) tell when the database row the Transfer Object represents requires updating.
On a par with an array, a Transfer Object by bundling multiple values in a single entity can help alleviate the long parameter list "code smell" when refactoring and enable methods to return multiple values encapsulated in an object. This is not its primary purpose, but the resemblance to a Parameter Object is close.
Note: This is a draft article dated 14 September 2006. The supplied code has not been tested.
Altering the behaviour of objects is a tricky business. In many cases you do not wish to alter the original object but rather tack on additional or modified behaviours. The easiest way to achieve this is using inheritance. Creating a series of subclasses allows a programmer to add additional methods and properties or alter those which already exist in the parent class. Unfortunately, as other Design Patterns often point out, inheritance can be a path full of pitfalls and traps for the unwary. The more layers exist in a class hierarchy, the more cumbersome and difficult to manage the whole structure becomes.
If we decide to set a goal of maintaining the original class as is and of disallowing any further inheritance, we immediately gain some measure of control. By preventing further inheritance we have a smaller discrete unit perfect for reuse in other projects minus the specific modifications current circumstances might require. To extend the original class and add new or modified behaviour to it we can use the Decorator Pattern.
The Decorator Pattern creates a separate class family which adds extended behaviour to an existing class while leaving the existing class unchanged. As the class is ported for reuse, we can transparently add new Decorators specific to each new application as we see fit. Additionally, since the Decorator classes are in a separate hierarchy they have a variable type which is distinct from the original class, i.e. we can tell if a class is a Decorator.
Of course the Decorator Pattern is not a silver bullet. Inheritance remains the simplest option and the Decorator Pattern is not suitable for all scenarios. However it remains an extremely useful option and is one of the more popular Design Patterns programmers are intimately familiar with, especially in web application development.
Pattern Definition
Definition: The Decorator Pattern represents the process of creating a new class hierarchy which adds new or modified behaviour to an existing class without modifying the existing class from its original state.
Description of the Problem
Let's introduce an example of a situation which lends itself to improvement through the application of the Design Pattern. During the development of an application we discover a need to store data to a file. For simplicity, the data is a simple string. A generic String_Writer class is ported from a pre-existing project. The class simply accepts a string and writes it to a specified file, storing the data in a property access by a public getter/setter pair. The class is generic in that it just stores strings. Outputting and additional formatting for display is not handled by the basic class. As a result it is decided to extend the String_Writer class behaviour to add formatting options for output and to add an output method.
Inheritance has been ruled out as an option for a number of reasons. First of all, there can be any number of formatting options. Adding each option to the original String_Writer class through inheritance could become complex, resulting in a class hierarchy many levels deep. Changes to any class high in the hierarchy might require modifying all subsequent child classes for the change in interface or properties in the higher level parent - a time-consuming task.
The Decorator Pattern on the other hand avoids multi-level inheritance.
Implementing the Decorator Pattern in PHP5
The basic String_Writer class is extremely simple:
The String_Writer class should be fairly simple to follow. We instantiate the class passing the path to the relevant log file in the constructor parameter. To store a new string in the file, we call setString(), followed by store(). Each store appends a newline to the data using the PHP_EOL constant to be agreeable for Unix, Mac or Windows systems.
In order to format the stored string for output without resorting to inheritance, we create a new class hierarchy. It's structure will be simple, a parent class and any number of specific child classes. We will call the parent class String_Formatter. The Formatter and its children implement the Decorator Pattern, i.e. they extend the functionality of the existing class, String_Writer, by supplying new formatting and output options. The String_Writer class is left unchanged.
The String_Formatter class is as follows:
The String_Formatter class is likewise simple. The additional behaviour is simply the output() method. By default this simply returns the value of the string held by the String_Writer object. No formatting is performed by default.
To make things interesting, we extend our basic String_Formatter class with a selection of child classes which format the output string. Here's three examples: Uppercase, Reverse, and Escape.
Each individual subclass performs a different formatting function. Of course using just one type of formatting is limited. Rather each subclass of String_Formatter accepts other related classes of the same type as arguments to its constructor. By linking all the decorators to each other, it is possible to perform specific formatting by calling each Decorator's formatting method.
An example usage:
Disadvantages
The Decorator Pattern is not suitable for all possible situations. If the number of Decorator options is limited and it does not add significantly to the number of hierarchy levels then inheritance is possibly a better option. In general however, class hierarchies should be fairly shallow. If a hierachy of classes is more than three levels deep then you should consider refactoring some of the additional elements using the Decorator Pattern or certain other Patterns instead. A deep class hierarchy can easily become a morass of dependencies where changes have knock on effects across numerous inheriting classes. Avoiding such maintenance black holes should be a priority.
Conclusion
In this article we have briefly examined a simple implementation of the Decorator Pattern. This pattern is an alternative to persistent subclassing in order to add new or modified behaviour to the ultimate parent class. Rather than using inheritance, one can build a separate class hierarchy of the behaviour required and apply the methods of the new classes to the original class. An essential feature of the Decorator Pattern is that the original class does not require any additional modification in order to apply the Pattern.
A Composite a means of assembling and organising classes such that standalone objects and object collections are members of the same class hierarchy and may be used by client code without distinguishing between them.
Imagine for a moment a book. In a book, you'll find pages, chapters, cover-pages, subsections, prefaces, etc. Of course, we don't slop them all together and call it a book: the book is divided into chapters, which are then further divided into pages. An in-memory representation of a book composite might look like this:
At first blush, it might seem logical to simply claim that a book only contains chapters, chapters only contain sections and sections only contain pages, and have each of the classes code around each of their unique interfaces. But there are common traits around all these elements, for example, they all contain text (or at least their children do). Standardize the interfaces around these common traits, and you've got a composite.
Example
Before we demonstrate the implementation of the pattern, let's look at how client code might utilise it. Let's take the example from our introduction a bit further. After implementing each of the Book, Chapter and Page classes we would expect our client code to utilise all these objects without distinguishing between them.
Notice how Book and Chapter both have addText() methods, rather than their own addChapter() and addPage() methods. This allows us to insert the standalone page, something not possible if it was assumed that all the children of a Book were chapters. Furthermore, all the classes in the hierarchy implement output(), allowing us to show the entire book, just one chapter, or even a single page.
Those familiar with the Document Object Model may note striking similarities between our example and the standard use-case of DOM. This is intentional: DOM is an extremely good example of the composite pattern. All elements in an XML document boil down to nodes, and they can be treated uniformly whether they are elements, text, or the document root node.
Implementation
This section is actively under discussion, see Talk:Composite.
Before we can actually start writing the code, there are a few common implementation issues we have to deal with first.
Child management operators
You may have noticed that in the above code, we never executed addText() on a page object. Since it's not a composite, such an operation is not meaningful. However, the whole point about composition is that you can treat components uniformly! Gang of Four boils it down to a trade-off between "safety and transparency". You can:
Define child operations at the very bottom of the class hierarchy, so that even the non-composite objects have it. This lets you treat all objects uniformly, but lets the client do meaningless things like $marble->add($bag). In our case, however, we can implement an interesting fallback behavior: call output() on the passed node and then concatenate that to the existing page contents. This may not always be possible, however, and even when it is, it should be considered poor form.
Define child operations only for Composites. While this means that it's now impossible for the client to add bag to the marble, it also means that the interfaces aren't uniform anymore.
The first possibility might look like this:
While the second possibility would look like this:
Throwing an "Attempt to call undefined function" error when addText is called on Page.
A rich base interface
The previous issue ties into a more general one, that is, how much should we stuff into the parent class? On one hand, anything we put into the base class is uniform across the entire hiearchy and can be used with impunity. On the other hand, it could mean a lot of junk methods that are meaningless for a particlar object in the hierarchy. The advice it to use good judgment and a little creativity for default behavior.
So, here's an implementation of the book class mentioned above.
Note that in this example the model and view are mixed together, which is generally considered a no-no. Find out how to seperate the HTML generation from these classes using a Visitor. You may also want to go through the book page by page, that would be implemented with an Iterator.
Hi, I am Vinod working as a Sr. Software Developer on PHP, MySql, Linux, Ajax etc. for last 4 years. This blog is a medium to share some thoughts & experiments of mine which I've experienced in the span of my professional career.
The Information in this weblog is provided "AS IS" with no warranties and confers no rights. This webLog does not represents the thoughts, intentions, plans, startegies, information about/of my employer. This is solely my thoughts which i want to share across. My thoughts and opinions might change from time to time as i learn more and develop deep knowledge about things which i write here.