Magento Blocks
It's incredibly common that an eCommerce business will use several applications to manage its presence online. Thanks to Magento's MVC architecture it's fairly simple to grab Magento blocks and include them in other PHP applications.
A good example of using Magento blocks in a non-Magento applications is the Magento Wordpress Integration plugin. But what about other applications? Joomla? Expression Engine? Drupal?
If we break it down, there's really only two things we need to do:
- Initialize Magento
- Include the block
Initialize Magento
This is a step we only need to do once, preferably early in the application's execution. We're going to include to Magento bootstrap file and load the Magento framework. We can see what this looks like by looking at Magento's index.php file.
include '/path/to/magento/app/Mage.php';
umask(0);
Mage::app();
Now we have a few extra steps. We need to trick Magento into thinking it's running. That way we can correctly use it's blocks.
Mage::getSingleton('core/translate')
->setLocale(Mage::app()->getLocale()->getLocaleCode())
->init('frontend', true);
Mage::getSingleton('core/session', array('name' => 'frontend'));
Mage::getSingleton("checkout/session");
Mage::getDesign()
// Set the package, usually "default" or "enterprise"
->setPackageName('enterprise')
// Set the theme, usually "default"
->setTheme('default');
$layout = Mage::app()->getLayout();
$module = Mage::app()->getRequest()->getModuleName();
if (!$module) {
$customerSession = Mage::getSingleton('customer/session');
$layout->getUpdate()
->addHandle('default')
->addHandle(
$customerSession->isLoggedIn()
? 'customer_logged_in'
: 'customer_logged_out'
)
->load();
$layout->generateXml()
->generateBlocks();
}
That's it! Magento is now loaded an we're ready to include our blocks.
Including Layout Blocks
To include a block created through Magento's layout system all you need is the name. For instance, we can find the Magento header in layout/page.xml
...
...
Here we're going to use the "as" attribute. If it was absent we would use "name".
Now that we have the name we can include the block with
echo $layout->getBlock('header')->toHtml();
Easy!
Including Static Blocks
Including a CMS static block is pretty easy too. All you need is the identifier. For instance, if we had a block called "home-slider"
echo $layout->createBlock('cms/block')->setBlockId('home-slider')->toHtml();
That's all it takes!
Magento Integration Script
If you want to make things even easier, checkout out our Magento Integration script on GitHub. You're ready to go in just three lines.
include 'magento-integration.php';
MI::init('/path/to/magento/app/Mage.php');
echo MI::getBlock('header');
>> Download the Source