Using An Object Oriented Approach for Implementing PHP Classes to Interact with Oracle

0
125
8 min read

Before you start developing object-oriented solutions with PHP 5, it is important to understand that its object model provides more features than PHP 4’s object model. Like most object-oriented languages, PHP 5 allows the developer to take advantage of interfaces, abstract classes, private/public/protected access modifiers, static members and methods, exception handling, and other features that were not available in PHP 4. But perhaps the most important thing to note about the object-oriented improvements of PHP 5 is that objects are now referenced byhandle, and not by value.

Building Blocks of Applications

As you no doubt know, the fundamental building block in any object-oriented language is a structure called a class.

A class is a template for an object. It describes the data and behavior of its instances (objects). During run time, an application can create as many instances of a single class as necessary.

The following diagram conceptually depicts the structure of a class.

Using An Object Oriented Approach for Implementing PHP Classes to Interact with Oracle

You might find it handy to think of an object-oriented application as a building made of blocks, where classes are those blocks. However, it is important to note that all blocks in this case are exchangeable. What this means is that if you are not satisfied with the implementation of a certain class, you can use a relevant class that has the same Application Programming Interface (API) but a different implementation instead. This allows you to increase the reusability and maintainability of your application, without increasing the complexity.

The intent of the example discussed in this section is to illustrate how you can rewrite the implementation of a class so that this doesn’t require a change in the existing code that employs this class. In particular, you’ll see how a custom PHP 4 class designed to interact with Oracle can be rewritten to use the new object-oriented features available in PHP 5.

Creating a Custom PHP Class from Scratch

To proceed with the example, you first need to create a PHP 4 class interacting with Oracle. Consider the following dbConn4 class:

    <?php
//File: dbConn4.php
class dbConn4 {
var $user;
var $pswd;
var $db;
var $conn;
var $query;
var $row;
var $exec_mode;
function dbConn4($user, $pswd, $db, $exec_mode= OCI_COMMIT_ON_SUCCESS)
{
$this->user = $user;
$this->pswd = $pswd;
$this->db = $db;
$this->exec_mode = $exec_mode;
$this->GetConn ();
}
function GetConn()
{
if(!$this->conn = OCILogon($this->user, $this->pswd, $this->db))
{
$err = OCIError();
trigger_error('Failed to establish a connection: ' .
$err['message']);
}
}
function query($sql)
{
if(!$this->query = OCIParse($this->conn, $sql))
{
$err = OCIError($this->conn);
trigger_error('Failed to parse SQL query: ' .
$err['message']);
return false;
}
else if(!OCIExecute($this->query, $this->exec_mode))
{
$err = OCIError($this->query);
trigger_error('Failed to execute SQL query: ' .
$err['message']);
return false;
}
return true;
}
function fetch()
{
if(!OCIFetchInto($this->query, $this->row, OCI_ASSOC))
{
return false;
}
return $this->row;
}
}
?>

In the above script, to define a class, you use the class keyword followed by the class name. Then, within curly braces, you define class properties and methods. Since this class is designed to work under both PHP 4 and PHP 5, all the class properties are defined with the var keyword. Declaring a property with var makes it publicly readable and writable. In PHP 5, you would use the public keyword instead.

In PHP 4, you define the class constructor as a function with the same name as the class itself. This still works in PHP 5 for backward compatibility. However, in PHP 5, it’s recommended that you use __construct as the constructor name.

In the above example, the class constructor is used to set the member variables of a class instance to the values passed to the constructor as parameters. Note the use of the self-referencing variable $this that is used here to access the member variables of the current class instance.

Within class methods, you can use $this, the special variable that points to the current instance of a class. This variable is created automatically during the execution of any object’s method and can be used to access both member variables of the current instance and its methods.

Then, you call the GetConn method from within the constructor to obtain a connection to the database. You reference the method using the $this variable. In this example, the GetConn method is supposed to be called from within the constructor only. In PHP 5, you would declare this method as private.

To obtain a connection to the database in this example, you use the OCILogon function. In PHP 5, you would use the oci_connect function instead. The query method defined here takes an SQL string as the parameter and then parses and executes the query. It returns true on success or false on failure. This method is supposed to be called from outside an object. So, in PHP 5, you would declare it as public.

Finally, you define the fetch method. You will call this method to fetch the results retrieved by a SELECT statement that has been executed with the query method.

Testing the Newly Created Class

Once written, the dbConn4 class discussed in the preceding section can be used in applications in order to establish a connection to an Oracle database and then issue queries against it as needed. To see this class in action, you might use the following PHP script. Assuming that you have saved the dbConn4 class as the dbConn4.php file, save the following script as select.php:

    <?php
//File: select.php
require_once 'dbConn4.php';
require_once 'hrCred.php';
$db = new dbConn4($user, $pswd, $conn);
$sql="SELECT FIRST_NAME, LAST_NAME FROM employees";
if($db->query($sql)){
print 'Employee Names: ' . '<br />';
while ($row = $db->fetch()) {
print $row['FIRST_NAME'] . '&nbsp;';
print $row['LAST_NAME'] . '<br />';
}
}
?>

The above select.php script employs the employees table from the hr/hr demonstration schema. So, before you can execute this script, you must create the hrCred.php file that contains all the information required to establish a connection to your Oracle database using the HR account. The hrCred.php file should look as shown below (note that the connection string may vary depending on your configuration):

    <?php
//File: hrCred.php
$user="hr";
$pswd="hr";
$conn="(DESCRIPTION=
(ADDRESS_LIST=
(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521))
)
(CONNECT_DATA=(SID=orcl)(SERVER=DEDICATED))
)";
?>

Once you have created the hrCred.php script, you can execute the select.php script. As a result, it should output the names of employees from the employees table in the hr/hr demonstration schema.

Taking Advantage of PHP 5’s Object-Oriented Features

Turning back to the dbConn4 class, you may have noticed that it was written for PHP 4. Of course, it still can be used in new applications written for PHP 5. However, to take advantage of the new object-oriented features available in PHP 5, you might want to rewrite this class as follows:

    <?php
//File: dbConn5.php
class dbConn5 {
private $user;
private $pswd;
private $db;
private $conn;
private $query;
private $row;
private $exec_mode;
public function __construct($user, $pswd, $db,
$exec_mode= OCI_COMMIT_ON_SUCCESS)
{
$this->user = $user;
$this->pswd = $pswd;
$this->db = $db;
$this->exec_mode = $exec_mode;
$this->GetConn();
}
private function GetConn()
{
if(!$this->conn = oci_connect($this->user, $this->pswd,
$this->db))
{
$err = oci_error();
trigger_error('Failed to establish a connection: ' .
$err['message']);
}
}
public function query($sql)
{
if(!$this->query = oci_parse($this->conn, $sql)) {
$err = oci_error($this->conn);
trigger_error('Failed to execute SQL query: ' .
$err['message']);
return false;
}
else if(!oci_execute($this->query, $this->exec_mode)) {
$err = oci_error($this->query);
trigger_error('Failed to execute SQL query: ' .
$err['message']);
return false;
}
return true;
}
public function fetch()
{
if($this->row=oci_fetch_assoc($this->query)){
return $this->row;
}
else {
return false;
}
}
}
?>

As you can see, the implementation of the class has been improved to conform to the new standards of PHP 5. For instance, the above class takes advantage of encapsulation that is accomplished in PHP 5—like most other object-oriented languages—by means of access modifiers, namely public, protected, and private. The idea behind encapsulation is to enable the developer to design the classes that reveal only the important members and methods and hide the internals. For instance, the GetConn method in the dbConn5 class is declared with the private modifier because this method is supposed to be called only from inside the constructor when a new instance of the class is initialized; therefore, there is no need to allow client code to access this method directly.

Since the implementation of the newly created dbConn5 class is different from the one used in dbConn4, you may be asking yourself: “Does that mean we need to rewrite the client code that uses the dbConn4 class as well?” The answer is obvious: you don’t need to rewrite client code that uses the dbConn4 class since you have neither changed the Application Programming Interface (API) of the class nor,more importantly, its functionality. Thus, all you need to do in order to make the select.php script work with dbConn5 is simply replace all the references to dbConn4 with references to dbConn5 throughout the script.

LEAVE A REPLY

Please enter your comment!
Please enter your name here