Categories


Archives


Recent Posts


Categories


Using the Magento API to Safely Serialize as JSON

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!

If you’re new to Magento, you may not realize that every remote API method has a native PHP equivalent. The why, how, and how to identify these models is covered elsewhere, but one thing I forget at my peril is how useful the API methods are when I need to serialize something as JSON or via PHP’s serialize function.

json_encode(
    Mage::getModel('catalog/product_api')->load($product_id)
);

$data = serialize(Mage::getModel('catalog/product')->load($product_id));

What’s great about the API load methods is they automatically return a simple PHP array full of scaler values. Compare that to something like this

json_encode(    
    Mage::getModel('catalog/product')->load($product_id)
);

While they may seem equivalent, the catalog/product object is going to have a lot of other object references — which is turn may have other other object references, which in turn may circle back to the product object. This isn’t insurmountable, but is a giant pain in the butt when all you want is a JSON representation of a product’s data. The API models give you this, with the added benefits that they’re relatively stable — array keys added to an API result are much less likely to change version to version.

Copyright © Alana Storm 1975 – 2023 All Rights Reserved

Originally Posted: 7th July 2014

email hidden; JavaScript is required