A review of "Learning PHP Data Objects"

4th May 2008

packt_learning_pdo.png

Packt Publishing recently sent me a couple of books to review. This post is about the second one I received, Learning PHP Data Objects by Dennis Popel. I was excited to receive this book as PDO underlies a lot of the Zend_Db_Adapter objects that I use in my day to day programming. It seemed like a good idea that I should know more about it.

Overview of the book

This book starts out introducing PDO and then takes us on a tour through all its features including error handling and prepared statements along with more advanced features like scrollable cursors.

The first chapter introduces PDO and shows the basics of how to use it to connect to a database, issue a query and retrieve the resultant data. The author also makes the distinction about how the code he is showing is example code and provides pointers to what's missing (such as proper error messages) if you were to use the code in production. I liked this very much as it's important as authors that we realise that inexperienced readers have a tendency to copy/paste examples and use as-is. The introductory chapter closes with a look at prepared statements and so covers all the high points of PDO.

Having introduced the subject, chapter 2 looks in detail at using PDO to connect to a database. This chapter is more tutorial-ish and the code is presented to be typed in. A worked example of a book database is used from here on throughout the rest of the book. The author appears to expect the user to learn what the code does by reading the comments within the code body, as there is little explanation of what the code does in the prose. One thing that's tricky is that when there is explanation after a code block, it's hard to work out which bit of the block the author is referring to. On the whole though, the tutorial nature provides step-by-step progress for people who learn best that way.

Chapter 3 covers error handling. I was pleased to see this important topic given an entire chapter and so early in the book. Error handling is not an after thought here. This chapter provides a good discussion of the types of errors that you will encounter and then provides instructions on how to handle them. Again, the tutorial aspect of the book is emphasised with lots of code to type in. Some of it is in bold, but I'm not sure why as no reference is made to it in the prose. This chapter also starts a dangerous trend where four pages of code is presented (without line numbers) and then the following page or so dissects the code with reference to line numbers that do not exist! This makes the explanation of the code really hard to follow, especially when the you get to the section about lines 189 to 191... This chapter also continues the tutorial by building more pages and showing you how to check for errors along the way.

Chapter 4 studies prepared statements and shows how to use them. Positional and named placeholders are looked at, along with how to insert blobs using bound parameters. In this chapter, the bold sections in the code make more sense as they are referenced in the prose. Again, we have pages of code with no line numbers and then are asked to study lines 60 to 73. The information in this chapter is nevertheless very good and I learnt stuff :)

Having looked at getting data into the application, chapter 5 looks at retrieval and rowsets. This chapter covers counting the number of rows returned and limiting rowsets. It's much shorter as it covers less topics and I'm glad the author didn't pad the chapter just to get the page count up! Chapter 6 is also relatively short, but this time covers a lot of ground. These are advanced topics and include connection attributes, buffered queries, dsn files for connections and transactions. The transactions section gets the most space and is covered quite less, though with rather less prose for the volume of code than I would have liked.

The last chapter in the book is a bit of an odd ball as it looks as designing a model within an MVC application. To me this didn't fit with the specialist PDO nature of the book, and I'd have rather have had more space devoted to transactions or database specific issues.

In summary

This book is an good, detailed tutorial for understanding PDO. It is not a reference book and so relatively hard to dip into to look up a specific thing. If you learn by starting from scratch and working your way through, then this is a very good book. The biggest distraction for me was the long code listings. It would have been better to have either put in line numbers or interspersed the code with the textual explanations.

A review of "Object-Oriented Programming with PHP5"

4th May 2008

packt_oop_with_php5.png
Packt Publishing recently sent me a couple of books to review, so let's start with Object-Oriented Programming with PHP5 by Hasin Hayder. According to the introduction, the book is intended for beginners to intermediate PHP5 programmers and the first chapter has a good introduction to what object oriented programming is and why you would want to use it.

Overview of the book

Chapters two and three of the book are an excellent discussion of how objects work in PHP and cover everything from the use of $this through to object cloning and fluent interfaces. Chapter 4 gives a basic introduction to design patterns, however I feel that it covers too many patterns in not enough detail. It does provide the terminology required though for communicating with other developers about design patterns which will also help when searching the web for more information.

Chapter 5 then introduces reflection and unit testing. This is an odd couple to put together and the entire chapter feels like the author was padding. There are long pages of code with very little explanation of what the code does and no example of real-world usage of the Reflection classes. The unit testing half provides a good introduction to unit testing and shows how to use it. Rather oddly, there's a 10 page table listing all the PHPUnit assert functions which would have been better left to the PHPUnit documentation as the table provides no added value.

Chapter 6 introduces the SPL. Like the design patterns chapter, it covers a lot of objects in relatively shallow depth. Good code examples are provided to show how to use the SPL objects, but again, there's not really enough textual explanation of the code or discussion of real-world usage. Similarly, chapter 7 covers object oriented database access with MySQLi, PDO, ADOdb and MDB2. It finishes up with a couple of pages ADOdb's ActiveRecord object. It's all a bit rushed.

XML is introduced in chapter 8 with SimpleXML and DOM are looked at. Again, a very basic introduction is provided. For example XPath is covered in 3 pages and I still have no idea how to actually use it in a project. The final chapter in the book covers the MVC design pattern as implemented in the author's home-grown framework. As with the rest of the book, a lot of code is presented with little explanation of why the code has been written. For example, the view class presented provides __get(), but not __set(). There is no explanation as to why __get() would be required in a view class, but not __set().

In summary

This book is a whistle-stop tour through object oriented concepts with PHP5 and I'm left with mixed feelings about it. The best parts are chapters 2 and 3 which provide a solid introduction to objects and classes. The rest of the book covers too many disparate topics in very little depth to be useable on its own for those topics.

PHP London 08

2nd March 2008

The PHP UK Conference in London is over for another year and this year's event was another evolutionary improvement on last year's. It was held in Inmarsat's conference facilities in the City of London. There were two conference rooms in use: a 300 seat main auditorium and a smaller 75 seat second room. There were also a large social area for food, drinks and networking. I thought it worked really well, kudos to Paul Morgan and the rest of PHPLondon for the organisation.

Lunch!
Lunch!

The day kicked off with a talk by Ivo Jansch on "Enterprise PHP". Ivo is an engaging speaker and talked about designing and building PHP applications with a more structured approach for long term benefits. After the break, the conference split into two tracks with Scott MacVicar & Mike Sullivan talking about their development experiences and Stefan Esser talking about security. I have to admit that I missed both these talks as I was talking too much with Lorna and Kathryn at the PHPWomen stand. I've been "talking" with Lorna on IRC and via blogs for a little while now, and it was great to meet her in person along with Kevin, her better half. They had t-shirts which were snapped up and I got one of the last ones and it wasn't even lunchtime. (I hope my donation at least covered its cost!) Here's a picture Dave the codemonkey and an elePHPant wearing a phpwomen t-shirt:

phpwomen t-shirts
PHPWomen t-shirts

Lunch was excellent too (Beef Stroganof for me) and I caught up with the PHP West Midlands people. We have a meeting in couple of weeks on 11th March, by the way. After lunch Marcus Bointon talked about mail whilst Scott MacVicar talked about SQLite3. Again, I managed to miss this slot, but I understand that both were well received and covered their subject well. The next slot in the main room was the Frameworks comparison with Ian Christian (Symfony), Toby Beresford (CodeIgniter) and myself (Zend Framework). We each had 20 minutes to present a bit about our framework and then there was a Q&A session afterwards. I thought it went okay. I was very nervous whilst speaking and so talked too fast. Fortunately, I had enough slides to cover and finished at the 20 minute mark. Ian and Toby gave very different talks but both covered their respective frameworks strengths. I thought that the Q&A went well and none of us embarrassed ourselves which was nice!

Whilst we were speaking, Zoe Slattery gave a talk on testing PHP and then Anthony Phillips talked about IBM's Project Zero. I wanted to see both of these, so I'm looking forward to the MP3s that the conference will be providing. The conference was wrapped up by Derick Rethans who talked about how PHP and usage of PHP has changed since he first started working with the language. It was funny and informative and it was interesting that pretty much all the questions afterwards were on testing.

All in all it was a great conference and I'm looking forward to next year's.

Code cleanliness guidelines from Etienne Kneuss

18th January 2008

I don't often post links to articles I read via my RSS reader as I assume that most people who read this blog also read sites like Planet PHP, PHP Developer or DevZone.

Having said that, Etienne Kneuss has posted an article aimed at less experienced PHP programmers providing some quick guidelines to code cleanliness which are actually a very good reminder to us all.

New Zend Framework Blog/Website

3rd January 2008

I thought I'd start a new website to talk about all things Zend Framework, so I'm introducing www.zendframeworkbook.com to the world.

The intention is to highlight interesting things that I see on the Zend Framework mailing lists and also to talk about book stuff periodically as well.

Obviously, if you follow the ZF mailing lists religiously, then you may find that you recognise the content of a lot of the posts, but if not, then it may turn into a useful summary of some of the main issues that are happening in Zend Framework land.

Where to set up your view?

9th December 2007

With Zend_Layout on the horizon, I've been looking at how to use it and it will remove the need for my own front controller plugin which I call SiteTemplate. As a result, I need to find a new home for the view customisation stuff I do in SiteTemplate.

My current plan is to create a new front controller plugin called ViewSetup (for want of a better name!) that contains just the view setup stuff from

<?php
require_once 'Zend/Controller/Plugin/Abstract.php';

/**
 * Front Controller plug in to set up the view with the Akra view helper
 * path and some useful request variables.
 *
 */
class Akra_Controller_Plugin_ViewSetup extends Zend_Controller_Plugin_Abstract
{    
    public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
    {
        $viewRenderer Zend_Controller_Action_HelperBroker::getStaticHelper('viewRenderer');
        $viewRenderer->setView(new Akra_View());

        // add helper path to View/Helper directory within this library
        $prefix 'Akra_View_Helper';
        $dir dirname(__FILE__) . '/../../View/Helper';
        $viewRenderer->view->addHelperPath($dir$prefix);
    
        // set up variables that the view may want to know    
        $viewRenderer->view->baseUrl $request->getBaseUrl();
        $viewRenderer->view->module $request->getModuleName();
        $viewRenderer->view->controller $request->getControllerName();
        $viewRenderer->view->action $request->getActionName();
        $viewRenderer->view->theme $request->getParam('theme''default');
    }
}

(I'll talk about how cool Akra_View is another time...)

I had a dig into Zend_Layout's source and it collects its view object from the view renderer too, so this works as expected. (*phew*!)

The alternative, as I see it is to put the view creation into my bootstrap and then create a series of view helpers like this one for the base url:

<?php

class Places_View_Helper_BaseUrl
{
    protected $_baseUrl;
    
    function __construct()
    {
        $fc Zend_Controller_Front::getInstance();
        $request $fc->getRequest();
        $this->_baseUrl =  $request->getBaseUrl();
    }
    
    function baseUrl()
    {
        return $this->_baseUrl;
    }
}

How does everyone else do it? Is the bootstrap + many view helpers approach a better one than using a front controller plugin? Have I missed a completely obvious better solution?

Back to zero bugs

27th November 2007

I've just finished going through the open Zend_Config issues and fixing them all. Nothing major, but a couple of nice fixes and one new function.

The bugs recently fixed are:

  • ZF-2209 Zend_Config* contructor should have the section defaults to null
  • ZF-2162 Zend_Config_Xml usage without sections bug
  • ZF-2021 Zend_Config::toArray() does not support generic object values

Lastly, I've added a new function called setReadOnly() in response to issue ZF-2061. This allows you to lock down a Zend_Config object after merging it with another one. For example:


$defaultConf = new Zend_Config($default_conf_arraytrue); // allow modifications so we can merge
$userConf = new Zend_Config($user_conf_array);
$defaultConf->merge($userConf);

$defaultConf now contains the merged data, but is still open for modifications, so could be modified at any time. This is not good. setReadOnly() will turn off the modifications flag like this:


$defaultConf->setReadOnly()

Not a big addition, but very nice, nevertheless!

PHPAbstract

25th October 2007

If you read DevZone, then you'll notice that Cal's looking for some PHP Abstract advertising.

I'm always up for free books, so there's my link Cal! (Though I doubt that technorati picks up my little blog!)

More seriously, PHPAbstract is worth listening to. Unusually for a podcast, each episode is short (around 10 mins) so that I actually get to listen to a whole episode without being distracted. They have episodes by many (lots?) well known PHP luminaries about a variety of PHP related topics. I've listened to every one (except #16) and PHPAbstract is one of only 4 podcasts I actually subscribe to in iTunes. (Where's the iTunes button on the PHPAbstract page then Cal?)

Advert over - back to writing about the Zend Framework!

(This post probably has more links than any other on this site!)

Life outside of PHP

22nd October 2007

I thought that I'd answer Davey's question: what do you do to get away from PHP?. I also enjoy seeing the non-PHP side of people on Twitter, though I'm tending to use Twitter as a micro-blogging tool more at the moment.

I enjoy spending my "non-PHP" time with my family. We are members of the National Trust as it gives us cheap access to land where the boys can run around freely. We also go camping for our holidays, though like to do it in a little bit of comfort.

I also enjoy photography, though still have a long way to go to being more than "proficient" at it. Looking through my Flickr stream, and it is also obvious that I like old trains - mainly as a photographic subject. There's something about the pent up power in the old steam trains, that just isn't there in the modern people transporters we have nowadays. I'll photograph anything really as I haven't really discovered what I'm good at!

Another thing I'm doing is writing a book, of course! I love reading fiction - anything really, from Bernard Cornwall to Peter Hamilton via Terry Pratchett. I also read "technical" books to keep my brain sharp and to keep on learning.

So what about you? Answers on a postcard and make sure you let Davey know too!

View Helper Case Notes

17th September 2007

This is how it works:

views/helpers/MyHelper.php contains class Zend_View_Helper_MyHelper which has a function called myHelper()

Also, if you add a function called setView() to your class, then the View will pass you an instance of itself before it calls your view helper function.

i.e.


Class Zend_View_Helper_MyHelper
{
    protected $_view;
    
    public function setView($view)
    {
        $this->_view $view;
    }

    public function myHelper($myVar)
    {
         return $this->_view->escape($myVar);
    }

}