PHP
  Home arrow PHP arrow Page 3 - Object Interaction in PHP: Introduction to Aggregation, part 2
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
PHP

Object Interaction in PHP: Introduction to Aggregation, part 2
By: Alejandro Gervasio
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 14
    2005-06-01


    Table of Contents:
  • Object Interaction in PHP: Introduction to Aggregation, part 2
  • Fetching data with class: the “MySQLConnector” class
  • Adding Some Functionality to the Class
  • Improving the “MySQLConnector class: adding row-counting methods
  • Implementing the “MySQLConnector” class: a practical example

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    Object Interaction in PHP: Introduction to Aggregation, part 2 - Adding Some Functionality to the Class
    ( Page 3 of 5 )

    Now, let’s add some functionality to the class, writing some code for the constructor, to set up the incoming parameters. So, the complete code for this method look like this:

    function MySQLConnector($host,$user,$password,$database){
        // validate incoming parameters
        (!empty($host))?$this->host=$host:die('Host parameter not valid');
        (!empty($user))?$this->user=$user:die('User parameter not valid');
        (!empty($password))?$this->password=$password:die('Password parameter not valid');
       
    (!empty($database))?$this->database=$database:die('Database parameter not valid');
        // connect to MySQL and select database
        $this->connectDB();
    }

    Up to this point, the constructor has become really very functional; it validates each parameter passed to it, assigning them as class data members. Also, notice that within it, we’re calling the private method “connectDB()”, which complements the job of the constructor. Thus, let’s go one step forth, and define it:

    // connect to MYSQL server and select database
    function connectDB(){
        $this->conId=@mysql_connect($this->host,$this->user,$this->password) or die('Error connecting to the server '.mysql_error());
        @mysql_select_db($this->database,$this->conId) or die('Error selecting database');
    }

    Although this isn’t a difficult method, it does let us connect to MySQL, and select the corresponding database. Now the internal call to this method from the constructor becomes clear. See how we’re encapsulating the native PHP function inside each method? I hope you do!

    Okay, there are still two methods to be defined to get the class completed. Thus, join me below for their definitions. In first place, the “performQuery() method:

    // perform query
    function performQuery($query){
        $this->result=@mysql_query($query,$this->conId) or die('Error performing query '.$query);
    }

    And secondly, the “fetchRow()” method:

    // fetch row
    function fetchRow(){
        return mysql_fetch_array($this->result,MYSQL_ASSOC);
    }

    These are my favorites, take my word for it, because they’re simple yet powerful. The first method accepts the SQL query, performs it against the selected database and ends up building a result set.

    Following the explanation, the second method fetches a row at time from the result set obtained, returning the data in an associative array, where the keys correspond to the name of the fields (notice the usage of the MYSQL_ASSOC argument). Simple, huh?

    Well, I think that our job for defining class methods is already done. So, let’s put the pieces together and assemble the MySQLConnector class. Here’s the full class code:

    class MySQLConnector {
        var $conId; // connection identifier
        var $host; // MySQL host
        var $user; // MySQL username
        var $password; // MySQL password
        var $database; // MySQL database
        var $result; // result set
        // constructor
        function MySQLConnector($host,$user,$password,$database){
            // validate incoming parameters
            (!empty($host))?$this->host=$host:die('Host parameter not valid');
            (!empty($user))?$this->user=$user:die('User parameter not valid');
            (!empty($password))?$this->password=$password:die('Password parameter not valid');
            (!empty($database))?$this->database=$database:die('Database parameter not valid');
            // connect to MySQL and select database
            $this->connectDB();
        }
        // connect to MYSQL server and select database
        function connectDB(){
            $this->conId=@mysql_connect($this->host,$this->user,$this->password) or die('Error connecting to the server '.mysql_error());
            @mysql_select_db($this->database,$this->conId) or die('Error selecting database');
        }
        // perform query
        function performQuery($query){
            $this->result=@mysql_query($query,$this->conId) or die('Error performing query '.$query);
        }
        // fetch row
        function fetchRow(){
            return mysql_fetch_array($this->result,MYSQL_ASSOC);
        }
    }

    So far, the class is ready to be put doing its thing, at least in simple applications. But, I’m feeling like it lacks of some frequent features, often required in such a class. What about adding a few more methods to count the total numbers or records retrieved, the number of records affected by an INSERT, UPDATE or DELETE statement, or the ID of a row just inserted? Surely, that would be a big improvement. It’s just a matter of keeping reading to find out more.



     
     
    >>> More PHP Articles          >>> More By Alejandro Gervasio
     

       

    PHP ARTICLES

    - Building Dynamic Queries with Chainable Meth...
    - PHP Encryption and Decryption Methods
    - Building a MySQL Abstraction Class with Meth...
    - Completing a Sample String Processor with Me...
    - Mastering WHILE Loops for PHP and MySQL
    - Method Chaining: Adding More Methods to the ...
    - Method Chaining in PHP 5
    - The Role of Interfaces in Applying the Depen...
    - Dependency Injection: Using a Setter Method ...
    - Using a Model Class with the Dependency Inje...
    - Injecting Objects Using Setter Methods with ...
    - Injecting Objects by Constructor with the De...
    - The Dependency Injection Design Pattern in P...
    - Performing Inferential Statistical Analysis ...
    - Performing Descriptive Statistical Analysis ...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 6 Hosted by Hostway
    Stay green...Green IT