Web Developers Forum & SEO Help
Web Developers ForumArticlesBlogLinks
topmenu

Programming and Scripts: Web Developers Forum

Go Back   TalkWebDev: Web Developers Forum for Web Designers & SEO Information > Web Development > Programming and Scripts
User Name
Password


Reply
 
Thread Tools Search this Thread
Old 06-09-2005, 02:42 AM   #1
Purple Haze
TalkWebDev Enthusiast
 
Join Date: Mar 2005
Posts: 37

Default Tutorial > PHP > Programming efficiency

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) ? 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} &gt; {$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.
__________________
Sticky Icky
Purple Haze is offline   Reply With Quote
Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Mastering Regular Expressions in PHP Lars Programming 0 04-12-2005 11:13 PM
Pre-made script > PHP > Displaying Database Information Purple Haze Programming and Scripts 6 04-11-2005 10:00 PM
Tutorial > PHP/MySQL > Creating a simple member system Purple Haze Programming and Scripts 0 04-06-2005 02:47 AM
Tutorial > XHTML > Images Purple Haze The Basics 6 03-29-2005 04:16 PM
php mysql tutorials Hoju Programming and Scripts 5 03-18-2005 04:45 PM


All times are GMT. The time now is 05:59 PM.

Powered by: vBulletin Version 3.0.7
Copyright ©2000 - 2012, Jelsoft Enterprises Ltd.

 
Admin CP Mod CP About Us Contact Us Top