Categories


Archives


Recent Posts


Categories


PHP Patterns in Magento

astorm

Frustrated by Magento? Then you’ll love Commerce Bug, the must have debugging extension for anyone using Magento. Whether you’re just starting out or you’re a seasoned pro, Commerce Bug will save you and your team hours everyday. Grab a copy and start working with Magento instead of against it.

Updated for Magento 2! No Frills Magento Layout is the only Magento front end book you'll ever need. Get your copy today!

In many programming languages, especially the less strictly typed ones, a common coding pattern starts to emerge.

$thing = $this->getSomeThing();
if($thing)
{
    //do something with the thing
}

Without a compiler to catch methods returning what they shouldn’t, a developer is forced to sanity check return values from methods before doing anything. This happens in the Magento core code, but you’ll often see it written like this

if($thing = $this->getSomeThing())
{
    //do something with the thing
}

Whaaaaaaat? Most programmers know about the “I used an assignment operator (=) when I meant to use a comparison operator (==) bug, but some aren’t familiar with deliberately doing this.

Try running the following PHP code

var_dump( ($test = "hi there") );
var_dump( ($test = false) );

Here we’re dumping the results of an assignment.

Your output will be something like

string(8) "hi there"
bool(false)

When you perform an assignment in PHP, it’s actually an expression, and has a return value. Its return value is whatever ends up on the left side of the assignment operator. In other words, whatever you’re putting into the variable will be returned.

So, by deliberately doing this

if($thing = $this->getSomeThing())
{
    //do something with the thing
}

a programmer saves a line of code.

If you’re never encountered this pattern before, it can add to mental overhead of understanding a code base (Magento included). You’ll scan code, and often skip over an important method call that does something because you’ve mentally mapped a conditional statement to "oh, that’s just a check” in your head.

Keep an eye out for it!

Copyright © Alan Storm 1975 – 2019 All Rights Reserved

Originally Posted: 18th June 2011