Design Pattern Theory Design Patterns - Some time ago people realized that we were solving the same problems again and again, they then decided to sit down and come up with really good solutions to those problems, they’re called design patterns. The advantages of design patterns are two fold: first they present a well defined solution to common problems, second they provide a common language for developers. The Singleton Pattern The singleton pattern is used to ensure that you only have one instance of a given class at a time. This is useful in a myriad of circumstances, resource connections (database, file, external) most notably. class singleton { private static $instance = null; protected function __construct() { /* … */ } public function getInstance() { if (self::$instance === null) { $class = __CLASS__; self::$instance = new $class; } return self::$instance; } } $connection = new singleton(); //Error $connection = singleton::getInstance(); The Singleton is, probably, the simplest design pattern. Its goal is to provide access to a single resource that is never duplicated, but that is made available to any portion of an application that requests it without the need to keep track of its existence. .database connection make constructor private/protected The Factory Pattern The factory pattern is used to provide a common interface to a series of classes with identical functionality but different internals (think data storage, varying shipping systems, payment processing) The “factory” provides an instance of the appropriate class. The Factory pattern is used in scenarios where you have a generic class (the factory) that provides the facilities for creating instances of one or more separate “specialized” classes that handle the same task in different ways. A good situation in which the Factory pattern provides an excellent solution is the management of multiple storage mechanisms for a given task. An Factory Pattern example: class Configuration { const STORE_INI = 1; const STORE_DB = 2; const STORE_XML = 3; public static function getStore($type = self::STORE_XML) { switch ($type) { case self::STORE_INI: return new Configuration_Ini(); case self::STORE_DB: return new Configuration_DB(); case self::STORE_XML: return new Configuration_XML(); default: throw new Exception(“Unknown Datastore Specified.”); } } } class Configuration_Ini { // … } class Configuration_DB { // … } class Configuration_XML { // … } $config = Configuration::getStore(Configuration::STORE_XML); class shippment { public static function getShippmentClass($method) { switch ($method) { case “Fedex”: return new shipFedEx(); break; case “USPS”: return new shipUSPS(); break; case “UPS”: return new shipUPS(); break; default: throw new Exception(“Unknown shipment method requested”); } } } $shippingInterface = shippment::getShippmentClass(“Fedex”); The Registry Pattern By taking the Singleton pattern a little further, we can implement the Registry pattern. This allows us to use any object as a Singleton without it being written specifically that way. An extension of the Singleton Pattern, that allows for differing functionality based on some input data. Imagine using the Singleton pattern on a database, but occasionally requiring a connection to an alternate database, Registry provides this. The Model-View-Controller Pattern MVC .Complex pattern, the user initiates an action via the controller, which interfaces with the model, finally the view is called which takes care of dealing with the user interface. .This clear distinction between various layers allows for modularity in code, entire levels of code can be swapped in and out. .Many modern frameworks use this pattern, such as Symfony, CakePHP and Ruby on Rails. Its goal is that of providing a methodology for separating the business logic (model) from the display logic (view) and the decisional controls (controller). In a typical MVC setup, the user initiates an action (even a default one) by calling the Controller. This, in turn, interfaces with the Model, causing it to perform some sort of action and, therefore, changing its state. Finally, the View is called, thus causing the user interface to be refreshed to reflect the changes in the Model and the action requested of the Controller, and the cycle begins anew. The ActiveRecord Pattern Encapsulates a data source, allowing external code to concentrate on using the data while the active record pattern provides a consistent interface, hiding the work that goes into iterating over records, making changes etc. Most commonly implemented with databases – One of the things people love about Ruby This is used to encapsulate access to a data source so that the act of accessing its components—both for reading and for writing—is, in fact, hidden within the class that implements the pattern, allowing its callers to worry about using the data, as opposed to dealing with the database. The Standard PHP Library SPL .Standard PHP Library .Extension available and compiled by default in PHP 5 .Improved in PHP 5.1 .http://www.php.net/~helly/php/ext/spl/ The Standard PHP Library (SPL) is a great addition to PHP 5. It provides a number of very useful facilities that expose some of PHP’s internal functionality and allow the “userland” developer to write objects that are capable of behaving like arrays, or that transparently implement certain iterative design patterns to PHP’s own core functionality, so that you, for example, use a foreach() construct to loop through an object as if it were an array, or even access its individual elements using the array operator []. SPL works primarily by providing a number of interfaces that can be used to implement the functionality required to perform certain operations. By far, the largest number of patterns exposed by SPL are iterators. Code Reuse .We solve the same problems every day .We solve the same problems as our neighbor every day .We solve the same problems on every project .Code Reuse allows us to cut development time while increasing code quality .Array Access to objects The ArrayAccess interface interface ArrayAccess { function offsetSet($offset, $value); function offsetGet($offset); function offsetUnset($offset); function offsetExists($offset); } .Simple Iteration The Iterator interface interface Iterator {} function current(); function next(); function rewind(); function key(); function valid(); } .Seekable Iteration The SeekableIterator interface interface SeekableIterator { function current(); function next(); function rewind(); function key(); function valid(); function seek($index); } .Recursive Iteration The RecursiveIteratorIterator .Filtered Iteration The FilterIterator Conclusion SPL contains a number of very useful code sets, take a look, they’re really useful. Design patterns present common solutions to common problems, they also provide programmers with a common language when describing solutions.