Magento Themes and Magento Extensions

Generated Magento Model Code

Share

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)
        {
            switch(gettype($value))
            {
                case 'string':
                    echo "'".str_replace("'","\\'",$value)."'";
                    break;
                case 'array':
                    echo "array(";
                    foreach($value as $v)
                    {
                        outputValue($v);
                        echo ",";
                    }
                    echo ")";
                    break;
                case 'NULL':
                    echo 'NULL';
                    break;
                default:
                    echo "'can\'t handle ".gettype($value)."'";
            }

        }       

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

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

            outputValue($value);
            echo ')';
            echo "\n";
        }

        exit;
}

Run this code and you’ll get some auto-generated code for the creation/updating of a Magentosalesrule/

rule Model (assuming you have a Model with an id of 1)

$model->setRuleId('1')
->setName('test')
->setDescription('')
->setFromDate('2010-05-09')
->setToDate(NULL)
->setCouponCode('')
->setUsesPerCoupon('0')
->setUsesPerCustomer('0')
->setCustomerGroupIds(array('1',))
->setIsActive('1')
->setConditionsSerialized('a:6:{s:4:"type";s:32:"salesrule/rule_condition_combine";s:9:
"attribute";N;s:8:"operator";N;s:5:"value";s:1:"1";s:18:"is_value_processed";N;s:10:"aggregator";s:3:"all";}')
->setActionsSerialized('a:6:{s:4:"type";s:40:"salesrule/rule_condition_product_combine";s:9:"attribute";N;s:8:
"operator";N;s:5:"value";s:1:"1";s:18:"is_value_processed";N;s:10:"aggregator";s:3:"all";}')
->setStopRulesProcessing('0')
->setIsAdvanced('1')
->setProductIds('')
->setSortOrder('0')
->setSimpleAction('by_percent')
->setDiscountAmount('10.0000')
->setDiscountQty(NULL)
->setDiscountStep('0')
->setSimpleFreeShipping('0')
->setApplyToShipping('0')
->setTimesUsed('0')
->setIsRss('1')
->setWebsiteIds(array('1',))

Leave a Reply

You must be logged in to post a comment.