Database Articles

  Home arrow Database Articles arrow Page 2 - A Framework for Persisting Data Relati...
DATABASE ARTICLES

A Framework for Persisting Data Relationships
By: Codewalkers
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 5 stars5 stars5 stars5 stars5 stars / 2
    2003-01-21

    Table of Contents:
  • A Framework for Persisting Data Relationships
  • The Classes
  • Trying it Out
  • What's next?

  •  
     

    SEARCH CODEWALKERS

    TOOLS YOU CAN USE

    advertisement

    A Framework for Persisting Data Relationships - The Classes


    (Page 2 of 4 )

    <?php
    // test_classes.php

    // A database persitable object, pretty useless unless you extend it.   
    class Persistable {

          // Unique database identifier.
          var $id; 
          // Table name that is used in the database
          var $table; 
          // Map of column labels in the database to object variables
          var $columns = array(); 

          // Persist a new object in the database. 
          function PersistNew() { 
            mysql_connect('localhost', 'username', 'password')
                      or die("Could not connect: " . mysql_error());
            mysql_select_db('databasename') 
                  or die ("Unable to select database");
            
            $sql = "INSERT INTO `".$this->table."` ";
            $labels = "(`id` ";
            $values = ") VALUES ('' ";

            foreach ($this->columns as $column) {
              $labels .= ", `".$column[0]."` ";
              $temp = '$this->'.$column[1];
              $values .= ", '"."$temp"."' ";    
              unset($temp);
            }

            $sql .= $labels.$values.")";
            eval ("\$sql = \"$sql\";");
            $result = mysql_query($sql);
            $this->id = mysql_insert_id();
          }
    }// End Class Persistable

    class Book extends Persistable {

          var $title;//String of book title.

          function Book() { //Constructor for Book.
            $this->table = 'test_books';
            $this->columns = array( array('title','title')
                                  );
          }
    } // End Class Book 

    class Author extends Persistable {
       
          var $fname; // String of author first name.  
          var $lname; // String of author last name.
        
          function Author() { //Constructor for Author.
            $this->table = 'test_authors';
            $this->columns = array( array('firstname','fname'),
                                    array('lastname','lname')
                                  );
          }
    } // End Class Author

    class BookAuthorLink extends Persistable {
       
          var $book; // integer book unique id.  
          var $author; //  integer author unique id.
        
          function BookAuthorLink() { //Constructor for Author.
            $this->table = 'test_bookauthorlink';
            $this->columns = array( array('book','book'),
                                    array('author','author')
                                  );
          }
    } // End Class BookAuthorLink
    ?>

    If you are not familiar with object oriented programming, a real advantage of the technique really shines through in this example. By working with a base class (in this case the class Persistable) I can create functions (called methods if they are contained in classes) that can be used for any object that I extend from the base class. In this case I create three classes that extend the Persistable class. By extending the Persistable class, all of the variables and functions (methods) that are defined in Persistable are available to each of the three extended classes. As a result, the PersistNew() function (method) that is used in the Persistable class is available for all of the other three classes, therefore, I didn't have to recode it for each class extended from it. All I had to do for each of the three extended classes was: (1) set the table variable for each class to the table in the database, (2) set the columns array to map the database column labels to the class variable names, and (3) add whatever variables I wanted for each new object.

    Taking a look back at the code, the part that I think is the most difficult to dissect is the PersistNew() function, so lets look at that in some detail. I start out by creating the first part of the SQL statement :

    "INSERT into $this->table (id, "

    Then I loop through each array in the array columns using foreach. The first column (column[0]) is the database labels, so I build up the SQL statement with the labels that follow the id. During the same foreach, I build the values from the second column (actually I am building the $this->"") portion of the VALUES part of the SQL. When I'm done, I get something that looks like:

    INSERT into example_books (id, title) VALUES ('', '$this->title').

    Then I evaluate the object variables in the SQL using the eval to get:

    INSERT into example_books (id, title) VALUES ('' , 'PHP is Great')

    Then I execute the mysql query. Now the part that I think is pretty neat is the next line of code. Basically all it does is set the id of the current object to mysql_insert_id(); Which is the latest value that mysql has generated using an auto-increment in the current connection. A common misconception is that the ids can get mixed up when two people hit your page at the same time. However, according to the MySQL website: The most recently generated ID is maintained in the server on a per-connection basis. It will not be changed by another client..

    More Database Articles Articles
    More By Codewalkers

    blog comments powered by Disqus

    DATABASE ARTICLES ARTICLES

    - Completing a Book Inventory Management System
    - Uploading Images for a Book Inventory Manage...
    - Finishing the Add Book Story for a Book Inve...
    - Integration Testing for a Book Inventory Man...
    - User Stories for a Book Inventory Management...
    - Unit Testing a Book Inventory Management Sys...
    - Testing a Book Inventory Management System
    - Implementing Models for a Book Inventory Man...
    - Book Inventory Application: Publishers and B...
    - Handling Publishers in a Book Inventory Mana...
    - Publisher Administration for Book Inventory ...
    - Book Inventory Management
    - Using the SQL Reference Manual
    - Using Oracle SQL Developer with SQL Statemen...
    - Fixing Errors with Oracle SQL Developer


    © 2003-2012 by Developer Shed. All rights reserved. DS Cluster 4 - Follow our Sitemap