This tutorial is split among three sections in this post. This is how the tutorial is organized:
- What is programming efficiency?
- Improving your code
- Beginning to separate code from design
- Error handling
1. What is programming efficiency?
Programming efficiency is optimizing your code and minimizing the amount of work you have to do while coding. This is achieved by creating functions and methods for code used frequently throughout your scripts. A common technique used in PHP is to use it's include() and require() functions to include a header and footer in a content page to make layout and design changes easy. In this tutorial, I will be covering code optimization and organization, error handling, and beginning to separate code from the layout and design.
2. Improving your code
Often while programming, you will notice that you may be using a certain part of your code over and over again. Rather than doing that, it would be more efficient to create a function to do that process for you and just call that function; when changes need to be made to that process, they can be made in just one place.
Let's say you have a web site that you sell products with. You have a select box that is used by the user for selecting what quantity of an item to add to their cart. Rather than putting that code on every page, we can just call this simple function:
PHP Code:
<?php
// quantity_select_box() - creates a select box of quantities
//
// $product_id => (Int) Product ID of the quantity we want
// $selected => (Int) The quantity that's selected
// $include_zero => (Bool) Whether to include zero as an option value
//
function qty_select($product_id, $selected = false, $include_zero = false)
{
$sql = "SELECT quantity
FROM products_table
WHERE product_id = '$product_id'";
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
// Is the product is out of stock?
if (!$row['quantity'])
{
return false;
}
$quantity_list = '';
for ($i = (($include_zero) ? 0 : 1); $i <= $row['quantity']; $i++)
{
$selected = ($select_id == $i) ? ' selected="selected"' : '';
$quantity_list .= '<option value="' . $i . '"' . $selected . '>' . $i . '</option>';
}
return $quantity_list;
}
// The function would be called like so:
//
$qty_select = qty_select(2);
echo ($qty_select) ? '<select name="qty">' . $qty_select . '</select>' : 'Out of stock';
?>
See how a very simple function can save you a lot of time?
3. Beginning to separate code from design
One thing many PHP programmers hate is how confusing it is to mix PHP code within HTML, so let's separate it, shall we? The first thing we must do is create a header and footer for your web site, which is common HTML code used for your layout that is outputted before and after the content of each page. We are going to this with functions:
functions.php
PHP Code:
<?php
function page_header($page_title)
{
define('HEADER_INC', true);
$site_name = 'Your web site';
$file = file_get_contents('templates/header.html');
eval('echo "' . addslashes($file) . '";');
}
function page_footer()
{
$u_home = 'index.php';
$file = file_get_contents('templates/footer.html');
eval('echo "' . addslashes($file) . '";');
exit;
}
?>
TEMPLATES
PHP Code:
<!--
templates/header.html
-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" dir="ltr">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-15" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<title>{$site_name} > {$page_title}</title>
</head>
<body>
<table border="0" style="width: 75%" cellspacing="0" cellpadding="0">
<tr>
<td style="background: #6CA6ED">{$page_title}</td>
</tr>
<tr>
<td style="height: 400px">
<!--
templates/footer.html
-->
</td>
</tr>
<tr>
<td style="background: #6CA6ED; text-align: right"><a href="{$u_home}">Back to home</a></td>
</tr>
</table>
</body>
</html>
<!--
templates/index.html
-->
<p>{$content}</p>
<b>Extra content:</b><br />
{$extra}
Using it in a live page:
PHP Code:
<?php
include('functions.php');
page_header('Test page');
$content = 'Some page content goes here.';
$extra = 'Blah blah blah';
$file = file_get_contents('templates/index.html');
eval('echo "' . addslashes($file) . '";');
page_footer();
?>
4. Error handling
When there is an error in your PHP code , you are shown a white screen with only PHP's error message (depending on the error). However, we can change that. We can use PHP's built-in set_error_handler() function to create our own error handler. This can be used not only to show error messages that are more pleasing to the eye, but also send error information to an email address or store it in a database. Below is a sample of how to make your own error handler (
Note: this makes use of the templating done in the previous section):
PHP Code:
<?php
set_error_handler('msg_handler');
// Credits to phpBB
function msg_handler($errno, $msg_text, $errfile, $errline)
{
switch ($errno)
{
case E_NOTICE:
case E_WARNING:
// These low-level errors will not disrupt your template, so no header or footer are required as they will output at the top of the page
echo "<b>PHP Notice</b>: in file <b>$errfile</b> on line <b>$errline</b>: <b>$msg_text</b><br>";
break;
case E_USER_ERROR:
// Include a lite template here with the error message since this error could mean something important went wrong
exit;
break;
case E_USER_NOTICE:
// A small error that can be placed within the content of your web site
if (!defined('HEADER_INC'))
{
page_header();
}
// Output message here
page_footer();
exit;
break;
default:
echo "<b>Another Error</b>: in file <b>$errfile</b> on line <b>$errline</b>: <b>$msg_text</b><br>";
break;
}
}
?>
To call an error your self, you would have to make use of PHP's trigger_error() function. Why would you want to do this? Consider that a user does not have permission to visit a certain page, you would use the following code to have your error handler help you:
PHP Code:
<?php
if (!$auth)
{
// This will call the E_USER_NOTICE error
trigger_error('You do not have permission to access this page.');
}
// To call a different type of error, you would do it like this:
trigger_error('You do not have permission to access this page.', E_USER_ERROR);
?>
Easier than you thought, huh?
Hope this was helpful! As always, leave comments and suggestions, and feel free to point out my mistakes as we are all here to help each other.