Generated Magento Model Code

Like this article? 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.

This is a quick one for advanced users, and was inspired by a recent question I answered over at StackOverflow.

One of the nice things about a well abstracted system like Magento is the opportunities it presents for meta-programming. Drop the following code in a controller action (yes, you can define an inner function in PHP)

function someAction()
        header('Content-Type: text/plain');
        $coupon = Mage::getModel('salesrule/rule')->load(1);        

        function outputValue($value)
                case 'string':
                    echo "'".str_replace("'","\\'",$value)."'";
                case 'array':
                    echo "array(";
                    foreach($value as $v)
                        echo ",";
                    echo ")";
                case 'NULL':
                    echo 'NULL';
                    echo "'can\'t handle ".gettype($value)."'";


        echo '$model';
        foreach($coupon->getData() as $key=>$value)

            echo '->set';
            echo str_replace(' ', '',ucwords(str_replace('_', ' ', $key)));
            echo '(';

            echo ')';
            echo "\n";


Run this code and you’ll get some auto-generated code for the creation/updating of a Magento salesrule/rule Model (assuming you have a Model with an id of 1)

Originally published May 10, 2010