Php Idioms

Error Handling

or die() on failure

Many resource-based functions in PhpLanguage, (such as fopen, or mysql_connect, where you will see this idiom the most) will return a boolean, or a resource, which means that the following code is perfectly valid:

mysql_connect('myserv','myuser','mypass') or die("It's barsted!");
The above is evaluated to an expression, and the way the Zend engine works, if the first part of the expression is true (mysql_connect, or fopen, or whatever), then the entire expression must be true, so it doesn't evaluate the second half.

[or die() on failure is a Perl idiom which found its way into PHP.]

This is more of an AntiPattern than anything else. Any script that is more then just the barest minimum has some cleaning up to do, if nothing else to close any open HyperTextMarkupLanguage tags. Just output a '>' in your die() then. NetscapeNavigator used to do the same thing in its '> Connection interrupted' messages

At the very least, you could wrap the function in an if-else block...

if (!mysql_connect('myserv','myuser','mypass'))
{
handleDatabaseError();  // User defined function to handle the database 
}// error by emailing it, or printing it
else
{
...
}
While this solution is better, and allows for proper cleanup, you will probably run into the ArrowAntiPattern quickly.

A better solution would then be to write an abstraction library, either procedural or OO (whichever you are comfortable with), and use that instead.

if ($result = getDbInfo())
{
... display the db info here, using templating of course! ;)
}
else
{
... print an I'm sorry message here ...
}

function getDbInfo() { mysql_connect('serv','user','pass') or return false; // or wrap in an if block mysql_select_db('mydb') or return false; $r = mysql_query("Select Lots,Of,Stuff from myTable where complexQuery='foo'"); if (!$r) { return false; } ... }
This example of course is a little contrived.

With the advent of PHP5, this will become less of an issue, because you can throw and catch exceptions. This, of course will probably mean that there will be PHP versions of most of the Exception Based JavaIdioms.

I generally make my own database functions similar to:

 $connection = dbConnect($connectInfoEtc, handleFail=True, failMessage="Error doing foo");

This (optionally) tells it to handle the failure on its own and display the given message (or default message if not given). Actually, handleFail=True may be the default if that's what works best for the app. If handleFail=False, then the error is tossed back to the caller (depending on the language). The problem is that Php doesn't have direct named parameters. In most cases, there is no need to clutter up database work with error handling. I like to keep the main logic only doing mostly domain stuff, not nitty gritty mechanics of error handling.


Constant Value as First operand in Conditional (this could stand a rename.) aka CompareConstantsFromTheLeft

The assignment operator (=) is easily confused with the equality (==) conditional. Thus, one can find code like:

if ($myFoo = 23)
instead of:
if ($myFoo == 23)
Therefore, switch the order of your operands in the conditional expression, so your constant value (23) comes first. That way when the interpreter hits (23 = $myFoo), it will complain that it cannot assign to a constant value. This works equally as well with functions. if (myDecomposedConditional($args) == $myFoo)

This is also one of the CeeIdioms/CeePlusPlusIdioms.

No, actually, it isn't. Why is somebody going about scattering this falsehood everywhere? PersonalChoiceElevatedToMoralImperative.

It's in every Beginning C book. It's in a number of coding standards (https://www.securecoding.cert.org/confluence/display/seccode/EXP21-C.+Place+constants+on+the+left+of+equality+comparisons). I see it in code all the time. Just because you don't do something doesn't make it not idiomiatic. PersonalChoiceElevatedToMoralImperative.


Test for null as default value in function

Default values in function parameters can't be the result of a function in PHP. You can't do:

    function my_func($param=other_func()) {
        ...
    }
What you can do is:
    function my_func($param=NULL) {
        if (NULL == $param) {
            $param = other_func();
        }

... }


EditHint: If there is enough interest, the idioms will eventually be refactored into their own pages, but for now, all on one page is TheSimplestThingThatCouldPossiblyWork.

Idiom definitions should be brief by their very nature. If it takes a whole page to describe a concept then it really isn't idiomatic, is it?


CategoryPhp


EditText of this page (last edited November 11, 2013) or FindPage with title or text search