Intranet Journal
The online resource for intranet professionals
Creating a PHP-Based Content Management System, Part 2
8/5/2004
|
|
Last month I laid out the structure of a content management system (CMS), to be written in PHP for use on a Web site or intranet. This month we'll get going on writing the most basic code on which it will rely.
This article requires a basic knowledge of PHP programming, although a number of concepts are explained for those less experienced.
Our CMS will be stored in a number of folders, structured as follows:
|
|
|||
You may wish to create these four folders now. We're going to start by creating the PHP class which all others will "extend." This will be the root of the administration system, and anything we put in it (such as variables and functions) will trickle down to the other classes.
This root class will be called 'SystemComponent'. The code follows, and a full explanation is below:
<?php
class SystemComponent {
}var $settings;
function getSettings() {
// System variables
$settings['siteDir'] = '/path/to/your/intranet/';// Database variables
$settings['dbhost'] = 'hostname';
$settings['dbusername'] = 'dbuser';
$settings['dbpassword'] = 'dbpass';
$settings['dbname'] = 'mydb';return $settings;
}
Reminder: A class is a block of code. Whenever we need to run that code, we create an 'object' or 'instance' of the class. We can create as many instances of a class as we like. If you don't understand objects and classes by the end of this article, I recommend getting a book or finding a Web site on Object Oriented Programming.
The above code starts off by telling PHP that our class will be called 'SystemComponent'. Between the braces (squiggly brackets) we declare the variable $settings, and a function called 'getSettings'. The purpose of this is to store a number of values in $settings, containing the path on the server to the intranet ('siteDir'), and the details of the database. Change these appropriately for the database system you'll be using (this tutorial uses MySQL, more details coming up). Finally, the 'return' command sends $settings to whichever class or function has requested it. We'll be storing more data in $settings as the series progresses.
Save this code to a file called SystemComponent.php in the 'includes' folder you created. Now let's do something with this class.
All of the information to be displayed in our Content Management System will be stored in a database. It is sensible, therefore, to create a reusable PHP class that we can call upon whenever we need to access our data. The code listed here is for connecting to a MySQL database. If you'll be using a different system, such as PostgreSQL, MS SQL or SQLite, then change the code appropriately. It's obviously quite a bit longer than our previous class, but it performs a number of very important tasks. The code follows:
<?php
////////////////////////////////////////////////////////////////////////////////////////
// Class: DbConnector
// Purpose: Connect to a database, MySQL version
///////////////////////////////////////////////////////////////////////////////////////
require_once 'SystemComponent.php';
class DbConnector extends SystemComponent {
var $theQuery;
var $link;//*** Function: DbConnector, Purpose: Connect to the database ***
function DbConnector(){// Load settings from parent class
$settings = SystemComponent::getSettings();
// Get the main settings from the array we just loaded
$host = $settings['dbhost'];
$db = $settings['dbname'];
$user = $settings['dbusername'];
$pass = $settings['dbpassword'];
// Connect to the database
$this->link = mysql_connect($host, $user, $pass);
mysql_select_db($db);
register_shutdown_function(array(&$this, 'close'));}
//*** Function: query, Purpose: Execute a database query ***
function query($query) {$this->theQuery = $query;
return mysql_query($query, $this->link);}
//*** Function: fetchArray, Purpose: Get array of query results ***
function fetchArray($result) {return mysql_fetch_array($result);
}
//*** Function: close, Purpose: Close the connection ***
function close() {mysql_close($this->link);
}
}
?>
Some explanation is required. After we've named the class 'DbConnector', we state 'extends SystemComponent'. This tells PHP to grab all of the data and functions from SystemComponent, and provide us with access to them (we'll need this in order to get the $settings variable we created earlier).
The first function, 'DbConnector', has the same name as the class that contains it, meaning it's run automatically when DbConnector loads. It firstly calls the 'getSettings' function we wrote earlier, and extracts from it the various database settings. It then uses these settings to connect to the database. (Note that we have no code to deal with errors, this will be covered in detail next time.)
The other functions
are explained below:
| Function | Purpose |
| query | Execute a database query |
| fetchArray | Create an array containing each record found using the 'query' function (above) |
| close | Closes the database connection. The register_shutdown_function command in the DbConnector function ensures this happens automatically when the object is no longer in use. |
Save the above code (also attached at the bottom of this article) to the 'includes' folder, with the name DbConnector.php. This class will be widely used in the Intranet system, so let me give you an example of how we'd create an instance of DbConnector, extract some data, and display it to the user. Let's imagine that our database stores the details of one customer, and we want to get hold of his / her name and display it. Here's the code:
<?php
// Get the PHP file containing the DbConnector class
require_once('DbConnector.php');
// Create an instance of DbConnector
$connector = new DbConnector();
// Use the query function of DbConnector to run a database
query
// (The arrow -> is used to access a function of an object)
$result = $connector->query('SELECT firstname
FROM customers');
// Get the result
$row = $connector->fetchArray($result);
// Show it to the user
echo $row['firstname'];
?>
If you'd like to try out the DbConnector class now, you'll need to save the above code in the includes folder in a php file, and set up a 'customers' table in your database. I'll be covering the set up of our Intranet's database next time.
The importance and power of using a database is clear - we can store information in a formal way, and rapidly access, manipulate and change it. The information we extract or store is specified using the 'query' function of the DbConnector class, and we create instances of DbConnector using the 'new' command, as shown above. This also demonstrates the usefulness of classes - if the settings are changed in SystemComponent, then all of the classes that extend it will automatically be changed.
Next month we'll be adding code to deal with errors, and creating the first part of the administration system that will allow you to add or remove information on the Intranet. Until then!
Files (in compressed format): .zip files (for Windows) .tar files (for Linux)
Read Part 3 of this series at: http://www.intranetjournal.com/articles/200409/ij_09_07_04a.html.