This is a discussion on What are the design patterns available in php? within the PHP Programming forums, part of the Web Development category; There are 16 design patterns available. # The ValueObject Pattern # The Factory Pattern # The Singleton Pattern # The Registry Pattern # The MockObject ...
| |||||||
| Register | FAQ | Members List | Calendar | Mark Forums Read |
| |||
| There are 16 design patterns available. # The ValueObject Pattern # The Factory Pattern # The Singleton Pattern # The Registry Pattern # The MockObject Pattern # The Strategy Pattern # The Iterator Pattern # The Observer Pattern # The Specification Pattern # The Proxy Pattern # The Decorator Pattern # The Adapter Pattern # The ActiveRecord Pattern # The TableDataGateway Pattern # The DataMapper Pattern # The Model-View-Controller Pattern Thanks, Ramkumar.B Last edited by ramkumaraol : 11-16-2007 at 02:45 AM. |
| Sponsored Links |
| |||
| The ValueObject pattern: VOs are actually a J2EE pattern. It can easily be implemented in PHP. A value object corresponds directly to a C struct. It's a class that contains only member variables and no methods other than convenience methods (usually none). A VO corresponds to a business object. A VO typically corresponds directly to a database table. Naming the VO member variables equal to the database fields is a good idea. Do not forget the ID column. PHP Code: Ramkumar.B Last edited by ramkumaraol : 11-28-2007 at 06:10 AM. |
| |||
| Another example of Value Object pattern: PHP Code: Ramkumar.B Last edited by ramkumaraol : 11-28-2007 at 06:11 AM. |
| |||
| The Factory pattern: As you know, there are many approaches to building regular web forms. Commonly, we plan carefully what kind of data needs to be collected from users, then open our editor and write some (X)HTML code to display the proper form, including a few text boxes, radio buttons and so forth. While this method may be quick and simple for implementing on small websites, when an application grows significantly in size, an object-based method is often much more efficient. If the program will use numerous forms for collecting user data, the form creation process might be reduced to something as simple as instantiating some form element objects and deciding the best layout for them. The Factory pattern is very powerful and flexible, since it allows you to separate object instantiation from the rest of the client code. Generally speaking, this pattern is implemented through a class that accepts one or more parameters (inputs), and based on those parameters, determines what object to instantiate. Due to the intrinsic power of the Factory pattern, I'm going to apply it in a concrete situation: the implementation of a "form element factory" that will take care of factoring each form component. Doing so, creation of forms can be noticeably simplified and translated into better code portability. Thanks, Ramkumar.B Last edited by ramkumaraol : 11-28-2007 at 06:11 AM. |
| |||
| Factory pattern: At some point in PHP development, programmers will discover a need to simplify the creation of some objects. Perhaps the object simply requires a number of detailed steps to create, all of which must be duplicated for every new object of that type. To remove such code duplication and simplify the task, the Factory Pattern offers a solution. In fact the Factory Pattern is something many programmers may discover by themselves since it is a logical step to take all the detailed creational steps of an object and try bundling into a new object to handle the task. The Factory Pattern can be applied as an individual class with sole responsibility for creating objects or as a single method within the object to be created (a Factory Method). In both cases, its purpose remains similar - to make creating an object easier. Definition Definition: An object implementing the Factory Pattern is an object which creates other objects of a specific type. Example One family of objects whose creation may require numerous complex steps are from Database Abstraction libraries such as the ADOdb Lite or PEAR::MDB2. These libraries involve instantiating a connection object, allowing plugin use, and connecting to a database using configuration options. The steps involved can range from simple two liners to using complex logic depending on the scenario and plugins required. Simplifying this process makes huge sense. One can write a dedicated Factory class to fetch configuration options and perform the instantiation and plugin tasks transparently (based on those options). A simple Factory interface and implementing class (with minimal tasks) for ADOdb Lite might look similar to: PHP Code: Of course, there are many other similar uses for a Factory. All that is required is that the Factory consolidate all the logic required to create an object. In the case above we have a single complex creation process for a Database Abstraction library's connection object. Another situation where a Factory is of use is where different objects of the same family must be created depending on some value. For example, we may have a Logging utility which is capable of outputting a log message either to the browser or to the command line. Or perhaps we want it stored for later viewing to a file. The typical logic used within our calling class to determine which to use may be similar to: PHP Code: The Factory Pattern suggests this creational logic should be isolated within its own class (the Factory) leaving the calling objects free to do their stuff and let the Factory worry about what Output object might be required. The result may look similar to: PHP Code: PHP Code: Thanks, Ramkumar.B |
| |||
| Factory pattern: Disadvantages The Factory Pattern is a common pattern to see implemented. It is a logical method of isolating the logic for creating a class, or the logic for deciding which concrete subclass of a family to instantiate. In this capacity it has few disadvantages. Some problems may arise when complex creational logic of various types co-exist - i.e. where it becomes necessary to utilise two or more Factory classes. One example might be our Database Abstraction Factory. It's sole purpose is to churn out ADOdb Lite connection objects applying configuration options, loading required plugins (if such added), etc. If someone were to decide that they needed access to PEAR::MDB2 or the traditional ADOdb library then the creational logic for instantiation and plugin loading would differ. Although this new piece of logic (deciding which library to use) could be integrated into the existing Factory class - it would simply turn into a very complex switch statement. Thanks, Ramkumar.B |
| |||
| Singleton Pattern: The Singleton is one of the simplest Patterns to understand. It's common usage is to ensure that only one instance of a class is ever instantiated. The reason for wanting such behaviour varies but typically it is because only one object instantiated from the source class is required and you want the resulting object to be available throughout an application, i.e. globally available. An example might be a class for storing Settings. A Settings class is a good candidate for a Singleton because its data is immutable (the only way to change settings data is to edit the settings file) and it is likely required in many areas of an application. Furthermore creating a new Settings object wherever it is needed is wasteful of resources - each is identical to all others. Definition Definition: The Singleton Pattern proposes a static method for creating an instance of a class in such a way that once instantiated further calls to the same static method return a reference to the original instantiated object. Thanks, Ramkumar.B Last edited by ramkumaraol : 11-28-2007 at 06:12 AM. |
| |||
| Example for Singleton Pattern: PHP Code: Ramkumar.B |
| |||
| Implementing the Singleton Pattern The key to implementing a Singleton is utilising a static variable; a variable whose value remains constant even when execution leaves its variable scope. This stores the object originally instantiated between calls to the static method Settings::getInstance(), and returns a reference to it on each subsequent call to the method. Also note that the constructor is usually made private. To ensure only one Settings object is ever used, we should restrict access to the constructor to prevent a new object being created in error. This specific restriction is not possible in PHP 4 so bear this in mind. The Singleton also requires careful consideration before use. It is by nature very similar to a global variable - the static method is available from anywhere in the application once the file containing the class is included. This can create problems similar to those experienced with global variables - and so should be used with some degree of care. The near global nature of the Singleton has led to it being referred to on occassion as an "Anti Pattern" since it is easily misused as an alternative to making data global. Using a Singleton is as simple as calling its static getInstance() method. PHP Code: Thanks, Ramkumar.B |
| |||
| Disadvantages of Singleton Pattern: The Singleton is not without its disadvantages. We have already noted that its global nature can cause problems similar to using global variables and encourage misuse without care. It can also make the practice of Unit Testing more difficult. Unit Testing typically tests individual objects. In testing the DB_Abstraction class above, a programmer may wish to "mock" the Settings object (i.e. insert a fake object with known return values). This is useful in cases where the Settings class may not even yet exist, and we need to emulate it. One solution, is to amend the class so that a developer may optionally pass a Settings object as a paramater into the constructor. The code for this may look similar to: PHP Code: Thanks, Ramkumar.B |
| |||
| Registry Pattern: The Registry is one of those Patterns where once you understand it, it seems so incredibly useful. Think of it as a basket; using a Registry you can add data (both values and objects) to the basket, and retrieve them as required from other parts of an application. Since all such data is handled by a single Registry object, it makes passing data and objects around an application far more simple than passing all such values as individual parameters to a constructor or setup method. In a similar fashion, a Registry can replace the need to have every object you need global access to acting as a Singleton. The Registry itself can either be passed around as a parameter or it can be turned into a Singleton to enable global access to it from anywhere in an application. Where it is used to replace numerous Singletons, it can replace the need to know each individual class name which often makes it easier to reuse classes in other applications. Definition Definition: The Registry Pattern allows the storing and retrieval of data and objects which need to be accessed globally in a single centralised object. Thanks, Ramkumar.B |
| |||
| Example of Registry Pattern: At a minimum a Registry allows data to be registered and retrieved, often allowing the setting of a label for the value being registered. One of the most common types of data to use a Registry for are objects for which global access from other objects is required. This simple PHP 5 example implements a private array to store objects and four methods for registering, unregistering, retrieving and checking the existence of objects. PHP Code: |