PHP DevCenter

oreilly.comSafari Books Online.Conferences.

We've expanded our LAMP news coverage and improved our search! Search for all things LAMP across O'Reilly!

Search
Search Tips

advertisement

Listen Print Discuss Subscribe to PHP Subscribe to Newsletters

The Practicality of OO PHP
Pages: 1, 2, 3

Multiplicity

My data extraction class has a flaw. My example class groups the HTML output into an array. This array, being associative, can hold only one row of data from the same database table. Entering a second row of data (from the same database table as the first row) into the array overwrites the original row. Additionally, entering data from a second (different) table that contains one or more columns with identical names as in the first table will override the data from the first table. I could have prevented this with better programming, but I want to show you an example of how I can fix this without having to modify code. This is where multiplicity comes in handy.



Multiplicity is the practice of using multiple instances of the same class. In this case it increases productivity because there is no need to do extra programming. For example, suppose that you need to say hello to two users instead of one. The siteaimproved.php code includes:

<?php
require_once("dataextractionclass.php");

$data1 = new DataExtraction();
$data2 = new DataExtraction();

$data1->deWhereStatement("WHERE id = '2'")
$data1->deExtractDataHtml("users_table", "id", "username", "email");

$data2->deWhereStatement("WHERE id = '3'")
$data2->deExtractDataHtml("users_table", "id", "username", "email");

echo("Hello, ".$data1->deGetData("username")."! ");
echo("Hello, ".$data2->deGetData("username")."!");
?>

Assuming "TestUser" has an ID of 2 and "AnotherUser" has an ID of 3 in the users_table table, that will output the text Hello, TestUser! Hello, AnotherUser!

As you can see, by instantiating a second instance of the class, you can now have multiple rows of data from the same database table. The second instance of the class is a separate object and exists independently of the first. Keep in mind that this might start to hog system resources if you need to call thousand of rows that need to instantiate thousands of objects. You probably wouldn't use this class in such a way, though. I'm simply trying to illustrate a point.

Versatility

Suppose that a new project comes along. It uses Flash and needs to display one row of information from a database. You could create an entirely new set of code and spend a ridiculous amount of time reprogramming old functions, or you could modify the original class. Here's a new function to add into dataextractionclass.php:

// Usage deExtractDataFlash("db_table", "field1", "field2", "field3")
function deExtractDataFlash($table)       
{
    $args = func_get_args();
    foreach($args as $k=>$v)
    {
       if($k != 0)
       {
         $fields .= trim($v).", ";
       }
    }
        
    //takes off the trailing comma and whitespace       
    $fields = substr($fields, 0, (strlen($fields) - 2));        

    $query  = "SELECT $fields FROM $table $this->whereStatement";
    //Ex: WHERE waterId='1'
                
    $this->dbDataExtraction->dbConnect_Db();
    //calls another class within this class
    $result = mysql_query($query) or die("MySQL Query Error: ".mysql_error());
                
    while($row = mysql_fetch_array($result))
    {
        foreach($args as $k=>$v)
        {
           if($k != 0)
           {
                      //outputs in flash variable format
              echo("&".$v."=".$row[$k-1]);
           }
        }
    }
}

You can now call this function from the original dataextractionclass.php class and use it in conjunction with Flash movie files. All that you have to do is insert the new function into the original class file. Sometimes you will find the need to keep your original class intact without changes. In that case, use the keyword extends to add to an existing class without having to modify its file.

For example, the original class name is DataExtraction. Use extends to avoid changing the original class file like so:

<?php
class FlashExtraction extends DataExtraction
{

/* Flash Extraction Function Here */

}
?>

Class extensions, unlike class functions, can go within separate files. In order to take advantage of this technique, however, keep in mind that you must define or include the original class within your PHP page before the class extension. For more in-depth info on PHP classes, refer to the official PHP documentation.

Organization

OO PHP is a great way to keep your files structured and organized. Instead of entire code structures being embedded and spread out over numerous HTML pages, a single class file can dissolve the chaos. When modifying code, instead of having to go to every page to change a variable or add an equation, you only have to modify the class file. The fewer files you have cluttered on your web server, the less likely you will be to freak out when it's time to make a change. Those of us with IT jobs aren't usually the most organized, so any little bit of organization with file structure helps. This also is a factor of productivity as well as efficiency.

Efficiency

OO PHP can increase efficiency dramatically. What do I mean? In this case, it's the integrity of the code--having a finished project with minimal errors. If you have to reuse functions that you have embedded within HTML, chances are good that you may have left out or forgotten some code--it's like losing a sock when you put it in the laundry. With OO PHP, however, the code stays within one file and there is minimal chance that the code will have changed, because all you need to do is transfer the file. Going back to the laundry analogy, this is similar to putting your socks in their own load, where it is easier to keep them all together.

The One Downside to OO PHP

I don't want to be totally biased about OO PHP. There is a disadvantage of using it. Honestly, there aren't many disadvantages to OO PHP, but one sticks out the most: time. It tends to take a little longer to program a class in PHP--in general, not just depending on your skill level. However, your productivity and efficiency increases immediately the next time you use the class. This should really help you decide whether to use OO PHP for certain projects, as I mentioned earlier.

If you need to reuse the code in similar projects, OO PHP is definitely the way to go; however, if you are short on time and will never use the code again, OO PHP may not be a wise choice.

There also is a slight learning curve to using OO PHP. It's nothing drastic, but if you've never worked with classes before or are new to programming, OO PHP may take a little while to get used to.

Conclusion

I hope that you can walk away from reading this with a newfound technique to improve your PHP coding experience. That said, it's important to remember that OO PHP is just a technique. It's not the end-all of other forms of coding. It's another tool in your proverbial toolbox. It's up to you and your good judgment to know whether OO PHP is the right tool to help construct your current project.

Example files are available here.

David Day is the founder of Geekmatics, a company that provides digital business solutions and home PC essentials.


Return to the PHP DevCenter.


Are you still using PHP 4? Was this useful? Let us know here.
You must be logged in to the O'Reilly Network to post a talkback.
Post Comment
Full Threads Oldest First

Showing messages 1 through 8 of 8.

  • Missing files
    2006-08-14 07:14:54  byrne001 [Reply | View]

    Does anyone know where the missing "dbclass.php" in this example and its support files is?
    • Missing files
      2006-08-14 09:24:45  mr_peanut [Reply | View]

      Hello,

      I would try re-downloading the file. I just downloaded it as I read your message and the dbclass.php file was included in the zip.

      Cheers!
  • Security Concerns
    2005-08-02 10:20:23  rmartin [Reply | View]

    There are some key security flaws with this database example used here, that unless you take some strong precautions you'll be in a lot of trouble.
    The example doesn't specially have a connection function (might have been left out for simplicity) but the reader might assume that its ok to put the mysql_connect method and all the password/login in the DataExtraction() (or in __construct() for php5). This is terrible because assuming common setup, I can simply
    include 'http://www.yoursite.com/databaseextraction.php';
    get_class_methods($this);

    and then call your function. Even worse, I can now execute any SQL command I want considering the nature of mysql_query.
    There are something’s that you can do to prevent this from happening, like:

    1. Setup PHP to run as CGI and disable all read permissions http://us2.php.net/manual/en/security.cgi-bin.php

    2. Ensure that you setup a SQL user that only has select permissions if that is all that user is going to be doing, and limit the views. Also, if the SQL server is going to be running on the same server lock the user access to the localhost http://dev.mysql.com/doc/mysql/en/user-resources.html

    3. Use a separate connect function that stores the username and password outside of the main database class.

    To you credit David, I understand that this is not a discussion on security nor do you make a claim this is how you should do it, but I just feel that it is important especially when creating tutorials for beginners that you pay class attention to security issues like this. More available at http://us2.php.net/manual/en/security.database.php


    Thanks,
    Roy
    www.roy-martin.com
    • Security Concerns
      2005-08-11 01:06:17  polarizer [Reply | View]

      >include 'http://www.yoursite.com/>databaseextraction.php';
      >get_class_methods($this);

      How can this work? The script will not be delivered in plain text, but will be interpreted. In case of class-files there is usally no output, cause no stuff is invoked in it.

      Please explain.
    • Security Concerns
      2005-08-11 01:05:41  polarizer [Reply | View]

      >include 'http://www.yoursite.com/>databaseextraction.php';
      >get_class_methods($this);

      How can this work? The script will not be delivered in plain text, but will be interpreted. In case of class-files there is usally no output, cause no stuff is invoked in it.

      Please explain.
    • Security Concerns
      2005-08-02 13:28:43  mr_peanut [Reply | View]

      Hello Roy,

      Thanks for your comment. As you said, this wouldn't be very wise to include the username/password information in the DataExtraction class. My examples, however, do in fact use a seperate class to store the username and password information (not to mention all MySQL functions). Though, I could be further secured by including those additional MySQL functions in yet a third file; however, I was striving for some sort of simplicity as you mentioned, so people could get the general idea behind the benefits of OO PHP).

      There is actually a zip file full of support files that go along with this article which I thought was available, but I am guessing it never posted. I will try to get them up as soon as possible so users can see there is more than just the one file involved (dataextractionclass.php).

      I appreciate your insight to security issues--they are always important, even for the smallest of sites. (For example, just recently a fellow PHP'er contacted me and told me about his troubles from someone who hacked his PHP forms and sent out 80,000 e-mails. And keep in mind his site wasn't used by more than 15 to 30 users.)

      In any case, this article's purpose is to be a stepping stone into the world of OO PHP, showing the benefits of using it. However, I still welcome and encourage constructive criticism, even if the criticism does not pertain to the scope of the article, because it could help answer questions or concerns of the reader. So, thanks again for your input! :-)

      Cheers,
      David
  • PHP OO drawbacks
    2005-07-28 23:30:16  jacekp [Reply | View]

    The so called 'longer development time' is not really a drawback at all. Once you get comfortable with OO (designing classes) it doesn't take much more time. However PHP OO, especially with version 4.x has a lot 'languae-level' drawbacks, that require you to maintain strict discipline and use various tricks. Personally I found that annoying enough to drop PHP for few applications. If you want to stick with PHP, then you might want to take look at http://www.phppatterns.com. You can find there a lot of tips for clean PHP OO programming.
    • PHP OO drawbacks
      2005-07-29 07:32:49  mr_peanut [Reply | View]

      Thanks for your comment! I agree with you that once you get comfortable with OOP that it definitely doesn't take as long; however, personally, I feel there is usually a longer initial programming time. Maybe because I try to organize my class files too much and add a substantial amount of comments :-) But, like the article says, as soon as you use the class a second time your productivity has increased substantially--so whether or not it initially takes you longer, you're still saving time.

      PHP 4.x does have some object drawbacks, but with the new PHP 5 object model, I think programmers migrating from other programming languages may feel a little more at home.

      I'll definitely check out phppatterns.com.


Tagged Articles

Post to del.icio.us

This article has been tagged:

php

Articles that share the tag php:

Understanding MVC in PHP (477 tags)

The PHP Scalability Myth (123 tags)

The Dynamic Duo of PEAR::DB and Smarty (53 tags)

PHP Form Handling (43 tags)

Very Dynamic Web Interfaces (39 tags)

View All

programming

Articles that share the tag programming:

Rolling with Ruby on Rails (1374 tags)

Very Dynamic Web Interfaces (279 tags)

Ajax on Rails (231 tags)

Understanding MVC in PHP (202 tags)

A Simpler Ajax Path (186 tags)

View All

oop

Articles that share the tag oop:

Understanding MVC in PHP (123 tags)

The Practicality of OO PHP (10 tags)

Object Overloading in PHP 5 (5 tags)

Form Your Own Design Pattern Study Group (5 tags)

Static Constructors Demystified (3 tags)

View All

oo

Articles that share the tag oo:

The Practicality of OO PHP (7 tags)

Better Code Through Destruction (6 tags)

Hacking Open Office (2 tags)

Object Overloading in PHP 5 (2 tags)

Introducing Comega (2 tags)

View All

article

Articles that share the tag article:

What Is Web 2.0 (1543 tags)

Rolling with Ruby on Rails (118 tags)

Understanding MVC in PHP (54 tags)

Programming is Hard, Let's Go Scripting... (50 tags)

Very Dynamic Web Interfaces (49 tags)

View All

Sponsored Resources

  • Inside Lightroom
Advertisement

Sponsored by:

O'Reilly Media

©2009, O'Reilly Media, Inc.
(707) 827-7000 / (800) 998-9938
All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
About O'Reilly
Academic Solutions
Authors
Contacts
Customer Service
Jobs
Newsletters
O'Reilly Labs
Press Room
Privacy Policy
RSS Feeds
Terms of Service
User Groups
Writing for O'Reilly
Content Archive
Business Technology
Computer Technology
Google
Microsoft
Mobile
Network
Operating System
Digital Photography
Programming
Software
Web
Web Design
More O'Reilly Sites
O'Reilly Radar
Ignite
Tools of Change for Publishing
Digital Media
Inside iPhone
O'Reilly FYI
makezine.com
craftzine.com
hackszine.com
perl.com
xml.com

Partner Sites
InsideRIA
java.net
O'Reilly Insights on Forbes.com