这一节内容,适合Magento Advance User(哎,可惜我不在之列,我还不明白原作者的具体意图).
一些封装良好的系统(当然包括Magento)供开发者在Coding时有多种不同的选择。把下面的代码[方法]放在Controller 的任意一个Action中 (PHP允许定义Inner方法)
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 Magento salesrule/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',))
Note:貌似只说明了Magento 的一些Model的成员属性命名都比较有规律。如果有读者发现这段代码的特别用处请留言告诉我一下。