Archive for October 12th, 2007

Creating a PHP-Based Content Management System

part one

i will ad the part tow in few days

If you’re going to run an intranet site, then you’ll probably want a content management system (CMS) — a tool used to organize documents and keep track of what’s where. I’ve covered a plethora of such systems in previous articles, but for many businesses there can be only one solution: to design and implement their own custom system.

Why? It’s not like the off-the-shelf systems lack features or stability. On the contrary, many have been crafted by hundreds of man-hours of work, and are successfully implemented by thousands of Web sites and intranets. But when it comes down to it, it’s hard to have much clue as to how they work. If you want to customize the way these systems operate, you’ll often have to wade through vast amounts of (often badly documented) code to find what needs changing.

Writing your own CMS, on the other hand, can lead to a solution that is better suited to your requirements, better addresses the needs of your users, and is better understood by your development team. If you have the time and expertise to write your own in-house system, it may well prove the better option. And this is what I shall be embarking upon in this series.

The system we create will be written using the PHP programming language, which excels in the development of Web-based systems. I’ll be using MySQL as the database server, but the system will be written to allow the use of alternative databases, such as PostgreSQL or SQL Server.

So what will this system actually do? First and foremost, it will allow the bulk of the intranet or Internet site’s content to be easily stored and managed in a database. We’ll also include a number of other features required for running a successful site, such as authenticating users and managing files.

Some basic PHP knowledge will be needed for coding your own CMS, although most of what you’ll need to know will be demonstrated here. I’ll assume you have access to a server running PHP and a database system. Once the series is complete, I’ll make available a polished version of the CMS for anyone to use.

I don’t promise the vast array of abilities incorporated into systems such as Postnuke, Smarty, or some commercial content management systems. But just having lots of features isn’t always what’s needed, and this series will help you to develop a system specifically targeted to your needs. With that, let’s get going…

Planning the CMS

To begin with, we’ll plan how our PHP-based content management system will work. In subsequent articles, I’ll demonstrate how each of the major components are implemented, leading to a complete system.

The first step is a basic specification of what our CMS must do. Obviously, this will depend on your needs:

  • Content Management: Probably the most vital function of the system, it must store content such as documents and news in a database, and display to the user whatever he or she requests. An easy-to-use interface is required to allow editors to add, remove, or modify content.
  • User authentication: There may be certain areas of the intranet or Internet site to which we wish to limit access. At the very least this will be the “admin” area, where the editor of the site will be able to add, edit or modify content. You may also wish to have areas only available to certain departments or staff.
  • Page uniformity/templates: The system should have a uniform look and feel, and this design element needs to be separated from the logic element, e.g., the programming required to display an article should be separated from how that article looks (stylistically) on the screen.

Object-Oriented Programming

PHP helps the design process by supporting object-oriented programming (OOP). When putting together our system, there are certain chunks of programming that are needed again and again, such as database access, user authentication, etc. To keep this code neat and tidy, we bundle it together in PHP files called “classes.” We can then create instances (or “objects”) of these classes whenever they are needed. Thus, the class can be thought of as a blueprint for one or more instances.

For example, we could create a class with code for connecting to a database, and then create an instance of that class whenever we need to query the database. If this isn’t immediately clear then don’t worry, it will become more obvious when we start coding. This method of programming allows a complex system to be broken down into smaller and simpler blocks, which makes life easier when it comes to management, modification, and error finding.

Let’s now consider how the system will fit together. This will doubtless be tweaked as you consider the requirements for your own system, but below is a basic outline:

System diagram

We have four main PHP modules (or “classes”) that will be widely used in the system. These are tasked with accessing the database, allowing the user to upload files to the site, reading and writing templates, and logging users in and out. These classes all “extend” one parent class called “systemObject.”

Think of these four as being independent of one another, yet all inheriting whatever data we put in systemObject. This technique of hierarchy allows us to make changes effecting all four system classes, just by adding or modifying the code in the systemObject parent class. Again, this concept will become clearer when we start coding. In the middle of the diagram are the basic areas of the administration system, and each will need one or more PHP pages to perform the required tasks.

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

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.

Creating the Database

The first table we’re going to add to our database will store articles, for display on the Intranet. The ability to share information is the most important function of an Intranet, and the job of the Content Management System is to make doing this as easy as possible. Consider your own data requirements, a few important ones spring to mind for most articles tables:

Field Purpose Type
ID A unique number given to each article, and the primary key of the table. Integer
Title The title of the article Varchar(300)
Tagline A very short summary of the article Varchar(600)
Section The category to which the article belongs Integer
TheArticle The article itself Text

Before we can create the system itself, we need to create the database to store our information. The code below will set this up if you’re using the MySQL database system – uses of other systems should modify the commands appropriately. Copy and paste the following into the MySQL admin tool, or use one of the many free ‘client’ programs available:

CREATE TABLE `databasename`.`cmsarticles` (
`ID` int(6) unsigned NOT NULL auto_increment COMMENT ‘The unique ID of the article’,
`title` varchar(200) NULL COMMENT ‘The article title’,
`tagline` varchar(255) NULL COMMENT ‘Short summary of the article’,
`section` int(4) NULL DEFAULT 0 COMMENT ‘The section of the article’,
`thearticle` text NULL COMMENT ‘The article itself’,
PRIMARY KEY (`ID`)
);

If all has gone to plan, you should now have a working table in the database. We’re now going to create a page to allow you or your staff to enter articles into the system.

Creating the editor

Firstly, design a form using the HTML editor of your choice. Create text fields for each database field (excluding ID). An example is below:

Title:Tagline:Section:Article:

Add comment October 12, 2007

Custom Content Management with PHP

 Custom Content Management with PHP
by Thomas Perl

It is well known that you can create powerful Web pages with PHP. Often, the question arises: How are these pages made? This tutorial wants to give you some hints on how to make your Web site appear more managed from both inside and outside. These are my own approaches to Web development; I hope you find them useful. Take these things as ideas rather than good practice.


Copyright notice: All reader-contributed material on freshmeat.net is the property and responsibility of its author; for reprint rights, please contact the author directly.

About the hints

Each hint in this tutorial can be implemented by itself without the others, but sometimes, it’s more useful if you combine them. It depends on you to decide which hint is good for your site.

Clean directory structure

Are you tired of calling a subpage of your site http://www.example.com/index.php?page=news&id=45? You could have a stylish URI in the form of http://www.example.com/news/45/. This gives better-sounding addresses, and your visitors may more easily remember your URIs. All you need is the Apache Web server or a browser in which this .htaccess file will be processed in the same way:

RewriteEngine  on
RewriteBase    /news/
RewriteRule    ^.*$    handler.php

These three lines instruct Apache to rewrite all URIs from the base directory /news/ matching the rule ^.*$ to the handler.php script.

Place this file in your newly-created /news/ directory, then create a handler.php file, which will handle all the requests beneath the /news/ tree. In other words, all URLs you request within that directory will be handled by handler.php. To get an array of “parameters” that are passed to handler.php, you can use this function:

function get_url_params( $base_url)
{
  $request = substr( $_SERVER['REQUEST_URI'], strlen( $base_url));

  if( substr( $request, -1) == '/')
    $request = substr( $request, 0, -1);

  return explode( '/', $request);
}

Use it in handler.php like the following:

get_url_params( '/news/');

You will receive an array with the parameters, which you can process as you wish. You could improve the get_url_params() function by adding code for processing a ? (and everything behind it) in the request URI.

I use this technique to get some fancy URI mapping of my Web site. It’s not any harder than using a single index.php which handles all requests, and the benefits are clearly visible. You will be able to make URLs on your Web page that don’t have to change, which is exactly what Cool URIs don’t change tells you is good practice. (This document got me into making this URI mapping system for my Web site; it’s really worth reading.)

Creating a template framework

You can use templates for outputting both static and dynamic content. You will want to create a directory in which you put the templates. You should secure this directory using this .htaccess file:

allow from none
deny from all

This will instruct Apache to deny all access to the template files directly. Access using template functions is still granted, because they’re not directly accessed.

You will now want to write a template function. Here’s what I currently use for my site:

function template_create( $template_name, $mapping = NULL)
{
  $template_data = file_get_contents( $_SERVER['DOCUMENT_ROOT'] .
    '/templates/' . $template_name . '.template');

  if( NULL != $mapping)
    return str_replace( $mapping['from'], $mapping['to'], $template_data);
  else
    return $template_data;
}

This means I have my templates in the /templates/ directory of my document root and that the files have the extension *.template (which isn’t necessary; you could name the extension of your templates as you like). If you include the $mapping parameter, this should be an array with two elements: $mapping['from'] and $mapping['to']. All occurrences of the “from” element will be replaced with the “to” element. Both elements can also be arrays, which results in all elements in the “from” array being replaced with the corresponding elements in the “to” array. Here is an example of how you could use this:

$time = time();
$text = 'This is a Test';

$mymap = array(
  'from' => array( '%%TIME%%', '%%TEXT%%'),
  'to' => array( $time, $text)
);

template_create( 'my_document', $mymap);

Where the file /templates/my_document.template could look like this:

<p>Hello. The time is %%TIME%% and here is some text:</p>
<p>%%TEXT%%</p>

You should now have seen how easy it is to create templates for pages and how to fill them with dynamic content. This is especially useful if you want to create templates for displaying dynamic data from databases and such. You can surely improve this by creating a function which reads one row from a database table and fills a mapping variable with data from that row, returning a valid mapping for the template_create() function.

Using templates for a unique layout

This is a short and easy one. Let’s say you want to create a unique layout for a page, but you don’t want to include the full code in every file or script you write. Use the templates hint above to create template functionality and include it in every subpage. Then, use it like the following (assuming header.template and footer.template include all the code for the beginning and the ending of the page):

template_create( 'header');

// place content output here

template_create( 'footer');

Yes, that’s all!

Make database access abstract

Here’s some more code for your include directory. After some time, it’s easier to make queries in this fashion than to make a mysql_query everywhere you need some data from the database. It also gives more sense to the code and makes it more readable because you just see the function call with the important parameters.

function database_get_single_element( $table_name, $key, $value);
function database_select_multiple_elements( $table_name, $from, $to,
   $order = NULL, $how = 'ASC', $key = NULL, $value = NULL);
function database_get_random_element( $table_name, $key = NULL, $value = NULL);
function database_get_column_sum( $table_name, $column, $key = NULL, $value = NULL);
function database_get_next_element( $query);
function database_count_elements( $table_name, $key = NULL, $value = NULL);

The database_get_single_element() function will select and mysql_fetch_assoc one row of the table named by $table_name. There will also be a WHERE part, and the $key field in the table must have the $value value.

The database_select_multiple_elements() will return a mysql_query of the same things. $from and $to are for the LIMIT part of the query. The data can then be fetched with database_get_next_element(), which is exactly the same as mysql_fetch_assoc, but has a more informative name.

database_get_random_element() will use the ORDER BY RAND() LIMIT 1 SQL query words to select some random element from the table.

Finally, database_count_elements() counts the number of rows of the results. This is good for counting how many elements another query will return.

These are just some hints of what I mean by database abstraction. I’m sure that you’ll probably need other functions which better suit your needs, and you might not need all the functions I’ve shown. Let me tell you from experience that it will get a lot easier when you start using these functions instead of simple queries. And if you have some very complicated queries, make a function for each of them. If your database layout changes or if you use another database instead of MySQL (which is certainly possible in PHP), you do not have to change all queries, but simply fire up your editor on the database include files and change all queries there.

Add comment October 12, 2007


Calendar

October 2007
M T W T F S S
    Nov »
1234567
891011121314
15161718192021
22232425262728
293031  

Posts by Month

Posts by Category