Posted March 28, 2010 by Spyros in PHP Programming
 
 

Top 10 PHP Techniques That Will Save You Time and Effort

makes_eat_time
makes_eat_time

What would happen if you tried to use a mirror as a surfboard ? Well, you may succeed in taming the waves for a little while, or even a big while, but deep inside, you know that this is not really the right way to do it. Weird as it may sound, the same principals apply to php programming. I’ve heard of people trying to learn PHP by studying it for like a weekend or more, but allow me to say, this is a pretty bad approach to learning this programming language.

Why is The Learning PHP Process Different Than Any Other Programming Language ?

By nature, PHP is all about knowing what to do. If you have the knowledge on how to do something in PHP, actually doing it is most of the times really really easy. I would actually pay to know some of these things beforehand. In PHP, doing things the way you think them will most probably result in doing them the wrong way. Not because you’re a bad programmer, but because there are some standard tricks of the trade that you cannot really avoid using, if you want to write good and maintanable code. Let’s talk about these 10 techniques that you really need to know about :

1. How to Properly Create a Website Index Page

Creating your website index page is the first thing to do for every website that you create. I’ve actually created a post that will help you properly create a website index page.

2. Use the Request Global Array to Grab Data

There is actually no reason to use $_GET and $_POST arrays to grab values. $_REQUEST, is another global array that fetches you either a get or form request. Therefore, it’s most times more convenient to use something like this to parse data :

$action = isset($_REQUEST['action']) ? $_REQUEST['action'] : 0;

3. Debugging PHP is About var_dump

If you’re looking for php debugging techniques, i have to say that var_dump is most times the way to go about it. This command is all you need to echo php information. There shouldn’t really be many cases where you need anything more than dumping values in PHP, in order to debug your code.

4. PHP Handles The Code Logic, Smarty Handles The Presentation

I think i’ve said this many times before, but Smarty usage (or other template system), is critical for creating organized PHP code. Learn to use smarty as a template engine for your websites, it will pay off, i promise.

5. When You Absolutely Need Global Values, Create a Config File

It is a bad practice to create global values for everything. There are limited cases where you would actually need to do so. Doing it for database tables or database connection information is a good idea, but do not use global variables throughout your PHP code. Moreover, it is always a better idea to keep your global variables at a single config.php file.

6. If NOT Defined, Access Denied !

If you’re creating your pages the correct way, there will absolutely no reason for anybody to access any other php page other than index.php or home.php. The idea is that once index.php is accessed, you utilize get variables in order to open the needed pages. Your index page should contain something like :

define('yourPage',1);

Then, your other pages should contain this :

if (!defined('yourPage')) die('Access Denied');

What this does, is preventing direct access to your other php pages. Therefore, any user who tries to access your other web pages, not through index.php, gets an “Access Denied” message.

7. Create a Database Class

If you’re doing database programming (pretty common in PHP), it would be a very good idea to create a database class to handle any database management functions. A good way to do it is by creating functions like :


    public function dbExec($query)
    {
        $result = $this->db->exec($query);
        if (PEAR::isError($result))
            errorRedirect($result->getMessage(), true);
        else
            return $result;
    }

This is an example function from an actual project i’m creating. This one just receives a query and executes it. It also handles any errors that may occur. You could also include sanitization code here, but i prefer to do it using a sanitization function like :


	// checks if arguments given are integer values not less than 0 - has multiple arguments
	function sanitizeInput()
	{
		$numargs = func_num_args();
	    $arg_list = func_get_args();

	    for ($i = 0; $i < $numargs; $i++) {
			if (!is_numeric($arg_list[$i]) || $arg_list[$i] < 0)
	            errorRedirect("Unexpected variable value", true);
	    }
	}

8. A php File Handles Input, a class.php File Handles Functionality

It is pretty important that you learn not to mess the code that retrieves user input and redirects it to any functions, with those actual functions. The idea is pretty simple. The php file gets any input that we need and then redirects execution to a function residing to the class file. For example, let’s suppose that a url is like “index.php?page=profile&action=display”. The profile.php file retrieves the url and gets that action is “display”. Then, using a simple switch, we execute the actual display function like :


require_once PROJECTROOT.'libs/messages.class.php';

$message = new Message();

switch ($action)
{
    case 'display':
        $message->display();
        break;

...

Again, this is part of a project that i create. You see that i include the messages class and then initiate the switch check. $message is just an object that is used to call functions inside the class.

9. Know Your SQL and Always Sanitize

As i mentioned before, a database is 99% of times important for any php created website. Therefore, you need to know many things about how to use sql properly. Learn to combine tables and more advanced techniques. I promise there will be mysql tutorials soon in codercaste.com. Let me present you an example of a function that uses mySQL and sanitazes using the function seen on point #7 :


    private function getSentMessages($id)
    {
	$this->util->sanitizeInput($id);

        $pm_table = $GLOBALS['config']['privateMsg'];
	$users = $GLOBALS['config']['users'];

        $sql = "SELECT PM.*, USR.username as name_sender FROM $pm_table PM, $users USR
		    WHERE id_sender = '$id' AND sender_purge = FALSE AND USR.id = PM.id_receiver AND is_read = TRUE
		    ORDER BY date_sent DESC";
	$result = $this->dbQueryAll($sql);

        return $result;
    }

At first, we sanitize the user input (the message id at this point, that is passed through a GET variable) and then we execute our sql command. Notice the usage of sql here. You need to learn how to use aliases and combine tables.

10. When You Need Just an Object, Use a Singleton Pattern

It happens pretty often in PHP that we just need a single object created one time and then used globally throughout our whole program. A good example of this is the smarty variable that has to be initialized once and then is used all over the place. A good way to do that is a Singleton pattern, where an object is just created once and for all. The way to do this is like :


    function smartyObject()
    {
        if ($GLOBALS['config']['SmartyObj'] == 0)
        {
            $smarty = new SmartyGame();
            $GLOBALS['config']['SmartyObj'] = $smarty;
        }
        else
            $smarty = $GLOBALS['config']['SmartyObj'];
        return $smarty;
    }

Notice that we have a global smarty variable (initialized in config.php in example) and if it equals 0, we go about creating a new smarty object. If not, it means that the object is already created and we just need to return it.

Hope these 10 techniques are as helpful to you as they are for me and i would really like to listen to what you think is your most important PHP technique.


Spyros