Jump-start your PHP applications with the Eclipse PHP Class Generator plug-in

Need a PHP class, but don't know where to start? Let Eclipse build one for you

PHP classes can sometimes still be a black box, a big unknown to many new and some old-school PHP developers. But it doesn't have to be that way. Classes help modularize code and remove extraneous copies of code scattered throughout the code base by placing the code into functions within classes. This helps make maintaining your code much easier. That's what the PHP Class Generator plug-in for Eclipse helps PHP developers do: generate PHP classes to help manage database tables, so you don't have to, which helps speed up the learning curve.

Tyler Anderson, Freelance Writer, Backstop Media

Tyler Anderson received his bachelor's degree in computer science in 2004 and his master's degree in electrical and computer engineering in 2005 from Brigham Young University. He worked with Stexar Corp. as a design engineer from May 2005 to August 2006. He was discovered by Backstop Media LLC in early 2005, and has written and coded numerous articles and tutorials for IBM developerWorks.



05 February 2008

Also available in Japanese

Classes are much like database tables: You can define a car class that has attributes for color, make, model, and year, or you can have a database table that has columns for those same attributes. This is important because most substantial applications involve manipulating data, and it's easy for code to become almost unmaintainable, with changing this value here, and adding a new record there, and differences in coding style all over the place. Using classes eliminates these problems by making it possible to have methods for, say, adding new records or finding a particular piece of data, and that's why the Eclipse PHP Class Generator is a great idea to learn to use.

The key feature of the PHP Class Generator plug-in is that you input database details and get out a class that allows you to easily manage a table in your database. You also pass in an XML template file you create manually that specifies the rules the PHP Class Generator will use in creating your class. The output, of course, is a PHP file geared to help you manage the specified database table. Note that currently, only MySQL is supported by the PHP Class Generator by default. See Resources for more information about support for other databases.

For your reference, an outline of the class you'll generate is shown in Figure 1.

Figure 1. Outline of the class
Outline of the class

In this article, you will:

  • Install the Eclipse PHP Development Tools (PDT) plug-in and the Eclipse PHP Class Generator plug-in
  • Develop and learn the syntax for PHP Class Generator template files
  • Use your template file and the PHP Class Generator to generate a PHP class
  • Use and test your new PHP class in a PHP application

Super-quick installation guide

The PHP Class Generator previously supported PHP Eclipse, and starting in mid-2007, it supports the PHP Development Tools project. Installation begins by installing the PDT, followed by the PHP Class Generator plug-in. To install:

  1. To download the PDT, go to the PDT downloads area (see Resources) and select a Release build (this article was tested using version R20070917).
  2. Under the PDT All-in-One heading, select and download an appropriate version for your system.
  3. After the download is complete, unzip the contents to your programs directory.

Install the PHP Class Generator plug-in:

  1. Visit the PHP Class Generator Web page and download the phpclassgenerator.zip file (see the Downloads).
  2. Unzip the downloaded file to the eclipse/plug-ins directory.

You're ready to roll. Next, you'll begin development on your custom template file.


Creating a database table

The template you're going to create is what you'll use to feed into the PHP Class Generator to create a PHP database class to manage a database table. Before you proceed, you're going to need to create a table in MySQL. To do so, type the following commands in the MySQL console, as shown below.

Listing 1. Creating a new database table in MySQL
mysql> create database phpclass;
mysql> use phpclass;
mysql> CREATE TABLE 'mybiz_users' (
  'username' varchar(50) NOT NULL default '',
  'firstname' varchar(50) NOT NULL default '',
  'lastname' varchar(50) NOT NULL default '',
  'address' varchar(50) NOT NULL default '',
  'city' varchar(20) NOT NULL default '',
  'province' varchar(20) NOT NULL default '',
  'country' varchar(20) NOT NULL default '',
  'postalcode' varchar(20) NOT NULL default '',
  'password' varchar(50) NOT NULL default '',
  'email' varchar(100) NOT NULL default '',
  'homephone' varchar(20) NOT NULL default '',
  'bizphone' varchar(20) NOT NULL default '',
  'cellphone' varchar(20) NOT NULL default '',
  'disabled' enum('false','true') NOT NULL default 'false',
  PRIMARY KEY  ('username')
);
mysql> GRANT ALL PRIVILEGES ON phpclass.* to 'phpclassuser'@'localhost'
identified by 'phpclasspass';

Listing 1 shows a straightforward table that stores user information. The table has a single primary key: username. You also create a new user with access to this table, phpclassuser, with password phpclasspass.

You now have a database table that the PHP Class Generator will be able to create a PHP Class for. Next, you're going to create the template file.


Developing your first Eclipse PHP Class Generator template

The template file needed by the PHP Class Generator plug-in is an XML file specifying its contents. You can use a single template file to create hundreds of classes, depending on the fields of the database table you feed into the PHP Class Generator plug-in.

To begin, create a new file called template.xml and begin defining it as shown below.

Listing 2. Starting the PHP template file
<?xml version="1.0" encoding="UTF-8"?>
<phpClassTemplate xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://www.sahits.ch/xsd/phpClassTemplate.xsd"
>
  <member name="conn"/>
  <members name="DB_FIELDS" initPK="0"/>
  <methods name="DB_FIELD_GETTER"/>
  <methods name="DB_FIELD_SETTER"/>
  <method name="__construct">
    <arg name="conn"/>
    <description>Default constructor</description>
    <description>@param conn the database connection</description>
    <body>
      $this->conn = $conn;
    </body>
  </method>
...

The first four lines specify the encoding of the XML file, the XML schema notation this file is based on (xmlns:xsi), and the schema that defines a correct XML file (xsi:noNamespaceSchemaLocation).

The following two lines specify class fields. The first element, member, containing a name attribute whose value is conn, is used to store the database connection. Within the template file, this field is accessed using $conn. Next, there's a members element, which essentially defines a field for each field found in the mybiz_users table (user name, first name, last name, etc.). You can see each of these fields in Figure 1.

The following two methods elements create getter and setter methods for each and every field in the mybiz_users table, which you can also see in Figure 1.

And the __construct method, the constructor that gets called upon initialization of this class, has four children. The first specifies that the constructor has a single parameter, $conn (as shown in Figure 1), which, as the children description elements specify, is the connection to the database. The body element encompasses code that becomes the method body. Here, the method body saves a local copy of the connection to the database for later use by the class.

With the above functionality, you have specified the fields the generated class should have, as well as getter and setter methods for each. You have also specified a way to pass in the database connection through the constructor.

Next are several functions that load the table data into instances of the class.

Listing 3. Loading data from the database
...
  <method name="TO_STRING" visibility="public"/>
  <method name="INIT_LOAD" visibility="public"/>
  <method name="INIT_POST" visibility="public"/>
  <method name="INIT_GET" visibility="public"/>
  <method name="loadAll" static="true" visibility="public">
    <body>
      $rows = mysql_query("select * from OBJECT_NAME", $this->conn);
      $OBJECT_NAMEs = array();
      while ($row = mysql_fetch_array($rows)) {
        $d = new CLASS_NAME($this->conn);
        $d->init($row);
        array_push($OBJECT_NAMEs,$d);
      }
      return $OBJECT_NAMEs;
    </body>
  </method>
  <method name="LOAD_UNIQUE" static="true" visibility="public">
    <body>
      $OBJECT_NAME = new CLASS_NAME($this->conn);
      $rows = mysql_query("select * from OBJECT_NAME where PK_WHERE",
                          $this->conn);
      $OBJECT_NAME->init(mysql_fetch_array($rows));
      return $OBJECT_NAME;
    </body>
  </method>
...

Here are six methods. The first four are predefined by the PHP Class Generator: TO_STRING returns a string representation of the class. INIT_LOAD is a function that initializes the class from an array containing all the fields in the mybiz_users table. INIT_POST is a similar function, except the class gets initialized from the $_POST array, used to process POST requests. INIT_GET is exactly like INIT_POST, except that its used to process GET requests.

The fifth method here is a custom function that, as you might guess from reading its body contents, loads all records from the mybiz_users table into a numbered array and returns it for further processing.

The sixth method is a semi-custom function that has defined parameters for as many primary keys the database table contains. Since in this case, there is only one primary key, the LOAD_UNIQUE function takes in one parameter, $username (as shown in Figure 1), loads the unique record containing the value specified by $username from the database, and returns it for further processing.

Notice there are a couple of variables in capital letters in the fifth and sixth methods. These variables are predefined, picked up, and replaced with appropriate contents by the PHP Class Generator plug-in:

  • OBJECT_NAME— The name of the database table, in lower caps
  • CLASS_NAME— The class name generated by the PHP Class Generator plug-in
  • PK_WHERE (sixth method) — Specifies the contents of the where clause (username='$username, in this case)

There you have it. Using these six methods, the class you'll generate will be able to display the contents of the class, as well as load data from the database using various flavors of methods.

Next, you'll create templates for the two most important functions, insert and update.

Listing 4. The insert and update methods
...
  <method name="INSERT" visibility="public">
    <body>
      $list = array(FIELD_ARRAY);
      $sql = "insert into OBJECT_NAME values (";
      foreach ($list as $key => $value){
        if(is_string($value))
          $sql .= "'$value', ";
        else
          $sql .= "$value, ";
      }
      $sql = substr($sql, 0, -2).")";
      return mysql_query($sql, $this->conn);
    </body>
  </method>
  <method name="UPDATE" visibility="public">
    <body>
      $list = array(FIELD_ARRAY);
      $sql = "update OBJECT_NAME set ";
      foreach ($list as $key => $value){
        if(is_string($value))
          $sql .= "$key='$value', ";
        else
          $sql .= "$key=$value, ";
      }
      $sql = substr($sql, 0, -2)." where PK_WHERE";
      return mysql_query($sql, $this->conn);
    </body>
  </method>
</phpClassTemplate>

The first method, INSERT, starts off by creating an array of all the fields in the class using another all-caps variable, FIELD_ARRAY, that will be replaced by the PHP Class Generator plug-in appropriately ("username"=>$this->username, "firstname"=>$this->firstname, etc.). This array is then iterated through to populate all the values being inserted as a new record. The query is then executed, the result of which is returned for further processing.

The UPDATE method works similar to the INSERT method, except that the update method requires a where clause, defined by PK_WHERE, used the same way here as it is in Listing 3.

That completes the template. Next, you'll load up the Eclipse PHP Class Generator plug-in and generate a new PHP class.


Using the Eclipse PHP Class Generator plug-in to create a PHP class

With the template file and database ready, you can now use the PHP Class Generator plug-in to build a PHP class to help manage the table you created in Listing 1. Before the PHP Class Generator can be invoked, however, create a new PDT project. Click File > New > Project, then expand the PHP folder and select PHP Project.

Figure 2. Creating a new PHP Project
Creating a new PHP Project

Click Next and enter a name for your project, classgenerator.

Figure 3. Naming your project
Naming your project

Click Finish. Your project should now appear in the PHP Explorer window.

Figure 4. Your new PHP project
Your new PHP project

Now you're ready to invoke the PHP Class Generator plug-in. Make sure your MySQL server is running, then click File > New > Other. Next, expand the PHP folder and select New DB PHP class.

Figure 5. Creating a new DB PHP class using the PHP Class Generator plug-in
Creating a new DB PHP class using the PHP Class Generator plug-in

Click Next and enter a project folder/container for your new class to be saved to (/classgenerator), a file name (Mybiz_users.php), and the path to the template file you created previously.

Figure 6. Entering the class file's details
Entering the class file's details

Click Next. Now enter the access details of your database table.

Figure 7. Entering the details of your database table
Entering the details of your database table

Click Finish to create the class and save it to your project.

Excellent! Next, you'll examine the contents.


Examining the contents of the generated class

As you saw in Figure 1, the PHP Class Generator created several fields and methods in the class. Because you can already see the fields in Figure 1, and the getter and setter methods simply return and set the local fields, respectively, you're going to focus on the functions you created a custom method body for.

First, you'll take a look at the loadAll method.

Listing 5. Examining loadAll
public function loadAll(){
      $rows = mysql_query("select * from mybiz_users", $this->conn);
      $mybiz_userss = array();
      while ($row = mysql_fetch_array($rows)) {
        $d = new Mybiz_users();
        $d->init($row);
        array_push($mybiz_userss,$d);
      }
      return $mybiz_userss;
}

You can see how all the all-caps variables you learned about earlier get picked up and replaced by the PHP Class Generator plug-in. What this method does is create a new instance of your new class, grab all records from the database, and store each record in a numbered array of type mybiz_users, creating a new instance of mybiz_users for each record and initializing it using the init method.

Next, you'll take a look at the loadUnique method.

Listing 6. Examining loadUnique
public static function loadUnique($username){
      $mybiz_users = new Mybiz_users();
      $rows = mysql_query("select * from mybiz_users where ".
                          "'username'='$username'", $this->conn);
      $mybiz_users->init(mysql_fetch_array($rows));
      return $mybiz_users;
}

You can see how PK_WHERE was replaced, and how it completes the select statement. Note that the loadUnique function exists because any query on the table using the where clause above will only have at most one possible return value. Thus, you can call this method and grab the single matching record from the database with one call.

The last method you'll take a look at is the update method.

Listing 7. Examining update
public function update($username){
      $list = array("username"=>$this->username,
                    "firstname"=>$this->firstname, 
                    "lastname"=>$this->lastname, 
                    "address"=>$this->address, 
                    "city"=>$this->city, 
                    "province"=>$this->province, 
                    "country"=>$this->country, 
                    "postalcode"=>$this->postalcode, 
                    "password"=>$this->password, 
                    "email"=>$this->email, 
                    "homephone"=>$this->homephone, 
                    "bizphone"=>$this->bizphone, 
                    "cellphone"=>$this->cellphone, 
                    "disabled"=>$this->disabled);

      $sql = "update OBJECT_NAME set ";
      foreach ($list as $key => $value){
        if(is_string($value))
          $sql .= "$key='$value', ";
        else
          $sql .= "$key=$value, ";
      }
      $sql = substr($sql, 0, -2)." where 'username'='$this->username'";
      return mysql_query($sql, $this->conn);
}

You can see how the FIELD_ARRAY all-caps variable turned out. It simply took each field in the table, in order, and created a lookup array, with the field names as the keys, and the field values as the values. In the foreach loop, the contents of the update statement are populated, with the where clause set up at the end, specifying which user name to update based on the parameter passed into this function with the resulting row returned.

Note there is one change in Listing 7 from what was generated by the PHP Class Generator. The value of PK_WHERE, 'username'='$username', needs to reference this as follows: 'username'='$this->username'.


Testing out the new class within your PHP app

Now for some fun. Create an index.php file in your project by clicking File > New > Other. Expand the PHP directory, select PHP file, and click Next. Type the name as index.php and source folder as \classgenerator. Click Finish.

You should now have a blank source file. Define it as shown below.

Listing 8. Creating a file to test your new class
<?php

include('Mybiz_users.php');

$conn = mysql_connect('localhost','phpclassuser','phpclasspass');
mysql_select_db('phpclass',$conn);

$mybiz_users = new Mybiz_users($conn);
$mybiz_users->setUsername('jdoe');
$mybiz_users->setAddress('one here st.');
$mybiz_users->setBizphone('555-555-5555');
$mybiz_users->setCellphone('555-555-5555');
$mybiz_users->setCity('Phoenix');
$mybiz_users->setCountry('USA');
$mybiz_users->setDisabled('false');
$mybiz_users->setEmail('jdoe@example.com');
$mybiz_users->setFirstname('John');
$mybiz_users->setHomephone('555-555-5555');
$mybiz_users->setLastname('Doe');
$mybiz_users->setPassword('k@ks;1ja');
$mybiz_users->setPostalcode('12345');
$mybiz_users->setProvince('AZ');

$mybiz_users->insert();
$allRecords = $mybiz_users->loadAll();

echo 'begin1
';
for($i = 0; $i < sizeof($allRecords); $i++){
	print_r($allRecords[$i]);
	echo '
';
}
echo 'end1

';


$mybiz_users->setDisabled('true');
$mybiz_users->update();
$allRecords = $mybiz_users->loadAll();

echo 'begin2
';
for($i = 0; $i < sizeof($allRecords); $i++){
	print_r($allRecords[$i]);
	echo '
';
}
echo 'end2

';

mysql_query("delete from mybiz_users where username='jdoe'");

?>

What you're doing here is creating a connection to the MySQL server. You then create and initialize a new mybiz_users record, insert it into the database, then load and display. Then, to test update, you disable the user by calling setDisabled('true'), update the user record in the database, reload the record, and display. Last, you delete the record so you can test again.

Before you run, you need to add a PHP executable: Click Window > Preferences, expand PHP, select PHP Executables, click Add, and enter a name, directory path and debugger (PHP V5, C:\apps\wamp\php, and XDebug, were used in this article, respectively).

To run, click Run > Run, select PHP Script, and click OK. If asked, choose the PHP executable you just set up and the XDebug debugger, and you're ready to run.

Review the output from executing the code in Listing 8 in the PDT debugger.

Figure 8. Debugger output
Debugger output

You can see the output. The first time you load the record, you see disabled="false". Then you set disabled="false" and call the update statement. After you reloaded the table, disabled was changed to "true". Essentially, without any extra SQL, you've updated your database using a class, saving yourself coding time.


Summary

Your PHP development using MySQL will be much easier now that you've figured out how to make a slick and fast class to help you conquer the database, and clean up potentially messy code with the help of a PHP class. Feel free to experiment with building your own template files, to have the Eclipse PHP Class Generator plug-in create even more personalized classes for you.

Make sure you review the Resources section to learn more things you can do with the Eclipse PHP Class Generator plug-in and contribute your expertise.


Download

DescriptionNameSize
Sample codeos-eclipse-phpclassgen.code.zip4KB

Resources

Learn

Get products and technologies

Discuss

  • The Eclipse Platform newsgroups should be your first stop to discuss questions regarding Eclipse. (Selecting this will launch your default Usenet news reader application and open eclipse.platform.)
  • The Eclipse newsgroups has many resources for people interested in using and extending Eclipse.
  • Participate in developerWorks blogs and get involved in the developerWorks community.

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into Open source on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=Open source
ArticleID=285390
ArticleTitle=Jump-start your PHP applications with the Eclipse PHP Class Generator plug-in
publish-date=02052008