PHP 5 Objects, Patterns, and Practice

Matt Zandstra

Mentioned 14

PHP 5's object-oriented enhancements are among the most significant improvements in the 10+ year history of the language. This book introduces you to those features and the many opportunities they provide, as well as a number of tools that will help you maximize development efforts. The book begins with a broad overview of PHP 5's object-oriented features, introducing key topics like class declaration, object instantiation, inheritance, and method and property encapsulation. You’ll also learn about advanced topics including static methods and properties, abstract classes, interfaces, exception handling, object cloning, and more. You’ll also benefit from an extensive discussion regarding object-oriented design best practices. The next part of the book is devoted to a topic that is often a natural extension of any object-oriented introduction: design patterns. PHP 5 is particularly well-suited to the deployment of these solutions for commonly occurring programming problems. The author will introduce pattern concepts and show you how to implement several key patterns in your PHP applications. The last segment introduces a number of great utilities that help you document, manage, test, and build your PHP applications, including Phing, PHPUnit2, phpDocumentor, PEAR, and CVS.

More on Amazon.com

Mentioned in questions and answers.

I'm a PHPer, and am not writing object-oriented code.

What are the advantages of OO over procedural code, and where can I learn how to apply these ideas to PHP?

I am a PHP aswell, although I do have a strong OOP background, I would say the best book on using OOP with PHP has to be PHP 5 Objects Patterns and Practice

I've noticed a lot of jobs in my area for PHP. I've never used PHP before, and figure if I can get more opportunities if I pick it up then it might be a good idea. The problem is that PHP without any framework is ugly and 99% of the time really bad code. All the tutorials and books I've seen are really lousy - it never shows any kind of good programming practice but always the quick and dirty kind of way of doing things. I'm afraid that trying to learn PHP this way will just imprint these bad practices in my head and make me waste time later trying to unlearn them. I've used C# in the past so I'm familiar with OOP and software design patterns and similar.

Should I be trying to learn PHP by using one of the better known frameworks for it? I've looked at CakePHP, Symfony and the Zend Framework so far; Zend seems to be the most flexible without being too constraining like Cake and Symfony (although Symfony seemed less constraining than CakePHP which is trying too hard to be Ruby on Rails), but many tutorials for Zend I've seen assume you already know PHP and want to learn to use the framework.

What would be my best opportunity for learning PHP, but learning GOOD PHP that uses real software engineering techniques instead of spaghetti code? It seems all the PHP books and resources either assume you are just using raw PHP and therefore showcase bade practices, or that you already know PHP and therefore don't even touch on parts of the language.

Getting started

If you are trying to learn PHP(no PHP experience) I guess you should first pick up an easy framework like Codeigniter. When watching there screencast you will find out the with Codeigniter you can create a simple blog in 20 minutes. I don't think you can code something like this with just plain PHP because codeigniter allready has the following solid foundation:

  • MVC: In my opinion this helps you to write cleanly separated code.

    MVC is a software approach that separates application logic from presentation. In practice, it permits your web pages to contain minimal scripting since the presentation is separate from the PHP scripting.

  • Database: This module helps you with a lot your database pain.

    CodeIgniter comes with a full-featured and very fast abstracted database class that supports both traditional structures and Active Record patterns. The database functions offer clear, simple syntax.

  • Easy: codeigniter is really easy to pick up which is a huge plus.

    CodeIgniter is installed in four steps:

    1. Unzip the package.
    2. Upload the CodeIgniter folders and files to your server. Normally the index.php file will be at your root.
    3. Open the application/config/config.php file with a text editor and set your base URL. If you intend to use encryption or sessions, set your encryption key.
    4. If you intend to use a database, open the application/config/database.php file with a text editor and set your database settings.
  • Fast: Rasmus(PHP inventor) did benchmark a lot of the PHP frameworks(slides 24-32) out there and as you can see Codeigniter performs good compared to some other framweworks. Also I would like to notice that mosts slides from http://talks.php.net/ are really good.

Learning PHP

In the past I stumbled upon Matt Zandstra's PHP book which is really good and I think you should read it to learn PHP properly.

PHP "best" practices:

"Clean" code:

  • Learn Recess PHP framework. I also really liked this framework. It will help you create rest-like applications.
  • Learn TDD/PHPunit to properly test your code.
  • Learn MVC.
  • Learn OOP.

Performance:

  • APC: If it all possible you should really install apc to speed up php. It will store the PHP opcode in memory(huge, huge boost).
  • Memcached: When your database is under heavy load you also need to store your query's in memory.

Good luck!

I've started to learn OO programming, but using the PHP language with the help of the "PHP 5 Objects, Patterns, and Practice" book. The thing is that I wish to learn to use into same time the CakePHP framework which make use a lot of the MVC pattern. Because I don't know much about OO and less about MVC I wish to understand the later one but assumptions I make with my OO knowledges might have bad impact on long term.

Does anyone know a good tutorial about what means MVC (more than cakephp manual says about it, but more easy to read/understand than wikipedia)?

TY

Here is an excellent PHP MVC tutorial on phpro.org to get you started.. I had trouble with MVC design pattern too but after reading this tutorial, I learned so much that I went on creating my own PHP MVC framework. (and yes I have re-invented the wheel but guess what, I learned a looooot and that was my primary reason).

Although you are already reading a book related to PHP OOP but yet I would recommend you going this great OOP tutorial at phpfreak

Possible Duplicate:
Book recommendation for learning good PHP OOP?

I need to learn more before jumping down the rabbit hole, know of any good books please tell me.

Thanks.

My favourite book on OOP for PHP, very good!

http://www.amazon.co.uk/PHP-5-Objects-Patterns-Practice/dp/1590593804

Head first PHP and Mysql is decent. The head first books are always pretty easy to read, they are not a reference manual but are not horribly boring.

http://www.amazon.com/Head-First-MySQL-Lynn-Beighley/dp/0596006306/ref=sr_1_1?ie=UTF8&qid=1302872116&sr=8-1

I recommend Object-Oriented PHP: Concepts, Techniques, and Code, it is easy to flow, learn and have real world examples using OOP of course.

I am kind of a slow learner I guess when it comes to coding, I have been learning PHP for a couple of years and I still don't understand Classes so it's time I put some effort in to at least understanding them a little better.

I use functions for everything. People often make comments to me on here that they can't believe I have a social network site and I don't use classes.

I really do not understand the benefit of them can you explain the benefits besides it supposedly being easiar for multiple people to work on your code?

To me it seems like classes just complicate simple task

Simply (in fact, extremely simply), classes allow you to organize code in logical units as well as provide containers and templates for user-created objects.

Let's say you have a car... A car can has a capacity and people inside.

class Car {
    private $people = array();
    private $capacity;

    function __construct($capacity) { $this->capacity = $capacity; }

    function addPerson($name) {
        if(count($this->people) >= $this->capacity) {
            throw new Exception("Car is already at capacity");
        } else {
            $this->people[] = $name;
        }
    }
    function getPeople() { return $this->people; }
    function getCapacity() { return $this->capacity; }
}

Now, we can start using those cars:

$aliceCar = new Car(2);
$aliceCar->addPerson("Alice");

$bobCar = new Car(4);
$bobCar->addPerson("Bob");
$bobCar->addPerson("Jake");

I now have 2 cars (instances), which holds different data.

echo implode(',', $aliceCar->getPeople()); // Alice
echo $aliceCar->getCapacity(); // 2

echo implode(',', $bobCar->getPeople()); // Bob,Jake
echo $bobCar->getCapacity(); // 4

I might also want to have a van, which will have an additional property for doors:

class Van extends Car {
    private $num_doors;

    function __construct($capacity, $num_doors) {
        parent::__construct($capacity); // Call the parent constructor
        $this->num_doors = $num_doors;
    }

    function getNumDoors() { return $this->num_doors; }
}

Now let's use that van:

$jakeVan = new Van(7, 5);

// Van is ALSO a Car
$jakeVan->addPerson("Ron"); //Jake is with Bob now, so his son is driving the Van
$jakeVan->addPerson("Valery") //Ron's girlfriend

echo implode(',', $jakeVan->getPeople()); // Ron,Valery
echo $jakeVan->getCapacity(); // 7
echo $jakeVan->getNumDoors(); // 5

Now maybe you can see how we could apply those concepts towards the creation of, for example, a DBTable and a User class.


In fact, it's hard to really start explaining why classes simplify one's life without getting into the concepts of Object Oriented Programming (abstraction, encapsulation, inheritance, polymorphism).

I recommend you read the following book. It will help you grasp the core concepts of OOP and help you understand why objects to really make your life easier. Without an understanding of those concepts, it's easy to dismiss classes as just another complication.

PHP 5 Objects, Patterns, and Practice

PHP 5 Objects, Patterns, and Practice

Available at Amazon.com

Basically I want the books to be text book based, ie, author discusses the background,philosophy,syntax,semtantix for every language AND after every section there are questions what you learned so far and mini projects. Is there any books like this, I'm absolutely new to php/mysql/javascript and web development in general. Thanks in advance.

Not single book

I know you asked for only book explaining introducing PHP/MySQL/Javascript. I am sorry I don't know one book for this. But what I have read/skimmed which I liked was the following.

PHP

I myself really enjoyed reading Matt zandstra's PHP 5 Objects, Patterns, and Practice. I think it is really a good book to learn good Object Oriented Programming. It directly learns you have to code good PHP instead of just picking up "an introduction to PHP" book which teaches you bad coding practices which will bite you later. I think this book isn't really for the beginners, but with a little bit of focus you could read this book.

Javascript

My advise would be to read Douglas Crockford's javascript the good parts. This book explains what part of javascript you should use because they are good and which parts are best to avoid because they aren't that good.

MySQL

I think you should learn the basics about PDO(PHP Data Objects) reading Dennis Popl's Learning PHP Data Objects.

Whats the best way to go about many-to-many relationships in object-oriented PHP.

If I have three tables, books and categories and the join table bookscategories (handles many to many), should I create a model/class called bookcategories and handle everything to do with the book-category relationship there?

My specific questions with reference to the psuedo code below are:

  1. Have I correctly assigned the methods to the appropriate classes?
  2. Is there a better way to achieve this that isn't very complex?
  3. In which class does one handle the linking relationship? e.g. $book->link_to_cat('5')?
  4. Any caveats for using this approach (if applicable).

Any advice is highly appreciated! Thanks in advance!

Pseudo Code:

<?php

class Books {
    //handles all book table stuff

    public function delete_book() {
        //deletes specific book
        //deletes all related bookcategories using find_by_book_id
    }
}

class Categories {
    // handles all category stuff
}

class BookCategories {

    public static function get_cats_by_book_id {
        // sql join statement to retrieve category objects by book id
    }

    public static function get_books_by_cat_id {

    }

    public static function find_by_book_id() {
        //returns bookcategories by book id.
    }
}


?>

You might find investigating design patterns helpful. The composite pattern is often used in this situation. A good book to help you with design patterns with php oo is Matt Zandstra's PHP Objects, Patterns and Practice

i have been using PHP for quite a sometime now, having understood the concept of OOPS, PDO, etc. i have been slowly moving forward to more advanced PHP. my strategy is always to learn more and more advance programming in every project. for my current project i would like to implement MVC, as i have been implementing my own directory or application structure before, this time i want to use MVC for my application. i did went through a MVC boilerplate tutorial on Nettuts. however that was just the basic i am searching for more and more resources for me to help get started with MVC for my projects. i am sure you guys might have passed from the same path i would like to know the links and suggestion about some of the great MVC tutorial for PHP available in the internet.

EDIT :

I have used frameworks like cakephp before i would request not to suggest using of any framework.

thank you

I strongly suggest you to take a look into Kohana framework. Its an HMVC framework, with cascading directory structure. If you are looking for books on advanced topics, "PHP Objects, Patterns, and Practice" by Matt Zandstra describes very well about Design patterns in PHP. "Pro PHP Patterns, Frameworks, Testing and More" is also an excellent book which discuss about many advanced topics.

Iv been trying to get my head around object orientation and I think iv started to get some of the concepts, but im not sure. Making a google search that answers if my train of thought is correct proved to be quite hard so I decided to ask here really quick, please tell me if the question is against any rules.

Im I thinking correctly in regards to messagepassing? What are the obviously bad things? How should I think while going forward with my learning? Like getpagecontent($page, $connection); etc

Atm im reading [Oreilly - Learning php and mysql][1] and [Programming in an Object-Oriented Environment][2] And some books on UML

Here is the code.

dbfunctions.php

<?php
class dbconnect {

    function dbconnect() {
    $this->dbhost = 'xx';
    $this->dbuser = 'xx';
    $this->dbpass = 'xx';
    $this->dbdatabase = 'xx';
    }

    function createdbconnection() {
        require_once('DB.php'); // pear

        $this->connection = DB::connect("mysql://$this->dbuser:$this->dbpass@$this->dbhost/$this->dbdatabase");

        if (DB::isError($this->connection)) {
        die("Could not connect (connection)<br>" . DB::errorMessage($this->connection));
        }
    }

    function closedbconnection(){
        $this->connection->disconnect();
    }
}

class dbinteractions {

   function dbinteractions($connection) {
            $this->connection = $connection;
        }

   function searchdb($qstring) {
    if (get_magic_quotes_gpc()) {
        $qstring = stripslashes($qstring);
    }

    $qstring = mysql_real_escape_string($qstring);

    $query = "SELECT content FROM site_content WHERE content LIKE '%$qstring%'";
    $result = $this->connection->query($query);

    if(DB::isError($result)) {
        die("Could not connect (query)<br>" . DB::errorMessage($result));
    }

    while($result_row = $result->fetchRow()) {
        echo("<h2>Resultat:</h2>");
        foreach($result_row as $out)
            echo($out . "<p>");
    }
}

    function getpagecontent($page) {
        $query = "SELECT * FROM site_content WHERE (page_id = \"" . $page . "\")";
        $result = $this->connection->query($query);;

        while($result_row = $result->fetchRow()) {
            echo "<h1>" . $result_row[0] . "</h1>"; //Echo page_id
            echo $result_row[1]; //Echo content
            echo "<h2>" . $result_row[2] . "</h2>"; //Echo timestamp
        }
    }

}
?>

search.php

<?php
function displaysearchform()
{
    echo("<p></p>");
    if($_GET["search"] == '') { //Display search box if no search ?>

        <form method="GET" action="<?php echo(htmlentities($_SERVER['PHP_SELF'])); ?>">
            <label>
                Search: <input type="text" name="search" />
            </label>
            <input type="submit" value="Go!">
        </form>

    <?php
        return false;
    }
    else
    {
        return true;
    }
}

?>

index.php

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<link rel="stylesheet" href="style.css" type="text/css">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title></title>
</head>
<body>
    <div id="container">
        <div id="sidebar">
            <a href="?id=1">1</a><br>
            <a href="?id=2">2</a><br>
        </div>
        <div id="main">

            <?php
                include("dbfunctions.php");
                include("search.php");

                $dbconnect = new dbconnect();

                $dbconnect->createdbconnection();

                $dbinteractions = new dbinteractions($dbconnect->connection);

                if(!$_GET["id"] && $_GET["search"] == "") { //Check if direct site hit and no search query
                    $dbinteractions->getpagecontent("1");
                    }

                else  {
                    $page = $_GET["id"];
                    $dbinteractions->getpagecontent($page); //Get and display page content
                }

                if (displaysearchform() == true){ //If search was made don't display searchform
                    $dbinteractions->searchdb($_GET["search"]);
                }

                $dbconnect->closedbconnection(); //Close connection to db
            ?>
        </div>
    </div>
</body>
</html>

You only have one thing right with OO. The $connection object.

Everything else is procedural. You should start by creating a class, instead of all those loose functions in "dbfunctions.php".

Also note that you should avoid mixing logic code with HTML. It gets hard to maintain.

Here's probably the best book you can read on the subject .

It's not easy to get into object oriented paradigm. But when you get it, it's like riding a bicycle. You never forget.

I want to know more about OOP in PHP 5.2.

Can anybody help me with a link to advanced OOP tutorials in PHP?

I know about static, public and private class member attributes, but I need more info about basic and advanced OO techniques. I hope somebody can help. :)

In order to first understand OOP with PHP, you must understand the core concepts behind OOP. Tutorials won't help you correctly grasps things like abstraction, inheritance, encapsulation, and polymorphism.

Grab a book about Object Oriented Programming, that is the best way to learn. One of my favorites is:

Design Patterns: Elements of Reusable Object-Oriented Software

Design Patterns: Elements of Reusable Object-Oriented Software

If you want something more PHP oriented, I heard nothing but good things about:

PHP 5 Objects, Patterns, and Practice

PHP 5 Objects, Patterns, and Practice

Both are available at Amazon.com

I don't understand why so many young/new programmers have a total aversion for books when they start learning.

Over the last 18 months i have been hard at work teaching myself PHP & Jquery and so far have become quite good at it but not having a "mentor" i have developed my own "model" for building webapps / sites. it goes like this...

I have my front end page (HTML) and a js script which i fill with lots of jquery ajax (using a get or post method then pass on a command to the php) commands which in turn reference a sometimes large php file made up almost entirley of one big "switch / case" command with all my various options.

my question is this, is there a better way to do this?

i want to advance in my skills, where should i take my model next?

To put it simply: start learning the pros and cons of the various programming patterns. Sounds like you're doing Front Controller, which is fine for simple, one-off projects. The GoF book, Design Patterns, is supposed to be really good. A friend of mine really likes the Head First version...

In your case I would make the switch to Object Oriented Programming. I've been in a similar situation like you but wasn't satisfied anymore at how my websites looked with simple procedural scripting. Switching to OOP will take quite some time to get used to, but in my opinion it was all well worth the effort.

Take your time learning OOP. First, check http://www.php.net/ to learn about objects and classes and afterwards read a book on the subject (Php Objects, Patterns And Practice by Matt Zandstra is a very good one http://www.amazon.com/PHP-5-Objects-Patterns-Practice/dp/1590593804). You will find out why a lot of people have made a switch to the OOP approach for web apps.

When you are used to the way of thinking in OOP, choose a framework. It doesn't make sense to write code for things that have been written 100 times before and are tried and tested approaches to common problems. A framework covers all the basic annoying stuff you shouldn't be spending your precious time on. But only choose a framework when you have really grasped the way of thinking with OOP. It's always best to learn the basics first instead of jumping right in the middle by directly choosing a framework.

Possible Duplicate:
Which is the best book to learn and implement Design Patterns using C#?

I want my application to be well planned and designed and it seems interviewers are much interested in design also now a days :) . So thought , I will ask the community , what really helped them to be quite clear in the concepts behind. which books will really help me to understand design patterns better.

I would love to decide for a book mostly suggested

I also loved this one: http://www.amazon.com/PHP-5-Objects-Patterns-Practice/dp/1590593804

It's PHP-specific, though :)

I'm developing several web sites in Kohana using its template system so that one code base is running several web sites using the same back end DB. I'm starting to see a lot of if statements in the views to say if this site do this, if that site do that. It starting to look very non-MVC or Object Oriented. Do other developers have any rules they follow when deciding to breakout view into separate partial views? I want to reuse as much of the code as possible but not swim in if statement in every view. Any reference would be great also.

If you are using Kohana, you should use modules for stuff you don't want to duplicate for every application. Then you can keep specifics in your application with extended classes or specific settings in config files.

http://kohanaframework.org/3.2/guide/kohana/modules

A lot of if statements are mostly an indication that you need to do refactoring. A large cascading if statement to allow for different sites to be loaded is bad practice in the sense that you make files tightly coupled causing to edit multiple files when you need to make a simple addition or change. Furthermore, it will eventually become ugly if every site needs to load different dependencies or settings or whatever in your if statement.

It's difficult to say what you need to change without seeing the code, but try looking at design patterns like the factory or abstract factory design patterns to create site objects.

A good book that deals with the subject of patterns and best practices with PHP is PHP 5: Objects, Patterns and Practice by Matt Zandstra: http://www.amazon.com/PHP-5-Objects-Patterns-Practice/dp/1590593804. A very good book.