View RSS Feed

traq

Before You Start: the basics, for PHP in particular and for programming in general

Rating: 31 votes, 4.81 average.
I wanted to take a few moments to talk about some of "the basics" that are all-to-often glossed over...

A Matter of Style

In general, I find that most PHP programmers fall into one of three main programming styles:
  • procedural: a simple ordered set of instructions, nested if's/ else's, etc.
  • functional: functions are little code containers that you can call on when needed. You [usually] give them arguments, they [usually] return values to you.
  • object-oriented: objects wrap up a set of functions and related information (properties) to represent a complete "thing" in your program. You have whatever objects you need, and you manipulate them using their methods (functions).


I'm a big fan of Object-Oriented Programming. Objects are very flexible and allow you to do things you'd never have thought possible otherwise. Even for tasks that could be accomplished without Objects, OOP is really cool and builds lots of good programming habits.

There's style, and then there's Style.

When it comes to writing your program, how you do it is important.

  • Use a good plain text editor with (at a minimum) syntax highlighting. Some recommendations:

    Microsoft Word is not a good choice for programming. Less obviously, programs like DreamWeaver and FrontPage often produce buggy, poor-performing sites. Quite simply, they're made for people who don't know what they're doing: you sacrifice control and quality for convenience.
    .
  • Format your code. You're not "wasting space" by indenting your code. You're not "slowing down the program" by adding comments. You're not being an "eLiTe haX0r" by writing code so "clever" that no one has any hope of deciphering it later.

Compare:
Code:
    function find( $find,$val=null )
{
$recurse = function( $obj )use( &$prop,$val,&$recurse )
{
              $p = array_shift( $prop ); return isset( $obj->$p )? empty( $prop )? is_null( $val )? true: ($obj->$p === $val): $recurse( $obj->$p ): false;
};
   foreach( $this as $obj )
{ $prop = strpos( $find,'.' )? explode( '.',$find ): (array)$find;
if( $recurse( $obj ) )
{ return $obj; 
}
}return false;          
}
PHP Code:
/**
 * searches storage for an object containing property $find; optionally with value === $val
 * @param string $find              name of property to find (in the form `object.property`)
 * @param mixed $val                value to match property against
 * @returns bool|object             object if match found; false otherwise
 */
function find$find,$val=null ){
    
    
/** closure bool            recurses through an object->property chain to search for property. */
    
$recurse = function( $obj )use( &$prop,$val,&$recurse ){
        
$p array_shift$prop );
        return isset( 
$obj->$p )?
            empty( 
$prop )?
                
is_null$val )?
                    
true:
                    (
$obj->$p === $val):
                
$recurse$obj->$p ):
            
false
        
;
    };
    
    
# search stored objects for matching property [& value]; return if found
    
foreach( $this as $obj ){
        
// parse property chain
        
$prop strpos$find,'.' )? explode'.',$find ): (array)$find;
        
// recurse
        
if( $recurse$obj ) ){ return $obj; }
    }
    
    
# no matches found
    
return false;

Take it to heart.

Server Set-Up

I'm running PHP version 5.4. You should too. It's fantastic.

However, there's nothing wrong with version 5.3. It came out in 2009, so there's no excuse to not have some release of it. If you're still on 5.2, you really need to upgrade. If your web host doesn't offer 5.3+, you should be looking for a new host.

Edit: I know many people are stuck with older codebases.
5.2 is "okay," if you're not in a position to leave it behind. But your goal should be to upgrade.


If you don't have 5.4, check these settings in your php.ini file. Make sure:
  • safe mode is turned OFF
  • register_globals is turned OFF
  • register_long_arrays is turned OFF
  • magic_quotes_gpc is turned OFF

These things aren't safe at all (no, not even safe mode). They cause problems. Don't use them.
(Talk to your web host.)

Fun and Games and Error Messages

We should have a brief word about development vs. production:
  1. development is when you are writing and testing your code.
    .
    When you're in development, you want to see every last error message. You want your program to crash and burn at every little bump in the road. You want PHP to complain endlessly about absolutely everything.
    .
    Why? ...why indeed.
    .
  2. production is when you put your code up on your website for all to see.
    .
    When you're in production, it's completely different. If there's a problem, you want to hide it at all costs.
    .
    Error messages? NO!
    If it's so bad a problem that you can't recover, blame the dinosaurs - not your program. No one "hacks" dinosaurs. But if you mention that something went wrong because {function} couldn't connect to {host} on {socket} with {username} and {variable} had an unexpected {value}, you can bet someone, somewhere, will start hacking away .


In the spirit of Development, use these settings in your php.ini file:
Code:
error_reporting = E_ALL & E_STRICT
display_errors = On
display_startup_errors = On
You can also do this at the top of your script:
PHP Code:
<?php
error_reporting
( -);
ini_set'display_errors','On' );
However, it's not as useful, and it won't always work. : (

Remember, in Production, both display_errors and display_startup_errors should be Off.

I Did Everything Right and My Code Still Broke

This is not unusual.
(Everyone thinks they did everything right.)
No, I believe you.
Really.

Situation #1

Something is wrong with your code. You're getting all kinds of crazy error messages. They say obscure things like
Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM, expecting ')' in ...
or
Warning: [function.session-start]: Cannot send session cache limiter - headers already sent ...
Don't Panic.

Error messages are your friends.

Quite often, they are simply the result of typos. Just read the message - it tells you exactly what's wrong. If you don't understand something in the message, google it. You're all big boys and girls; you're allowed to use the internet on your own.

If the problem is not obvious, and the 'net fails you, then sit back and take a good look at your code. Start at the line number the error message gave you, and work backwards. (There's a fundamental truth to be uncovered here: PHP doesn't actually know where the problem was caused; it knows only where the problem got unfixable.)

For example:
Parse error: syntax error, unexpected 'print' (T_PRINT) ...on line 2
Code:
2 >   print "hello";
That looks fine, right? Hint: back up.
Code:
1 >   some_function( 'this does cool stuff' )  // <---WHUP NO CLOSING SEMICOLON
problem solved.

Situation #2:

Something is wrong with your code. You're not getting any error messages at all. But your webpage says "Vote For The Cutest Kitten" AND THERES ABSOLUTELY NO CATS ANYWHERE. Maybe there is no error - maybe what you wrote just doesn't do what you expected.

Don't Panic.

This is where version control come into play. "Undo" is just not good enough when it comes to managing your code. Ya know how people tell ya, "backup your files"? If you don't want to get into using version control systems,* like subversion or git, you need to at least make it a habit to "backup your files" every time you make a significant change. I don't mean having several copies of the latest version - you should be able to "revert" to any of the last two or three working versions of your scripts.

*Yes, I said "if you want to." There are people who will be mad at me because I didn't say you have to. However, I will say that, if you're doing anything more than "messing around," you really, really should be using a VCS. It's well worth it.

Where Do We Go From Here?

We're going to build a Web App. All kinds of bells and whistles and shiney stuff. Coming soon to a blog near you. Look for it.

PAQ,
- Adrian

Submit "Before You Start: the basics, for PHP in particular and for programming in general" to del.icio.us Submit "Before You Start: the basics, for PHP in particular and for programming in general" to StumbleUpon Submit "Before You Start: the basics, for PHP in particular and for programming in general" to Google Submit "Before You Start: the basics, for PHP in particular and for programming in general" to Digg

Updated 12-17-2012 at 03:49 AM by traq

Categories
PHP coding

Comments

  1. Beverleyh's Avatar
    You got me traq. I need to straighten out my methods, cos some aren't pretty.

    I'm sitting here waiting with my chewed pencil, notepad (the paper and digital kind) and cup of tea in hand.

    Any ETA? - my tea's getting cold
  2. traq's Avatar
    It's gonna be a big one, so it might take a few weeks. But I'm workin' on it, trust me!
  3. Beverleyh's Avatar
    No worries. I'll be patient

    Don't forget to make time for all those Chrimbo films that'll be gracing our TVs soon! Glitter, grog and goodwill - Fantastic!