Put some MVC in your PHP
Trial by separation
Hands on The Model-View-Controller (MVC) architecture provides a useful three-tier pattern for building software, as MVC patterns decouple the graphical user interface (GUI) from the application logic.
That comes in useful when it comes to changing an application after it has been deployed. Separation of the views from the data means modifications made in the views do not affect the model and modifications made to the model to not effect the graphical user interface, simplifying maintenance. Also, an application may be expanded to add views and controllers that talk to a model without actually making any changes to the model itself.
Unfortunately for web developers, one of the features lacking in PHP until recently has been support for the MVC architecture. That has meant the MVC pattern has had to be implemented externally.
Some PHP frameworks have now added support for the MVC pattern, most notably the Zend Framework - one of the leading open-source PHP frameworks. Zend simplifies the task of developing secure, reliable web-based applications and web services. Zend provides an extensible code base, a flexible architecture and does not require any configuration files.
In this article we shall connect Zend to a database from Oracle, a company that's been working closely to optimize its software with Zend.
Fire up Zend
The Zend framework requires at least PHP 5.1.4. It's recommended to install PHP 5.2.2 or later because of the security and performance improvements in the newer version of PHP. Download the Zend Framework zip file from here and - if you don't already have it - download and install Apache 2.2.3, making sure it's configured with PHP. Then, add the following
include_path directive to
php.ini configuration file:
Enable the PHP database extension for Oracle database in
Restart Apache HTTP Server. Install the Oracle database including the sample schemas and create a table
Catalog using SQL script
Create an MVC application
Now it's time to create a Create Read Update Delete (CRUD) application using Zend's MVC architecture that'll let us build, read, update, and delete an Oracle database table row.
In the MVC architecture the model represents the entities/class objects, the controller implements the business logic and integrates the model with the view, and the view represents the presentation layer or the user interface.
The MVC architecture in Zend Framework is implemented by the
Zend_Controller component. The
Zend_Controller_Front class provides a front controller for the MVC architecture. The front controller intercepts all requests and dispatches the requests to action controllers based on the request URL. The format of the request URL is
http://localhost/controller/action. If no controller is specified the
index controller and the
index action are invoked. An action controller class extends the
Zend_Controller_Action class. An action controller class is named with the notation
<ControllerName>Controller. For example, the action controller class for the "index" controller is
Create a "controllers" directory and a "views" directory in the Apache web server document root
htdocs by default. We shall create the view scripts in the "views" directory and controllers in the "controllers" directory. Create action controller, "database", for the business logic of the MVC application. Create a
DatabaseController class that extends the
Zend_Controller_Action class and add action functions
deleteAction to the class.
The controller actions will be invoked from view scripts, which provide a user interface to specify the table row to be added, selected, updated and deleted. Create the view scripts
deleteView.php in the "views" directory. The view scripts and other resource files are available in a zipped resources file here.
Add a row
First, we shall add a row to the
Catalog table. In the
insertView.php add a form with input fields for the table row to be added. The "action" attribute of the
<form> element specifies "database/insert", which corresponds to the "insert" action of the "database" controller. In the
insertAction function create a
Zend_Db adapter, which represents a connection with Oracle database, using the
$params = array ('host'=>'localhost','username'=>'OE','password'=>'pw','dbname'=>'orcl'); $db=Zend_Db::factory('Oracle', $params);
The first argument specifies the base name for the adapter class - "Oracle" for the Oracle database. The second argument specifies the adapter parameters. Retrieve the input fields specified in the
$_POST['field'] and create an associative array,
$row, for the columns that constitute a row in the database table. Specify the database table to be updated and insert the new row using the
insert() method of the
Zend_Db adapter class.
$table = 'Catalog'; $rowsAffected = $db->insert($table, $row);
The first argument of the
insert() method is the database table and the second argument is the associative array that maps column names to values. Invoke the
insertView.php with URL
http://localhost/views/insertView.php. To add a row specify the column values and click on create.
Adding a row
Retrieve a row
Next, retrieve a row from the catalog table using the Zend Framework. Create a
Zend_Db_Select object from the
Zend_Db adapter object using the
$select = $db->select();
Zend_Db_Select object is used to construct a SQL
SELECT statement. Specify the
FROM clause using the
from() method and the
WHERE clause using the
$select->from('Catalog', '*'); $select->where('ID = ?', $_POST['id']);
Create the SQL query string from the
Zend_Db_Select object using the
_toString() method. Run the SQL query using the
fetchAll() method and query results will be returned as a row set.
$sql = $select->__toString(); $rowset = $db->fetchAll($sql);
Zend_View object to render a view script and specify the directory containing the view scripts. The
Zend_View class represents the "view" component of the model-view-controller pattern.
$view = new Zend_View(); $view->setScriptPath('views');
Assign the row column values to the
Zend_View instance. The variables assigned to the
Zend_View object become the properties of the
$view->id = $_POST['id']; $view->journal = $rowset["JOURNAL"]; $view->publisher = $rowset["PUBLISHER"]; $view->edition = $rowset["EDITION"]; $view->title = $rowset["TITLE"]; $view->author = $rowset["AUTHOR"];
Create a view script,
resultView.php, associated with the
Zend_View object. The view script will run in the scope of the
Zend_View object. References to
$this in the view script are references to the
Zend_View object. Create a table header and add values to the table using the
Zend_View properties assigned in the action controller. In the
selectAction function render the
selectView.php view script with the URL
http://localhost/views/selectView.php. Specify the catalog ID for the row that is to be retrieved and click select.
Selecting a database table row
The row corresponding to the specified catalog ID will be retrieved and the results displayed.
Update a Row
Next, update a catalog table row using the Zend Framework. Create an associative array,
$data, of column names and values for the row to be updated. Create a SQL expression specifying the
WHERE clause for the ID of the row to be updated.
$where = "ID ="."'".$_POST['id']."'";
Update the database table using the
$n = $db->update('Catalog', $data, $where);
updateView.php script with URL
http://localhost/views/updateView.php. Specify the catalog ID of the row to be updated and the column values to be updated and click on update.
Updating database table
A table row may be deleted using the
MVC has a proven track record in simplifying the development and on-going maintenance of applications. Using Zend and the methodology I have outlined, you can now take advantage of MVC to simplify your work with PHP applications.®