PHPRO.ORG

By Kevin Waterson

  • Author: Kevin McArthur
  • Publisher: Apress
  • ISBN: 1590598199
  • Buy this book now

  • A letter from the author to the reader opens this book and states "If you want to take PHP way beyond the basics, this is the book for you". Not an immodest claim by any means. The 21 chapters are broken into five parts to cover several key aspects of modern development with PHP. It is these five sections that will be discussed, and are listed here.

    1. OOP and Patterns
    2. Testing and Documentation
    3. The Standard PHP Library (SPL)
    4. Model-View-Controller
    5. Web 2.0
    6. Summary
    7. Purchase

    At a quick glance the list looks to have chosen some topics that are well directed at developers who are already familiar with how PHP works, so if you are looking for an "Introduction To PHP" style of book, this is not the place to begin. However, if you are seeking to move on to the next level of development, or moving into Object Oriented design, this book will get you there.

    OOP and Patterns

    Design have been around for some time, and it is only recently that they been adopted en masse by the PHP community, although the new OO model was introduced with PHP 5, the uptake has been rather slow. The advent of the End Of Life of PHP 4 and the emergence of "Web 2.0" has had many PHP developers rethinking their coding structures as they shift from small dynamic web sites, to enterprise level applications. chapter on structuring applications.

    The Object Oriented (OO) sections leads off and begins with Abstract Classes and into Interfaces and gives simple, yet concise examples of how each may be used. A grateful addition here is also examples of errors which is mostly overlooked by many authors.

    The flow is easy for the reader to follow as it leads through various aspects of OO programming, with plenty of examples of how each aspect works, and how they can work together. The easy example code showing the use of parent scope is clear indication that the author has taken the time to follow the flow of information, not just at programming level, but at the authors level also. This example code from the book shows the "Using parent scope" example form the book.


    <?php

            
    class MyObject {

                    function 
    myMethod() {
                            
    //Standard functionality
                            
    echo "Standard Functionality\n";
                    }

            }


            class 
    MyOtherObject extends MyObject{
                    function 
    myMethod() {
                            
    //Add some new functionality
                            
    echo "New Functionality\n";

                            
    //Then call the original myMethod that is defined in MyObject
                            
    parent::myMethod();
                    }
            }

            
    $obj = new MyOtherObject();
            
    $obj->myMethod();

    ?>

    As the flow of code continues, the reader is taken on a logical step-by-step guide into the OO world and provides not just the bare essentials, but also the the logic behind the code. Those new to OO practices will find the steps both informative and logical as the author moves from dealing with information into dealing with errors with Exceptions.

    Exceptions have been a mystery to many who delve into the OO side of PHP and most choose not to make use of them as they are 'too hard' or not needed when traditional error handling methods still exist and can be implemented via a OO wrapper class of their own. The author quickly dispels any such illusions by exposing the Exception class internals in a simplistic fashion and demonstrating easy to use, and easy to understand code as follows.


    <?php

            
    function connectToDatabase() {
                    if(!
    $conn pg_connect(...)) {
                            throw new 
    Exception("Could not connect to the database");
                    }
            }

            try {
                    
    connectToDatabase();

            } catch(
    Exception $e) {
                    echo 
    $e->getMessage();
            }

    The coverage does not stop there, as code continues, greater use and possibilities are revealed for the use of Exceptions by extending the Exception class, and creating custom Exception classes for handling any condition. This culminates with a short Logging Exception Base Class for logging exception generated errors.

    A concise PHP installation section is provided and, like previous examples, the reader is treated to a step-by-step set up of the system the author is using to avoid incompatibilities when dealing with some of the future topics which touch on the bleeding edge of PHP in the shape of PHP 5.3 and PHP 6.0. It is these additions to the book that make it ahead of any other to date, as very little is known, and even less published, on new and emerging technologies and features to stem from the PHP base.

    What is known to most about the release of PHP 6 is the inclusion of Unicode. This has been both a major oversight within PHP and then a major task to put it to rights by the development team. The author is careful to point out to the reader, that the code featured within for yet to be released PHP features is subject to change without notice as the PHP core is apt to the same changes.

    Some of the new features touched upon include Unicode Semantics, Namespaces, and Late Static Binding. Each is again covered with simple code examples, that show how the implementation of each of the new features works. Note: this is at the time of publication only and changes within the PHP core may affect the language behavior.

    Testing and Documentation

    It is not uncommon for projects of any scale to lack documentation. Its just something somebody else will have to do... Too often this is the case and development is easily out pace the documentation in a fast paced development environment. Even when some attention is given to the documentation it is often sparse and not logically formatted.

    The PHP community has adopted two particular pseudo standards for documentation in the form of PHPDoc and DocBook. Along with a structured documentation environment comes the need for coding conventions. This is the stuff holy wars are made of and the author is quick to tell all 'consistency is king'. Several comparisons are given but still no hard and fast standard exists for PHP, or any other language for that matter. In a PHPRO document on PHP Coding Style examples of various types are also shown that have been with us since K&R first brought the C programming language into being.

    Moving from the controversy to the chapter follows through documentation and coding conventions and introduces "Lexing", which is almost unheard of in most PHP volumes. Possibly a whole topic for a small book itself, the subject is lightly introduced, and possibly more on this subject may follow.

    The PHPDoc section provides the reader with a detailed information on the how and the why of documentation with the PHPDoc tools and covers all the bases for documenting comments and identifiers as shown in this small example.


    <?php

    /**
     * This function adds two string.
     *
     * It does this by taking the first string and
     * adding it to the second string, and
     * then returns the result.
     *
     * @param string $string1 The left string.
     * @param string $string2 The right string.
     * @return string A string containing concatenated inputs.
     * @todo Add a join character parameter.
     */
    function cocattwoString($string1,$string2) {
        return 
    $string1.$string2;
    }

    The coverage of documentation is quite thorough in providing a guide to installation of the tools required to get the documentation tools to work. Then follows examples of use with various applications on various platforms.

    This pattern is again repeated for the DocBook documentation system which uses XML to mark up its docs as this example shows.

    <?xml version="1.0 encoding="UTF-*" ?>
    <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.4//EN"
    "/usr/shar/xml/docbook/schema/dtd/4.4/docbookx.dtd">

    <book>

    <bookinfo>
      <title>Documentation</title>
      <subtitle>Cool Application</subtitle>
    </bookinfo>;

    <chapter>;
      <title>Chapter Title</title>
      <sect1>
        <title>Section title</title>
        <para>Introduction to this section </para>
        <sect2>
          <para>Section may have subsections</para>
        </sect2>
      </sect1>
    </chapter>

    </book>

    What follows from the above example is an in-depth journey into a large and complex system, yet with the examples provided and guiding notes, the mystery of DocBook is laid bare for all. The examples take the DocBook system to "an absurdly complex" level to demonstrate as much of the system as possible.

    Possibly the most important part of the documentation is the the fleeting mention of Reflection. This is important as it leads into the next chapter which covers the Reflection API in depth. The examples lead from the most rudimentary uses to examples of a whole plug-in architecture using Interfaces that were discovered earlier in the book. The chapter culminates with how reflection can be used with the documentation systems previously described.

    Other topics follow to cover Subversion for Version Control (SVN), PHP Unit Testing with PHPUnit, and Deploying applications with Phing. All are covered in detail with examples that leave little room for error on the readers behalf. The detailed nature of the examples and explanations give a clear insight into the authors own development strategies which would seem to be thorough and robust.

    No real Pro PHP book would be complete without an inclusion of Xdebug, that amazing tool written by core PHP developer Derick Rethans. Solid documentation is provide which included remote debugging and code coverage.

    The Standard PHP Library (SPL)

    This subject has drawn some controversy lately, and it is introduced here with fanfare such as "The Standard PHP Library (SPL) is where PHP 5's object-oriented capabilities truly shine.".

    Not an immodest claim by any means. The SPL library was introduced into PHP by Marcus Boerger in PHP 5.1 and has been a mystery to many who have overlooked it or failed to see any benefit from it and fall back on tradition 'PHP 4' style methods of traversing structures.

    Here we see a comprehensive coverage which breaks down the library into its basic six class and builds on each with descriptions, example code, and UML diagrams to provide the reader with a detailed understanding of how the SPL library can be useful, and more importantly, how it operates internally. With this knowledge the reader can build on the examples and interfaces shown.

    The text includes Observer Pattern, the Serializable Iterator, and SPL Autoloading which makes true autoloading possible with PHP. This is remarkable benefit to those who have Opcode cache issues when using require_once and the like. This snippet taken from the book shows how multiple autoload functions may be used to search the include path and autoload a class file which may have an extension of .php .inc .class or .interface.


    <?php

     spl_autoload_register
    (null,false);
     
    spl_autoload_extensions('.php,.inc,.class,.interface');
     function 
    myLoader1($class) {
        
    //Do something to try to load the $class
     
    }

     function 
    myLoader2($class) {
        
    //Maybe load the class from another path
     
    }

     
    spl_autoload_resister('myLoader1',false);
     
    splatted_register('myLoader2',false);
     
    $test = new SomeClass();

    The chapter explores all the available SPL iterators and includes all the new features that came to PHP in version 5.2 such as the mergingIterator and the RegexIterator and the InfiniteIterator . The PHP library provides a lot of functionality and by reading this chapter, a clear understanding can be gained about them and how they may be used within application development with PHP.

    Not only does the SPL chapter provide an insight into the workings of SPL, it also provides some useful real world problem solving techniques that can be implemented in any project of and size. The chapters on SPL take quite a bit time to consume and culminates with the creation of and SPL Shopping Cart which makes use of the SPL ArrayAccess class.

    The section on Objects To Keys is great benefit and little known example of what SPL has hidden within it. By exposing the internals of the iterator interfaces the author provides possibilities to new solutions for many frustrating limitations previously encountered. Here we see a simple example from the book of using objects as array keys.


    <?php

    class KeyOjbect{}

    class 
    CollectionObject implements ArrayAccess {
            protected 
    $_keys$_values;

            public function 
    __construct() {
                    
    $this->_keys = array();
                    
    $this->_values = array();
            }

            public function 
    offsetSet($key$value) {
                    
    $this->_keys[spl_object_hash($key)] = $key;
                    
    $this->_values[spl_object_hash($key)] = $value;
            }

            public function 
    offsetGet($key) {
                    return 
    $this->_values[spl_object_hash($key)];
            }

            public function 
    offsetExists($key) {
                    return 
    array_key_exists(spl_object_hash($key), $this->_values);
            }

            public function 
    offsetUnset($key) {
                    unset(
    $this->_values[spl_object_has($key)])
                    unset(
    $this->_keys[spl_object_hash($key)]);
            }
    }

    $key = new KeyObject();
    $collection = new CollectionObject();
    $collection[$key] = 'test';

    echo 
    $collection[$key];

    Follow this is the SPL Exceptions which builds on the previous chapter on exceptions and adds another dimension to the already comprehensive Exception and SPL libraries.

    Model View Controller

    Probably the most popular, if not most widely known design pattern is the Model View Controller (MVC). This simple yet often mis-used and mis-understood pattern serves a primary goal of logical separation of business logic (Model) and presentation logic (View). It is all strung together with a Controller that is well described here.

    By explaining exactly what MVC does and does not do, the reader is easily taken through the make-up of MVC and how each of the components that make it up work together to provide a simple API for applications which can differ from each implementation, but the basic concepts remain the same.

    It is these concepts which are approached and once again the step-by-step set up of a development environment is laid out. It is this attention to detail that will make this book an essential guide for those new to Object Oriented coding and Design Patterns.

    The internet is now littered with MVC frameworks, each boasting better and faster application development, so it the author has chosen a better known framework with the Zend Framework to illustrate how application development can be made simpler and more efficient by using the MVC design pattern.

    The detailed instructions on how to set up the Zend Frameworks are also included to make sure the environment the user is has matches exactly with the environment of the author. With this in place, the examples flow as with the rest of the book and easy to follow instructions accompany them making for a smooth learning curve on creating Models, Views and Controllers.

    A pleasant surprise is the inclusion of some JSON functionality also which the Zend Framework totally re-implements in PHP code. The inclusion of JSON within the book opens up new possibilities for developers wishing to marry javascript of AJAX with their PHP code.

    What follows is essentially a Zend Framework tutorial but gives the good insight into application development using the MVC architecture. This flows into an Advanced Zend Framework chapter which builds on the previous functionality and adds some of the advanced features inside.

    Web 2.0

    The final section of this tome brings us the buzzword that is most likely paying the bills for us, "Web 2.0". What is it? Where do we find it? How do we make it? Nobody knows, so the author launches directly into the heart of it with a chapter on AJAX and JSON.

    Two methods of JSON use are provided, PECL and Zend Framework. The JSON extension is essential only two functions. json_encode and json_decode. As this snippet form the book shows, it can be as simple as you like.


    <?php

     $original 
    = array('key'=>'value''key2'=>'value2');
     
    $json json_encode($original);
     
    $restored json_decode($jsontrue);

     
    print_r($original);
     print 
    "\n" $json "\n\n";
     
    print_r($restored);

    The examples lead from simple javascript to implementation of XmlHttpRequest (AJAX) methods that leave little room for error if the code is followed as directed.

    A Chapter on SOAP is provided with excellent explanations of terminology used within SOAP services with WSDL. This is crucial for the examples that follow and the author has done well to include these definitions of terms rather than assuming a level of expertise, possibly beyond the range of knowledge of the reader.

    SOAP interfaces can be very simplistic or extremely complex. Both of these scenario's are addressed leaving the reader confident that they can mix it with the best when challenged with web services in a production environment. A Real World Example is provided using the Amazon Web Services API to provide a functional code base to live services. The snippet below from the book demonstrates the Amazon code.


    <?php

     $wsdl 
    "http://webservices.amazon.com/AWSECommerceService/AWSECComerceService.wsdl";

     
    $client = new SoapClient($wsdl);

     
    $namedParameters = array(
       
    'ASWAccessKeyId' => 'YOU_ACCESS_KEY',
       
    'Request'        => array(
                            
    'title' => 'Pro PHP',
                            
    'SearchIntex' => 'Books',
                            
    'ResponseGroup' => 'Small',
                            
    'Publisher' => 'Apress'
                            
    )
       );

      
    $response $client->ItemSearch($namedParameters);
      
    var_dump($response);

    The next chapter moves from the ease of interfacing with the Amazon API and introduces Advanced Web Services with the use of Complex types and creating class maps to reduce your code and on to creating objects to handle SOAP requests.

    A welcome inclusion is that of the binary transmit ion using SOAP which is omitted from all but the most detailed SOAP tutorials. This ability is little known as it is little implemented and provides an indication of the authors depth of knowledge on the subject matter.

    Summary

    This book, as the opening suggests, is not of the PHP newcomer and most surely comes under the banner of "Advanced". It does however, provide those moving into Object Oriented development a comprehensive insight into the workings of PHP and some of the new features that PHP will be providing in the near future. For those already experienced in PHP Object Oriented coding practices there is much to be gained from the authors experience and his ability to provide concise explanations and examples at all levels. When the question is asked "will I gain from reading this?" the answer is a resounding yes. This is a book that can be used to gain knowledge and used later as a reference to material and concepts as they may arise in your own development cycle.

    Purchase

    Buy this book now