RE: Top 10 PHP Techniques That Will Save You Time and Effort

I realise that I already posted something today, but this seemed like an emergency…

What do you want me to do?  LEAVE?  Then they'll keep being wrong!

I thought maybe this was a serious post when I clicked on it, then when I got to number 2 on the list (I had skipped reading his post about how you should write an index page), I thought maybe he was joking, but at the end of it I realised that he was not.

1. How to Properly Create a Website Index Page
See my post about how to do it right.
[... snip]

$page = isset($_REQUEST['page']) ? $_REQUEST['page'] : 'home';
 
switch($page)
{
    case 'home':           break;
    case 'mail':           break;
    case 'contact':        break;
    default:
        $page = 'home';
}
 
include("$page.php");

[... snip]

Apparently this is the right way. I do like the single point of entry idea, and at least he is filtering the variables so you can’t load other php pages right? It really is too bad my $_COOKIE['page'] = ‘mail’… I wonder what the rest of the site is like. This also makes it a pain to add new pages, and causes a massive switch statement.

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…

No! This is wrong, the $_REQUEST array contains not only the $_POST and $_GET variable contents but it also contains the contents of the $_COOKIE array. The arrays are merged in the order described by your php.ini file, generally $_GET, $_POST, $_COOKIE but not always. So, use the $_POST variable when you mean for it to come from the $_POST variable, use the $_GET for get variables, and the $_COOKIE for things in the cookie. Don’t take the lazy way out.

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…

Wrong again. var_dump simply tells you what is in whatever object/array/whatever you are var_dumping. The xdebug extension is a much better alternative:


The Xdebug extension helps you debugging your script by providing a lot of valuable debug information. The debug information that Xdebug can provide includes the following:

* stack traces and function traces in error messages with:
o full parameter display for user defined functions
o function name, file name and line indications
o support for member functions
* memory allocation
* protection for infinite recursions

Xdebug also provides:

* profiling information for PHP scripts
* code coverage analysis
* capabilities to debug your scripts interactively with a debug client

http://xdebug.org/

4. PHP Handles The Code Logic, Smarty Handles The Presentation
… Learn to use smarty as a template engine for your websites, it will pay off, i promise.

While I am not advocating combining “Code Logic” and “Presentation”, there are much better tools out there than Smarty. Smarty is a horrid piece of archaic spaghetti that had it’s purpose a long time ago, but no longer really does. Or you could learn to separate the presentation from the logic by using one of the myriads of frameworks out there. You could even go one better by separating it out to use the MVC pattern.

5. When You Absolutely Need Global Values, Create a Config File
… 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.

Actually… this one isn’t bad, polluting the global namespace is something you should try to avoid, and keeping all of your config values in one place makes them easy to find.

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.

This goes back to #1, a horrible way to make an index page.

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.

He then goes on to suggest you make a dbExec($query) function which calls $this->db->exec($query), and a sanitize($var1, $var2…) function which will not actually sanitize the input (it appears to just be making sure the input is numeric?). In his examples he is using the PEAR classes for his database abstraction, which already does this… so I am not sure what the point of putting a database abstraction ontop of a database abstraction is here. Also, use the escape functions that are already given to you by php (or the pear library so that your code is portable across database backends), do not write your own, you will get it wrong.

8. A php File Handles Input, a class.php File Handles Functionality
[...] The php file gets any input that we need and then redirects execution to a function residing to the class file. [...]

It almost seems like he is implementing a poorman’s MVC? I think? Mostly? A much better way would be to actually use an MVC framework (or to look at a tutorial online and see a much better way to do it).

9. Know Your SQL and Always Sanitize
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;
   }

The message is the right one. Sanitize your input. However, it would be awesome if he used some coding standards for naming his variables $user and $pm_table are both tables apparently. The well named function sanitizeInput should probably be renamed to checkInt or something similar since that is what it appears to do. He should also probably not be putting his variables straight in the string, to make it easier to change the query later on when he realises that he missed something. Don’t even get me started on the fact that this function is private and presumably extends his database abstraction class…

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.
[..snip...]

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

[.../snip...]

The singleton pattern: you’re doing it wrong.

This is not actually a singleton pattern, while yes it lets you get the instance that you created earlier, you can still create the object by normal means, so I could have $GLOBALS['config']['SmartyObj'], $GLOBALS['config']['SmartyObj2'], $GLOBALS['config']['SmartyObj3'] which would all be instances of the smarty object, but they can all have different properties and values. If it were a singleton this would not be the case. The proper way of doing this is to use the pattern described in the php.net manual under Patterns Singleton. That way it is always the same object everywhere that you use it, and you do not have to muck around with the $GLOBALS array (which I am pretty sure is a code smell…).

Read his full post here. If you think I may have been too harsh, or not harsh enough, on him, leave a comment.


Related posts:

  1. Dynamic Images with PHP
  2. PHP Functions, you’re doing it wrong…
  3. Documenting PHP Code
  4. Why implement PHP in Java?
  5. Exceptions Are Not For Flow Control

Tags: , , , , , , , , , , , , , , , ,

  • Ajaxmonk

    Just curios. What does all of your index pages look like?

  • Prabhchahal21

    i like it so much

  • Pingback: An alternative to Poor Man’s MVC in PHP · Squirrel Hacker

  • Pingback: uberVU - social comments

  • http://www.reflectiv.net cx42net

    I was hoping his post was an easter egg, but regarding to his comments, it’s not.

    The sad point is that he’s sure to be right while is not.

    The main problem is that most of the tutorials you can find are the old ones from 10 years ago but so many changes was made since.

    For example, searching “php database” or something similar on google, and the first links you’ll find is about mysql_*.

    Hey ! Where is PDO ?! Where are the ORM indications ?

    How can a beginner find out about these if google is not helping him/her ?

    • http://blog.seanja.com/ SeanJA

      True, I tend to look to stackoverflow/github for inspiration on those matters. The problem is he is spouting good ‘habits’ from the 90s like they are still a good idea.

  • Pingback: 網站製作學習誌 » [Web] 連結分享

  • http://zoeandgavin.com zoe

    Hah! Sean, when I first saw that XKCD comic, I thought of you.

    • http://blog.seanja.com/ SeanJA

      I totally did that last night too

  • Aziz Light

    You stole this article from another blog…it was first released a couple days ago.

    It sucked before and still sucks now. Terrible article…

    • Aziz Light

      actually, hasty answer, sorry about that. The article you supposedly “stole is actually the object of this post”. The original post sucked, this post is just pointless…

      • http://blog.seanja.com/ SeanJA

        Yes, yes it is, hence the RE: part of the title, no problem though ;)

      • http://blog.seanja.com/ SeanJA

        That is where our opinions differ, in this post I am trying to fix the mess he has made for new PHP programmers by pointing out that he is mostly wrong.

    • http://blog.seanja.com/ SeanJA

      I like to think that my article vastly improves on the original, mostly because it points out that the original sucks.

  • http://giorgiosironi.blogspot.com/ Giorgio Sironi

    For 3: debugging sucks, testing rocks. :)

  • http://www.maca134.co.uk Macca

    Nice!!

  • Denny

    Perhaps you could make a tutorial showing the right way to make an index file. While a lot of what the original post contained looked wrong to me, the stuff on index pages largely matches what I’ve been doing.

    • http://whitebot.com Mike

      I’m also curious as to a better or preferred method for the index page. I’ve done this in the past (not with $_REQUEST however). Aside from the potentially long switch (which wasn’t an issue the times I’ve used it) what other problems to you foresee with it?

      Nice clean up BTW.

  • http://blog.paulbouzakis.com Paul

    Thank you Thank you Thank you! I thought I was going crazy when I read that blog post… I agree with every one of your responses. It’s a shame how that post, while probably having good intentions, will corrupt a bunch of young php programmers.

  • http://www.marcusk.co.uk Marcus Kielly

    I have to say, I thought the same when I read it. Your comments about poor man’s MVC hit the nail on the head. To be fair, MVC might be a bit heavweight for a simple 5 page brochure site – in which case some of the advice is ok – but then again, if that was the case, why bring Smarty into play?
    Good post

  • http://www.kristopherwilson.com Kristopher

    A puked a little in my mouth when I read his code.

  • bgd

    Wow, his comments on his own post are mind-boggling. He really seems clueless, doesn’t he? Good fun, though, in reading that…

  • http://--- Wolfgang

    Well,

    your much more right than the guy/girl before!
    He/She did a lot of beginner mistakes.

    W.F.

  • Vlad

    Thx for this … I barely contained myself from filling the guy’s comment form with curse words when i saw what he wrote.

  • http://www.craigfrancis.co.uk/ Craig Francis

    With your comment “The singleton pattern: you’re doing it wrong”.

    I have been wondring if this is always the case… take for example a “config” object:

    —-

    class config {

    private $store = array();

    final private function __construct() {
    // Being private prevents direct creation of object.
    }

    final private function __clone() {
    trigger_error(‘Clone of config object is not allowed.’, E_USER_ERROR);
    }

    final private static function get_instance() {
    static $instance = NULL;
    if (!$instance) {
    $instance = new config();
    }
    return $instance;
    }

    final public static function set($variable, $value = NULL) {
    $obj = config::get_instance();
    if (is_array($variable) && $value === NULL) {
    $obj->store = array_merge($obj->store, $variable);
    } else {
    $obj->store[$variable] = $value;
    }
    }

    final public static function get($variable, $default = NULL) {
    $obj = config::get_instance();
    if (isset($obj->store[$variable])) {
    return $obj->store[$variable];
    } else {
    return $default;
    }
    }

    }

    —-

    This allows the site to just use config::set(‘my_config’, ‘my_value’), and call the respective get method when required, without creating an instance of the config object all the time, or trying to keep one instance assigned to a variable which is always in scope (e.g. $this->config->get()).

    And I’ve been wondering if this is the right approach… I keep seeing comments that the singleton pattern is bad, but no-one really explores the issue well enough (in my opinion) to justify an outright ban… but likewise, if the singleton pattern is so bad, what is the alternative?

    One thing to keep in mind is that the less characters needed to access the config, the better, as its used enough times that it should be easy to use (from a typing point of view).

    • http://blog.seanja.com/ SeanJA

      Well, his ‘singleton’ pattern was just to pull the object out of the $GLOBALS array.

      I take the view that any pattern is good or bad based on how you use it, I do use it for my $config object in my small framework, which seems to make sense in this case because there should only be one configuration for one site. I am not sure about any other really good uses for it to be honest. It is possible his smarty one is correct if he were to actually use the singleton pattern because if you assign a bunch of variables in one class, then display in another, your variables are gone.

    • http://www.satya-weblog.com Satya Prakash

      This code seems useful.

  • Pingback: Are you open to learning from others? – Aaron McGowan

  • http://www.amcgowan.ca Aaron McGowan

    Well said!

    • http://blog.seanja.com/ SeanJA

      Thank you.

      side note: What? No gravatar?