Article

Home » Server-side Coding » PHP & MySQL Tutorials » The PHP Anthology Volume 1, Chapter 2 - Object Oriented PHP

About the Author

Harry Fuecks

author_HarryF Harry has been working in corporate IT since 1994, with everything from start-ups to Fortune 100 companies. Outside of office hours he runs phpPatterns: a site dedicated to software design with PHP that aims to raise standards of PHP development. He also maintains Dynamically Typed: SitePoint's PHP blog.

View all articles by Harry Fuecks...

The PHP Anthology Volume 1, Chapter 2 - Object Oriented PHP

By Harry Fuecks

January 5th, 2004

Reader Rating: 9.5

Page: 1 2 3 4 5 6 7 8 9 10 11 Next

The object oriented paradigm is an approach to programming that’s intended to encourage the development of maintainable and well structured applications. Many PHP coders regard object oriented programming (OOP) as some kind of mystic art, given that frequently, examples of PHP look only at procedural approaches to problem solving. (Note that procedural programming is the name given to non-object oriented programming. All the code we’ve seen in this book so far has been procedural in nature.)

This is a shame, as there is much to be gained from adopting an object oriented approach to developing PHP applications, perhaps the most important being code reuse. A well written piece of object oriented code can easily be employed to solve the same problem in other projects; we can simply slot it in whenever we need it. There is a growing number of object oriented code repositories, such as PEAR and PHP Classes, which can save you from hours of work spent solving well charted problems, and leave you free to focus on the specifics of your application.

In this chapter, you’ll gain a practical grounding in writing object oriented PHP—and there’ll be plenty of opportunities to get your hands dirty. There are many ways to teach OOP, and the topic provides endless room for discussion. In my opinion, the best approach is to dive in head first, seeing how procedural tasks can be accomplished with classes in PHP, and adding the theory as we go. This is the approach we’ll take in this chapter. Throughout both volumes of The PHP Anthology, I’ll be using OOP, where appropriate, which should give you further examples to study. In particular, Chapter 7, Design Patterns should provide some insight into why OOP is an effective way to structure your applications.

In practice, learning to use the object model provided by PHP requires us to achieve two goals, which usually have to be undertaken simultaneously:

  • You’ll need to learn the PHP class syntax and object oriented terminology.
  • You must make the “mental leap” from procedural to object oriented code.

The first step is easy. It’s the subject of the next solution, and further examples appear in later solutions that look at more advanced subjects.

The second step, the “mental leap”, is both easy and challenging. Once you achieve it, you will no longer think about long lists of tasks that a single script should accomplish; instead, you’ll see programming as the putting together of a set of tools to which your script will delegate work.

Jumping ahead a little—to give you a taste of things to come—here’s a simple example that should be familiar to anyone who’s worked with PHP for more than a week: connecting to MySQL and fetching some data. A common procedural approach looks like this:

<?php
// Procedural Example

// Connect to MySQL
$connection = mysql_connect('localhost', 'harryf', 'secret');

// Select desired database
mysql_select_db('sitepoint', $connection);

// Perform a query selecting five articles
$sql = 'SELECT * FROM articles LIMIT 0,5';
$result = mysql_query($sql, $connection);

// Display the results
while ($row = mysql_fetch_array($result)) {
 // Display results here
}
?>

In the above script, we’ve called directly PHP’s MySQL functions, which act on the variables we pass to them. This generally results in our getting back a new variable with which we can perform further work.

An object oriented approach to solving the same problem might look like this:

<?php
// OOP Example

// Include MySQL class
require_once 'Database/MySQL.php';

// Instantiate MySQL class, connect to MySQL and select database
$db = new MySQL('localhost', 'harryf', 'secret', 'sitepoint');

// Perform a query selecting five articles
$sql = 'SELECT * FROM articles LIMIT 0,5';
$result = $db->query($sql); // Creates a MySQLResult object

// Display the results
while ($row = $result->fetch()) {
 // Display results here
}
?>

The detail of dealing with MySQL using PHP’s MySQL functions has now been delegated to an object that’s created from the MySQL class (which we’ll use frequently throughout this book, and which is constructed in Chapter 3, PHP and MySQL). Although this example may not make entirely clear the advantages of OOP, given that, in terms of the amount of code, it’s very similar to the first example, what it does show is that some of the original script’s complexity is now being taken care of by the MySQL class.

For example, we now no longer need to perform two steps to connect to the MySQL server, and then select a database; rather, we can handle both steps in one when we create the MySQL object. Also, should we later wish to have the script fetch the results from a different database, such as PostgreSQL, we could use the relevant class that provided the same application programming interface (API) as the MySQL class—and, to do so, we’d only need to change a single line of the above example. We’ll do exactly that in Chapter 7, Design Patterns.

The object oriented approach really shows its worth in situations in which objects interact with each other. I’ll leave further discussion of that to the solutions in this chapter, but it’s an important concept. As you become fluent in object oriented programming, you’ll find that writing complex applications becomes as easy as putting together blocks of Lego.

I’ll introduce the occasional Unified Modelling Language (UML) class diagram in this discussion. UML is a standard for describing object oriented programs with images. Don’t worry if you haven’t come across UML before; the relationship between the diagrams and the code will speak for itself.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links