[Zend PHP5 Cerification] Lectures -- 9. OOP Design and Theory

DesignPattern Theory

DesignPatterns - Some time ago people realized that we were solving thesame problems again and again, they then decided to sit down and comeup with really good solutions to those problems, they’re calleddesign patterns.

The advantages of design patterns are twofold: first they present a well defined solution to common problems,second they provide a common language for developers.

 

Read more aboutDesign Pattern, don’t just for pass the exam sake. The exam regardto the Design Pattern and general OOP theory is very basic. Anyway,following I listed some basic Design Pattern may tested in the exam.Also, I think you should look into the SPL(standard PHP Library) andPECL(PHP Extension Community Library) and PEAR(PHP Extension andApplication Repository). 

The famous GoF book! –see morepatterns  


TheSingleton Pattern

The singleton pattern is used toensure that you only have one instance of a given class at atime.
This is useful in a myriad of circumstances, resourceconnections (database, file, external) most notably.

classsingleton
{
private static $instance = null;
protectedfunction __construct()
{ /* ... */ }
public functiongetInstance()
{
if (self::$instance === null)
{
$class =__CLASS__;
self::$instance = new $class;
}
returnself::$instance;
}
}
$connection = new singleton();//Error
$connection = singleton::getInstance();

 

TheSingleton is, probably, the simplest design pattern. Its goal is toprovide access to a single resource that is never duplicated, butthat is made available to any portion of an application that requestsit without the need to keep track of its existence.

.databaseconnection
 make constructor private/protected

TheFactory Pattern

The factory pattern is used to providea common interface to a series of classes with identicalfunctionality but different internals (think data storage, varyingshipping systems, payment processing)

The “factory”provides an instance of the appropriate class.

The Factorypattern is used in scenarios where you have a generic class (thefactory) that provides the facilities for creating instances of oneor more separate “specialized” classes that handle the same taskin different ways.
A good situation in which the Factory patternprovides an excellent solution is the management of multiple storagemechanisms for a given task.


An Factory Patternexample:
class Configuration {
const STORE_INI = 1;
constSTORE_DB = 2;
const STORE_XML = 3;
public static functiongetStore($type = self::STORE_XML)
{
switch ($type) {
caseself::STORE_INI:
return new Configuration_Ini();
caseself::STORE_DB:
return new Configuration_DB();
caseself::STORE_XML:
return new Configuration_XML();
default:
thrownew Exception("Unknown Datastore Specified.");
}
}
}

classConfiguration_Ini {
// ...
}

class Configuration_DB {
//...
}
class Configuration_XML {
// ...
}
$config =Configuration::getStore(Configuration::STORE_XML);


classshippment
{ public static function getShippmentClass($method){
switch ($method) {
case "Fedex":
return newshipFedEx();
break;
case "USPS":
return newshipUSPS();
break;
case "UPS":
return newshipUPS();
break;
default:
throw new Exception("Unknownshipment method requested");
}
}
}
$shippingInterface= shippment::getShippmentClass("Fedex");

 


TheRegistry Pattern
By taking the Singleton pattern a littlefurther, we can implement the Registry pattern. This allows us to useany object as a Singleton without it being written specifically thatway.

An extension of the Singleton Pattern, that allows fordiffering functionality based on some input data.
Imagineusing the Singleton pattern on a database, but occasionally requiringa connection to an alternate database, Registry providesthis.

 

 

The Model-View-ControllerPattern  MVC
.Complex pattern, the user initiates an actionvia the controller, which interfaces with the model, finally the viewis called which takes care of dealing with the user interface.

.Thisclear distinction between various layers allows for modularity incode, entire levels of code can be swapped in and out.

.Manymodern frameworks use this pattern, such as Symfony, CakePHP and Rubyon Rails.
Its goal is that of providing a methodology forseparating 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 theController. This, in turn, interfaces with the Model, causing it toperform some sort of action and, therefore, changing its state.Finally, the View is called, thus causing the user interface to berefreshed to reflect the changes in the Model and the actionrequested of the Controller, and the cycle begins anew.


TheActiveRecord Pattern
 

Encapsulates a data source,allowing external code to concentrate on using the data while theactive record pattern provides a consistent interface, hiding thework that goes into iterating over records, making changes etc.

Mostcommonly implemented with databases – One of the things people loveabout Ruby


This is used to encapsulate access to adata source so that the act of accessing its components—both forreading and for writing—is, in fact, hidden within the class thatimplements the pattern, allowing its callers to worry about using thedata, as opposed to dealing with the database.



TheStandard PHP Library   SPL

.Standard PHPLibrary
.Extension available and compiled by default in PHP5
.Improved in PHP5.1
.http://www.php.net/~helly/php/ext/spl/


TheStandard PHP Library (SPL) is a great addition to PHP 5. It providesa number of very useful facilities that expose some of PHP’sinternal functionality and allow the “userland” developer towrite objects that are capable of behaving like arrays, or thattransparently implement certain iterative design patterns to PHP’sown core functionality, so that you, for example, use a foreach()construct to loop through an object as if it were an array, or evenaccess its individual elements using the array operator [].

SPLworks primarily by providing a number of interfaces that can be usedto implement the functionality required to perform certainoperations. By far, the largest number of patterns exposed by SPL areiterators.


Code Reuse
.We solve the sameproblems every day
.We solve the same problems as our neighborevery day
.We solve the same problems on every project
.CodeReuse allows us to cut development time while increasing codequality

 


.Array Access to objects   TheArrayAccess interface

interface ArrayAccess {
functionoffsetSet($offset, $value);
function offsetGet($offset);
functionoffsetUnset($offset);
function offsetExists($offset);
}


.SimpleIteration               The Iterator interface

interface Iterator {}
functioncurrent();
function next();
function rewind();
functionkey();
function valid();
}

 

.SeekableIteration          The SeekableIterator interface

interfaceSeekableIterator {
function current();
functionnext();
function rewind();
function key();
functionvalid();
function seek($index);
}

 

 

.RecursiveIteration          The RecursiveIteratorIterator

.FilteredIteration             The FilterIterator

 

Conclusion

SPLcontains a number of very useful code sets, take a look, they’rereally useful.
Design patterns present common solutions to commonproblems, they also provide programmers with a common language whendescribing solutions.

你可能感兴趣的:(design)