Slashdot Mirror


PHP 5 Objects, Patterns and Practice

Daniel Holmes writes "In addition to using PHP to 'just get the job done' for years now, I've been running a humble user group here in the Midwest. As such, I have read numerous books on and around the subject, always looking for something great to inspire my colleagues, group members and myself alike. There are a metric ton of books out there that will walk you through PHP syntax -- this is not one of them. If you are looking for a book on rapidly developing prototype sites, or writing lots of HTML-embedded PHP, just keep looking. But if you have read even one of those books, or just felt like your programming style itself could use a little upgrade, then go get yourself a copy of PHP 5 Objects, Patterns, and Practice by Matt Zandstra." Read on for the rest of Holmes's review. PHP 5 Objects, Patterns and Practice author Matt Zandstra pages 437 publisher Apress rating 10 reviewer Daniel Holmes ISBN 1590593804 summary A powerful tour though PHP 5's object-oriented features; leveraging the power of design patterns and developer best-practices.

For around 40 bucks, you will get a book separated into three main parts, as the title suggests; plus an Introduction, Conclusion and Appendix. However, you also get an amazing level of detail, insight, and plenty of lessons from the (even non-PHP) programming greats. In just over 400 pages I saw hints as well as direct references to some of the best texts in the business: The Pragmatic Programmer, "the GoF", "Enterprise Patterns" and a host more that I will touch on later. The point is: if you have seen true object-oriented development, and have had trouble using these concepts in PHP; don't despair any longer. Matt has done all the work for you--all you need is a weekend or two to do a little reading. Part I - Introduction As you would expect, Part I really sets the stage for the whole book. It points out where the typical state of PHP development is, and (frankly) why we all need to read Matt's book. He does this by telling a great story of a project life cycle gone badly. As many of you know, systems are easy as they are small, but as they grow things often get out of control without proper care and feeding. This section is important as so many good PHP developers don't even know why their code has grown so rapidly out of their control. Don't skip it, even if you know better.

Part II - Objects In Chapter 2, we read the story of the evolution of PHP as a language -- specifically in regards to its object-oriented (OO) constructs. This is nice in that the author presents it in a way so as to not insult the procedural crowd -- something I often struggle with around this topic. Matt's writing style is immediately approachable; he does not come off as the pretentious object-oriented zealot you might expect from the lengthy title.

You also learn that his lessons will take you way beyond just the syntax. Knowing the ins and outs of PHP's oo syntax is not enough: "You must first choose the right participants for your system, and decide the best ways for them to interact." Now that's something you rarely get in a PHP book.

In Chapter 3, we begin to review the new syntax introduced in PHP 5; just to make sure we are all on the same page. One nice feature here is that Matt uses "sidebars" to point out everything that isn't available in PHP 4. This makes it easy to pass over if you are starting with PHP 5, but it also makes the information available for the rest of us.

It is important to note that this chapter gradually and effectively introduces the layers of OO syntax available in PHP 5. Each lesson or feature simply builds on the next. This makes it nice because you can stop, try things out, read some more, etc.

Chapter 4 takes us a little deeper into PHP 5's OO syntax. It is quite helpful that Zandstra breaks up Chapter 3 and Chapter 4. If you are new to OO syntax, the end of Chapter 3 makes a great place to stop and reflect for the night. Seriously, go to bed and let it sink in.

As you can imagine, the "Advanced Features" include concepts such as:
  • Static methods and properties
  • Abstract classes and Interfaces
  • Error handling and Exceptions
  • Final classes and methods
  • Interceptor methods aka "Object overloading"
  • Destructor Methods
  • Object Cloning
  • The magic __toString(): converting objects to strings.


These are not particularly easy topics to master the first time you hear them. However, I think Matt finds a great balance of code and presentation to get the ideas across.

His section on Exceptions alone should be required reading for anyone using PHP 5. Again, not only does he show what they do, he really explains how they will actually help you out.

By the time you get to Chapter 5, you are ready to learn a handful of tips and techniques you can use to keep yourself out of trouble. First off, as PHP is lacking support for true namespaces, Matt shows us the PEAR method of using naming conventions to avoid namespace conflicts. We also learn about using include, require and the new (and possibly controversial) __autoload() function. Of course, there are pitfalls with nearly all of this, and Matt makes sure we know them before we leave the chapter.

Finally he walks us through various reflection techniques. Naturally, starting with simple, function-based reflection. Then taking us through a very complete tour of the new class-based, Reflection API. If you haven't used this, it is a very clean way to expose every nook and cranny of your objects and classes at runtime. Something that can save your sanity in a language that lets you change your API on the fly. Again, it's not just a bunch of talk; there are plenty of great examples to get you there.

By the time you get to Chapter 6, it is time to take another break. Better yet, if this is all new to you stop and play with the code for a bit. Sure you could keep reading, but it will really help if you have the syntax and concepts down so you don't keep flipping back.

Again, Zandstra doesn't just jump straight into design examples; rather, he walks you through why you should even care. Sure, many of us have features in mind and run straight for the finish line ... but this can really get painful on older systems. He even takes a moment to point out one of the biggest traps for developers new to OO. "The presence of classes does not guarantee object-oriented design, even in languages like Java, which forces you to do everything in a class."

The chapter hooks you right away with an example done procedurally and another in OO using appropriate abstract methods. The point is clear: with proper design, you can get away from the Giant If-Else Blocks of Doom and pave the way towards actually keeping up with your client's requests.

Finally, he defines and relates the concepts of Responsibility, Coupling, Cohesion and Orthogonality.

Another great nugget of advice has been planted in this chapter. According to Zandstra, the art of selecting and defining objects "...is far more than just finding the 'things'" in a system. "If you see a class as a noun, a subject for any number of verbs, then you may find it bloating as on going development and requirement changes call for it to do more and more things."

Never before have I seen a simple sentence more completely dispel the inappropriate "object oriented" lessons you may have learned in school. If anything; if you find that it hits too close to home, you will pay attention to what he is about to say!

After telling a story about classes gone badly: "How should we think about defining classes? The best approach is to think of a class as having a primary responsibility, and to make that responsibility as singular and focused as possible. Put the responsibility into words." He continues, referring to the writings of Peter Coad: "If your sentence gets too long, or mired in clauses, it is probably time to consider defining new classes along the lines of some of the responsibilities you have described."

Our tour continues through the basics of polymorphisms and encapsulation. After which, Matt provides us with "four signposts" to help identify problems that can creep into our designs:
  • Code Duplication
  • The Class that knew too much
  • The Jack of All Trades
  • Conditional Statements


For more detail on these tell-tale signs that are probably represented somewhere in your code, go buy the book.

Matt really surprised me in this chapter. After getting us up on all the OO syntax and concept basics, he pulls out the UML. What was so surprising is how easy and approachable he made this introduction. In just a few pages, you learn enough to diagram and interpret inheritance, associations, aggregation and composition, and actually know what all that means. As an added bonus, he even gives a useful introduction to sequence diagrams.

Now, a chapter on UML (or some diagramming set) is usually included in any pattern book. But, this is different from those others. Matt provides s a short, easy to understand introduction to just enough UML to communicate your concepts and processes. A very cool bonus indeed.

Part III - Patterns As Matt says in chapter 1, this book stands on the work of giants. He makes this obvious in parts III and IV. While some may say that he is just repeating what others are saying, I would disagree. The value he adds in basing the patterns in examples you can actually picture writing yourself is worth every delicious page.

After walking us though the why-and-how of how "design patterns" came to be, Matt again makes us actually care about spending the time to learn as many as possible and to use them when it is appropriate. Again, he does a great job of breaking these tough concepts into bite-sized chunks. Don't get me wrong, though; you'll be full after reading the chapters in this section.

I won't go into great detail, but I need to at least provide you with an idea of the patterns you will learn about in this section.

In chapter 8, Matt describes some of the most low-cost, high-return concepts around: composition, decoupling, "patternitis" and the golden rule of OO development -- "Code to an interface, not an implementation."

In chapter 9 he introduces us to some "creational" patterns: The singleton, abstract factory, factory method and prototype.

Chapter 10 focuses on "structural" patterns. The ones he focuses on are the composite, decorator and the facade.

You should note, most of this is PHP written as if we were developing a civ-style, Web-delivered game. This is much easier for "the rest of us" to digest and apply these examples than the GoF's examples of building a large-scale word processor. No disrespect to the bible that is the GoF, but if you have read about design patterns, and still need a little help applying the ideas to your day job, parts III and IV were written for you.

Chapter 11 introduces us to some great task and message management patterns: Interpreter, Visitor, Strategy, Command and Observer.

Finally, Chapter 12 drives us home and provides us with a great look at even more great patterns and explains how they fit into the three tiers of sustainable web development: presentation, business logic and data retrieval and storage.

Presentation
  • Registry
  • Front Controller
  • Application Controller
  • Templates and Template Views
  • Page Controller
Business Logic
  • Transaction Script
  • Domain Model
Data Access and Storage
  • Data Mapper
  • Identity Mapper
  • Unit of Work
  • Lazy Load


Part IV - Practice This is a very important section: like the intro, please don't be tempted to skip it. Matt reminds us while learning code and code design is great, it teaches you nothing about the day-to-day tasks associated with actually keeping the project alive and kicking.

In "Borrowing the Wheel," he shares with us a fantastic piece of advice; one that many PHP developers could stand to listen to:
When this temptation [to reinvent the wheel] comes over me I remind myself of projects past. Although the choice to build from scratch has never killed a project in my experience, I have seen it devour schedules and murder profit margins. There I sit with a manic gleam in my eye, hatching plots and spinning class diagrams, failing to notice as I obsess over the details of my component that the big picture now is a distant memory (p. 294).


Please, take another moment to read that again. If this sounds eerily familiar, please stop reading my review and head strait for your nearest book dealer.

In these chapters we naturally get the (hopefully) obvious hints: use version control, write tests, use PEAR, etc. But, where else will you find all this along with excellent references on actually using PHPUnit2, writing your own PEAR Packages for managing even your own code, actual phpdoc syntax and examples ... not just the act of documenting your code, but using the phpdoc command line tool. And with the section on using cvs, you will have absolutely no excuse but to save your life with some form of version control.

Matt even devotes an entire chapter to managing automated builds with Phing, the PHP equivalent of Apache's ant or C's make.

Most of this information is available in countless forums, articles and websites where you could learn about all of these topics for "free." Or, you could read this section in an afternoon or two and begin amazing your friends and better managing your code right away.

Part V - Conclusions Matt's summary and overview is a great recap of the journey he has put us on. But, on top of that, he outlines some of the essentials that he had to leave out. Here he at least mentions the importance of tools such as bugzilla, mail lists and a wiki for all that other documentation.

Looking at the Bibliography (and all the places he gives credit where credit is due) is like looking at the reading list of nearly every great programmer. You will find books such as: Core J2EE Patterns, Design Patterns (GoF), Extreme Programming Explained, A Pattern Language, Patterns of Enterprise Application Architecture, The Pragmatic Programmer, Refactoring and UML distilled. This is, of course, along with many on-line articles and websites.

Sure, you could spend years reading all of these sources (and some you still should) but unless you get paid to read, do yourself a favor and get some of the best of all of these texts, tailored to you in PHP and delivered in just over 400 pages. My General Impressions

As I mentioned earlier, one of my favorite features of this book is that the examples are "real." This is not some collection of abstract examples like building the next great competitor to Word -- these are website concepts we mere mortals can relate to, such as product catalogs, games, invoices, and the like. You know, the stuff we actually do for a living.

This book does not cover loops, conditionals, functions, operators or any of the non-OO basics of PHP, and believe me, I am grateful. If you would like an introduction to the language of PHP, simply check out php.net or one of the many great introductory books.

I would certainly recommend this book (as if there was any doubt) to any PHP developer. This is especially true for anyone interested in learning more about using objects and classes more appropriately than ever before.

I would also recommend this book to any Java, Ruby or Python developer out there who hears the letters PHP in a sentence and immediately responds with any number of colorful phrases. As we have all read the Pragmatic Programmer by now, we know we can learn something from reading up on any language, and PHP has never been better than it is today.

Finally, I would tell any web application developer who is looking for a quick way to absorb and comprehend the meat of some of the best development and design books ever written.

Read it for yourself and I think you will agree: the desk of nearly every PHP application developer will one day be holding a copy of this book.

Daniel Holmes maintains the PHP User Group in Kansas City since its inception in 2000. He is also the Systems Integration Manager at JCCC in Overland Park, KS. You can purchase PHP 5 Objects, Patterns and Practice from bn.com. Slashdot welcomes readers' book reviews -- to see your own review here, read the book review guidelines, then visit the submission page.

15 of 165 comments (clear)

  1. Seems a lot like... by op12 · · Score: 2, Informative

    the Spring Into PHP 5 book reviewed here earlier recently.

  2. I like... by theotherlight · · Score: 2, Informative

    WROX's Professional PHP 5.

    This book sounds a bit more technical, but I've always loved WROX's style of writing.

    --
    The cat's in the bag and the bag's in the river.
  3. "the GoF"??? by Anonymous Coward · · Score: 4, Informative
    The Gang of Four is not a book. They are four guys who got together to write a book, and an excellent book at that: Design Patterns - Elements of Reusable Object-Oriented Software.

    In no particular order (other then that which appears on the front cover of Design Patterns), the Gang of Four is:
    • Erich Gamma
    • Richard Helm
    • Ralph Johnson
    • John Vlissides
    1. Re:"the GoF"??? by Frymaster · · Score: 2, Informative
      Though PHP4 has a comparatively crappy object sytem

      "comparitively crappy"? while i love php4 for its lightening-fast dev time and embarassingly forgiving syntax, it's oop implementation is far and away the worst i have ever seen.

      php started life as a procedural language, based on the ideology the that primary component of web development was the "page" or even the "session" and that adding another logical component system (the "object") was pointless. the oop capacity of php4 was little more than a gross retrofit. if the language can't enforce private methods, or grok object cloning vs referencing then it's really not useful for oop. in fact, i would go so far as to say php4 is not an oop language, but a procedural language with some oop capabilities.

      now, having said all that, it looks like the cats at zend have made a serious effort to build a meaningful oop language with php5 (i'm especially keen on exceptions) and i applaud them for taking the time to do it right. but i still stand by my initial statement: php4 isn't oop and, for the sake of the children, shouldn't be used that way.

  4. Matt Zandstra has also written some articles... by tcopeland · · Score: 3, Informative

    ...for IBM developerWorks recently; here's his two part series on objects in PHP (part 1 and part 2).

    If you like to write tech articles, I recommend dW; they're a good crew. Some of their tutorials (like my GLib collections tutorial) require registration, but, hey.

  5. a short article from same author by Anonymous Coward · · Score: 2, Informative

    http://www.zend.com/php/design/patterns1.php?print =1

    You can get a taste of his writing skills which are pretty straight forward.

  6. sure, pedant by jbellis · · Score: 2, Informative

    but just about everyone refers to that book as, well, The Gang of Four.

    it's like the Dragon Book, but that's probably before your time.

    sorry to burst your bubble...

  7. Re:Book Review or Book by WiFiBro · · Score: 3, Informative

    I agree, this is a bit too long for a review, it's almost a book, and where's the criticism?
    What do I do with a comment like "a very useful something-to-string-function in chapter X"

  8. Re:Web design and objects by Doctor+O · · Score: 2, Informative

    Of course objects 'stick around between page loads' - just store them in your session and restore them as the first action on the loaded page. If you don't use sessions because you dislike cookies, just configure your PHP to use server-side sessions by default or cast the unholy INI set rune to override the unfavoured default.

    --
    Who is General Failure and why is he reading my hard disk?
  9. For the economically conscious by worf_mo · · Score: 5, Informative

    For around 40 bucks

    This book is also available for $26.39 at amazon.

  10. Patterns by spiffy_dude · · Score: 2, Informative

    I believe every single one of the patterns mentioned above share names with patterns out of the book by Martin Fowler (and company): Patterns of Enterprise Application Architecture. I'm not sure I would be as unqualifyingly kind as the author of this review about regurgitating them. They are great patterns, but is a PHP-ized version of these patterns worth the price when it's such a major part of the book?

  11. Re:PHP vs. RoR? by Philmeeh · · Score: 2, Informative

    You're forgetting that there are far more web hosts providing PHP than Ruby / Ruby On Rails. I am currently learning Ruby and Rails at the moment and did a quick trawl of web hosts forums and in every support forum that asked for possible support for Rails there was just the question "What is Rails?". PHP on the other hand is well known and has a lot of famous applications for it.

    If you have control over your own server environment it could well be worth swapping to Ruby & Rails.

  12. Re:PHP vs. RoR? by ciroknight · · Score: 2, Informative

    First of all, that third-to-last sentence was barely parsable, but I gotcha.

    Secondly, PHP and Perl are like the C and C++ of the web world. They're the oldest and most trustworthy platforms available now, and now since PHP has joined the ranks of full object orientation, it can be a serious competitor to VB/.Net.

    Too many websites, web applications, corporations, banks, etc. rely on PHP for it to just die. Ruby on Rails may be better, but it's very much a niche product, and it will take it a lot of time to gain momentum in the corporate world where competition in this particular market is FEARCE.

    Lastly, I think people will stick with PHP out of familiarity of the programming model. PHP4 felt just like scriptable C except the lack of types, which, frankly, pissed me off at the beginning, but later turned out to feel just right. Ruby on the other hand, reminds me a lot of Scheme/Lisp or Smalltalk, and is kinda foreign and alien to less experienced programmers (but no more foreign than Object C and it's Smalltalk origins, which I have to admit I have fallen in love with over the past year).

    --
    "Victory means exit strategy, and it's important for the President to explain to us what the exit strategy is." G.W.Bush
  13. PHP stood for Personal Home Pages by freezin+fat+guy · · Score: 3, Informative

    PHP's author never envisioned it becoming a mainstream language. It tied into Perl to do its processing and had some massive security holes. There is a surprising amount of hate filled FUD surrounding the language these days (???) but an objective look at the modern PHP language/platform will show it suitable for a broad range of web applications. Perfect? Hardly. But wonderfully pragmatic for most everyday tasks.

    Good design and OO will only help those who have more serious needs. In that vein I would love to see future versions focus on scalability (yes, I do realize that Yahoo runs on it but not without some serious configuration) and perhaps persistance?

    Fortunately there's lots of great development tools and when PHP fits, I say use it.

  14. I've been considering the same thing... by TheInternet · · Score: 2, Informative

    At this point if I were just starting out in Web development, wouldn't I want to invest in learning Ruby on Rails instead of PHP?

    I've been thinking about this too, but PHP seems to win hands down in the deployment category. It looks like a lot of Rails apps use lighttpd, but a lot of people are very happy with Apache.

    You can use mod_ruby, but this gets tricky with multiple applications on the same server instance. The "preferred" deployment method seems to be FastCGI, but this seems like a strange option to me. I worked with FastCGI at a 4 million+ member site, and we were happy when we were able to leave FastCGI behind. It ate up gobs of resources. Maybe things have changed since then?

    Another area that's a bit more grey is syntax. Ruby has all sorts of special syntax, some of which is quite clever, but one person's "clever" is another's person "bizarre." Probably not quite as vexing as Perl, though. For better or worse, PHP doesn't have much special syntax. Personally, I think this is good.

    Finally, I've found PHP to be unbelievably fast. There's been dozens of instances where I was sure I'd have to spend time optimizing an application, but was proven wrong. Your mileage may vary, of course.

    There's a lot that Rails does right, but I'm not yet convinced it's the only reasonable optional for medium-sized apps. Of course, this gets a bit muddle because we're really comparing a framework to a language.

    --
    Scott Stevenson
    Tree House Ideas