PHP
  Home arrow PHP arrow Page 2 - Polymorphism, Design Patterns, and PHP Programming
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Polymorphism, Design Patterns, and PHP Programming
By: Sams Publishing
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 9
    2006-10-05


    Table of Contents:
  • Polymorphism, Design Patterns, and PHP Programming
  • Interfaces and Type Hints
  • The Factory Pattern
  • The Singleton Pattern

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Polymorphism, Design Patterns, and PHP Programming - Interfaces and Type Hints
    ( Page 2 of 4 )

    A key to successful delegation is to ensure that all classes that might be dispatched to are polymorphic. If you set as the $dbh parameter for the Weblog object a class that does not implement fetch_row(), a fatal error will be generated at runtime. Runtime error detection is hard enough, without having to manually ensure that all your objects implement all the requisite functions.

    To help catch these sorts of errors at an earlier stage, PHP5 introduces the concept of interfaces. An interface is like a skeleton of a class. It defines any number of methods, but it provides no code for them—only a prototype, such as the arguments of the function. Here is a basic interface that specifies the methods needed for a database connection:

    interface DB_Connection {
     public function execute($query);
     public function prepare($query);
    }

    Whereas you inherit from a class by extending it, with an interface, because there is no code defined, you simply agree to implement the functions it defines in the way it defines them.

    For example, DB_Mysql implements all the function prototypes specified by DB_Connection, so you could declare it as follows:

    class DB_Mysql implements DB_Connection {
     /* class definition */
    }

    If you declare a class as implementing an interface when it in fact does not, you get a compile-time error. For example, say you create a class DB_Foo that implements neither method:

    <?php
    require "DB/Connection.inc";
    class DB_Foo implements DB_Connection {}
    ?>

    Running this class generates the following error:

    Fatal error: Class db_foo contains 2 abstract
    methods and must be declared abstract (db connection::execute, db
    connection:: prepare) in /Users/george/Advanced
    PHP/examples/chapter-2/14.php on line 3

    PHP does not support multiple inheritance. That is, a class cannot directly derive from more than one class. For example, the following is invalid syntax:

    class A extends B, C {}

    However, because an interface specifies only a prototype and not an implementation, a class can implement an arbitrary number of interfaces. This means that if you have two interfaces A and B, a class C can commit to implementing them both, as follows:

    <?php
    
    interface A {
     public function abba();
    }
    
    interface B {
     public function bar();
    }
    
    class C implements A, B {
     public function abba()
     {
      // abba;
     }
     public function bar()
     {
      // bar;
     }
    }
    ?>

    An intermediate step between interfaces and classes is abstract classes. An abstract class can contain both fleshed-out methods (which are inherited) and abstract methods (which must be defined by inheritors). The following example shows an abstract class A, which fully implements the method abba() but defines bar() as an abstract:

    abstract class A {
     public function abba()
     {
      // abba
     }
     abstract public function bar();
    }

    Because bar() is not fully defined, it cannot be instantiated itself. It can be derived from, however, and as long as the deriving class implements all of A's abstract methods, it can then be instantiated. B extends A and implements bar(), meaning that it can be instantiated without issue:

    class B {
     public function bar()
     {
      $this->abba();
     }
    }
    $b = new B;

    Because abstract classes actually implement some of their methods, they are considered classes from the point of view of inheritance. This means that a class can extend only a single abstract class.

    Interfaces help prevent you from shooting yourself in the foot when you declare classes intended to be polymorphic, but they are only half the solution to preventing delegation errors. You also need to be able to ensure that a function that expects an object to implement a certain interface actually receives such an object.

    You can, of course, perform this sort of computation directly in your code by manually checking an object's class with the is_a() function, as in this example:

    function addDB($dbh) 
    {
     if(!is_a($dbh, "DB_Connection")) {
      trigger_error("\$dbh is not a DB_Connection
    object", E_USER_ERROR); } $this->dbh = $dbh; }

    This method has two flaws:

    • It requires a lot of verbiage to simply check the type of a passed parameter.

    • More seriously, it is not a part of the prototype declaration for the function. This means that you cannot force this sort of parameter checking in classes that implement a given interface.

    PHP5 addresses these deficiencies by introducing the possibility of type-checking/type hinting in function declarations and prototypes. To enable this feature for a function, you declare it as follows:

    function addDB(DB_Connection $dbh)
    {
     $this->dbh = $dbh;
    }

    This function behaves exactly as the previous example, generating a fatal error if $dbh is not an instance of the DB_Connection class (either directly or via inheritance or interface implementation).



     
     
    >>> More PHP Articles          >>> More By Sams Publishing
     

       

    PHP ARTICLES

    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL
    - Method Chaining: Adding More Methods to the ...
    - Method Chaining in PHP 5
    - The Role of Interfaces in Applying the Depen...
    - Dependency Injection: Using a Setter Method ...
    - Using a Model Class with the Dependency Inje...
    - Injecting Objects Using Setter Methods with ...
    - Injecting Objects by Constructor with the De...
    - The Dependency Injection Design Pattern in P...
    - Performing Inferential Statistical Analysis ...
    - Performing Descriptive Statistical Analysis ...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 4 Hosted by Hostway
    Stay green...Green IT