<? Classes/Paging?>

Classes/Paging


Until now we have reused code mainly by creating functions and placing them in include files. This works fine for most PHP applications. We are thus able to develop more quickly, by including files with code we had already written, and could view significant code more easily.

We also benefit by being able to adapt the code in our include file, and have the results effect all pages that call the include. A more advanced way to re-use code is to create a class, create instances (specific examples) of our class called objects and use the objects created to store data and perform special functions called methods on the data that they contain.

We have seen one class thus far.  A class named Config created our $config object that stores site wide properties like the contents of the <title> tag and meta tags in our include files.  We need to learn about classes because a great deal of useful code will come to us in the only form of classes & objects.

Classes Defined: class is a blueprint, or prototype, that defines the properties (qualities) and methods (functions/operations) common to all objects of a certain type.  We can use a class to create an instance (a particular occurence) of an object, which is defined by the class from which it sprang. Seabiscuit is a particular horse (an instance of an object) that sprang from the "horse" class! (the model or template defining all horses)

Classes are 'Out Of Flow': Classes, like functions can be considered out of flow of the normal procedure 'top down' reading of code.  All functions and classes are read into memory before procedural code is run.  Therefore classes and functions can be anywhere, before or after the code and can easily reside in include files.

One Classy Car: let’s think about a class named Car. Such a class could have a property (quality or characteristic) called "color". All objects created based on this class would have such a property, but some objects set this property to "red", others to "blue", and so on. This means that the class only holds a definition, and the object holds the actual value (red or blue).

You can declare a class by using the class keyword:

class Car
{
  public $color; //the color of the car
  public $mph; //the maximum speed
  public $price; //the price of the car, in dollars
 
public $model; //the model of the car
  function go($hours)
  {
    return ($this->mph * $hours); //returns miles traveled given time
  }
}

After the declaration of the class, you can see the variables used within the class, which are called properties. These are declared using the "public" statement, which allows the data stored in them to be available outside the class.

Functions within a class are called methods. They're used to manipulate the class properties and produce results. In this simple method you can see that when we use a class method or property, we must use the “->” operator, which is used to reference a property or method in any class, either from the inside or outside. The keyword “this” tells the class to reference the current instance of the object. PHP then knows the property or method is internal (contained) inside.

Creating An Object: While a class only exists in code and is considered to be a blueprint, an object exists in memory and is a working instance (example) of a class. An instance of an object is created using the "new" statement along with the name of the class the object is based on. Let’s return to our Car class:

$myCar = new Car();
$
myCar->color = "red";
$
myCar->price = 60000;
$
myCar->model = "Ferrari";
$myCar->mph = 140;

echo "My " . $myCar->model . " can go " . $myCar->go(.5) . " in half an hour!";

We use the "->" operator to access and modify the object's properties. We use the same operator to call a method.

Benefits of Objects: Perhaps the greatest benefit of object-oriented code is reusability. Because the classes used to create objects are self-enclosed, they can be easily copied from one project and inserted into another. Additionally, it is possible to create child classes that inherit and/or override the characteristics of their parents. This technique allows you to create more complex and specialized objects.  One last benefit is that we can encapsulate (hide) complex code in the class/object to make large chunks of code more useable.

Constructor Function: If you wish to have the object load initial properties when it is created, you place code into a special function called a constructor. This function runs when an instance of the object is created. In PHP version 5 the constructor is named __construct() (note the double underscore!). In previous versions of PHP, the constructor was given the same name as the class. (This is done in several other languages).

Here we add a constructor to our class:

class Car
{
  public $color; //the color of the car
  public $mph; //the maximum speed
  public $price; //the price of the car, in dollars
 
public $model; //the model of the car
  function go($hours)
  {
    return ($this->mph * $hours); //returns miles traveled given time
  }

    function __construct($model,$color,$price,mph)
   {
      $this->model = $model; //assigning data to properties via the constructor
      $this->color = $color;
      $this->price= $price;
      $this->mph= $mph;
   }

}

Now we can create our Car object and assign initial values in one line of code:

$myCar = new Car("Ferrari","Red",60000,140);

An Array of Objects: Once we can create objects in one line of code, we can create an array and store several objects at once:

$aCar = array(); //an empty array
$aCar[] = new Car("Ferrari","Red",60000,140); //now we're creating and adding cars to the array
$aCar[] = new Car("Corvette","Blue",40000,120);
$aCar[] = new Car("Volkswagen","Green",30000,80);
$aCar[] = new Car("Hummer","Black",100000,100);

The data entering the Car objects above would normally come from a database.  Once the $aCar array is loaded, we can use a foreach loop to access all the data quickly:

echo "We have " . count($aCar) . " cars, and here they are:<br />";

foreach($aCar as $car)
{

     echo "Here's a " . $car->color . " " . $car->model . " . It can go " . $car->mph . " and it costs $" . $car->price . ".<br />";

}

Next let's look at an object we've seen in our code before.

config Object: In config_inc.php we assigned values to a $config object that was created to store site wide page properties. If you look at the config_inc.php file you'll find this line of code:

$config = new Config();

This is an instance of the Config class being created as an object named $config.  This object has a special capability in which I can use two magic methods in PHP __get() and __set() to create properties on the fly.  In PHP this capability is called overloading.  With this we assign HTML and text to properties that are therefore available anywhere on our site page:

$config->theme = 'TwoTone';
$config->titleTag = 'ITC280';
$config->metaDescription = 'Web Database ITC281 class website.';
$config->metaKeywords = 'SCCC,Seattle Central,ITC281,database,mysql,php';
$config->metaRobots = 'no index, no follow';

Storing all our page data in an object named $config allows us to pass only one object into the function named get_header() to allow every attached property to be available to the entire page, no matter which header/footer combination is used.

More About Classes: To take a closer look at the relationship between classes & objects in PHP, please study the following PHP Object Fundamentals Handout Once you've studied that here's the official starter page for PHP classes: Class Basics at php.net.

Also check out phpclasses.org, to see all the great code that is available in class form!

Paging: Another place that using an object can come in handy is when we span records across multiple web pages.  We'll use it in a new version of the list/view application as detailed below.

When you are presenting records that number into the dozens or possibly the hundreds you will need to consider spanning your data across multiple pages. Google, Amazon and other web sites use a method of showing "Next" and "Previous" links on the bottom of a page, as well as numbered links to allow a user to select a single page.

Pager Class: The following example builds a PHP class, and allows easy access to paging. You can either use simple characters such as < and > for your ‘previous’ and ‘next’ icons, or use images.

The Pager class creates simple records paging by deconstructing the existing SQL statement and adding MySQL limits to the statement. Once the Pager object is loaded with the SQL statement, a method named 'showTotal()' returns the possible number of records, and another named 'showNav()' places the Paging Nav (next & previous arrows, etc.) on the page.

Calling the constructor allows a default configuration, which applies simple text 'arrows'. Upon creation the developer can identify a different number of records per page, and implement images for arrows or text in any combination. Here is the minimal implementation using the default 'first' 'prev', 'next', 'last' arrows, and declaring 10 records per page:

$myPager = new Pager(10);

The next example instantiates the pager object with 20 records and images for previous & next arrows, and no first & last arrows:

$myPager = new Pager(20,'','<img src="images/arrow_prev.gif" border="0" />','<img src="images/arrow_next.gif" border="0" />','');

Note the use of single quotes, '', to indicate no 'first' or 'last' icon above.

Once the pager is instantiated, you are required to run your SQL statement through the loadSQL() function:

$myPager = new Pager(10); //create new pager object
$sql = $myPager->loadSQL($sql); //adapt existing SQL statement

Since MySQL limits the number of records returned, this function will disassemble the SQL statement and re-assemble it to retrieve the total number of records per page. The adapted SQL statement is returned to be used by the page.

IMPORTANT: The pager needs to adapt the SQL BEFORE the SQL statement is used by the page. You would re-use the variable named $sql (for instance) in the SQL call on the page. See a new version of the demo_list_pager.php example below to see the Pager implementation in action.

demo_list_pager Zip File of Code

The Pager class exists in a file named Pager_inc.php, which will reside in your PHP include folder, inc_0700. You may have noticed that the include file used purposely starts with a capital ‘P’. That is because PHP will automatically look for an include file that matches the name of a class with another "magic" PHP function named __autoload().  We can override __autoload() by creating our own version of the function, and tell PHP where to look for our Class files.

Our version of the __autoload() function is in the common_inc.php, and it appends the suffix “_inc.php” to the end of the file for which PHP searches.  We will also tell PHP to look in our PHP include folder for all such class files, in our case inc_0700.

The reason for using __autoload() is to only load code that is actually used, instead of cluttering server memory with classes that are not utilized.  The confusing part is that we don't need to include the file at all, as long as PHP knows where to search for class files, if it finds a class for which there is no obvious definition available.

Print this Page Back To Top

© 2000- 2012 newMANIC INC, All rights reserved