Run Magento Code Outside of Magento
Posted on 03. Nov, 2008 by Fido in Development, Magento
Hi All -
Finally time for a new post! (Something I’m surprised I haven’t covered yet).
This post will inform you on how to run Magento code outside of Magento. All you need is to have access to Magento’s ‘app/Mage.php‘ file.
This will be handy code for a few things:
- Integration with 3rd party items - shared sessions, or just shared themes
- Ajax calls - although not the preferred solutions for Ajax calls, it is a quick and easy one
To expand on these ideas a bit more:
Integration:
-You can use this code to output HTML that is outputted in Magento anywhere. You might want to integrate Wordpress and steal the navigation from Magento, for instance. You might want to share sessions and users between your CMS and Magento (and even share the databases). This can help you get started on doing that.
Ajax:
-Because you can use this code to output any block/template, you can use it for Ajax calls in your Magento build. You build your block and template (and any other needed objects) as usual and output them via this code.
Here is a sample:
<?php
require_once 'app/Mage.php';
umask(0);
/* not Mage::run(); */
Mage::app('default');
// get layout object
$layout = Mage::getSingleton('core/layout');
//get block object
$block = $layout->createBlock('catalog/product_ajax');
/* choose whatever category ID you want */
$block->setCategoryId(3);
$block->setTemplate('catalog/product/ajaxevents.phtml');
echo $block->renderView();
?>
We can see in this block of code that we are grabbing the custom block ‘catalog/product_ajax‘.
This is simply a block that grabs a product collection. In this case, we are able to set the category id to 3. (See the post on custom blocks to help you get a feel for what this might look like).
This block is then setting the .phtml template to ‘ajaxevents.phtml‘ and rendering the view. You hopefully can see how this would be useful for Ajax calls.
Other code that might help you along your way:
From php architect’s book (might be outdated!!! We haven’t tested this particular code):
include('app/Mage.php');
Mage::App('base'); //might be "default"
$customer = Mage::getModel('customer/customer');
$customer->loadByEmail('some@email.address'); /* need a users email address */
$session = Mage::getSingleton('customer/session');
$session->start();
Here is some session code that will grab cart information. Notice that this code doesn’t start a session:
<?php
$mageFilename = 'app/Mage.php';
require_once $mageFilename;
umask(0);
Mage::app();
/* Magento uses different sessions for 'frontend' and 'adminhtml' */
Mage::getSingleton('core/session', array('name'=>'frontend'));
// $cart = Mage::getSingleton('checkout/cart')->getItemsCount();
// $cart = Mage::helper('checkout/cart')->getItemsCount();
$cart = Mage::helper('checkout/cart')->getCart()->getItemsCount();
echo 'cart items count: ' . $cart;
?>
Yet another block of code with some interested stuff:
require_once 'app/Mage.php';
umask(0);
$app = Mage::app('default');
/* Init User Session */
$session = Mage::getSingleton('customer/session', array('name'=>'frontend'));
if ($session->isLoggedIn()) {
/* do something if logged in */
} else {
/* do something else if not logged in */
}

17 Comments
Fido
03. Nov, 2008
Sorry for the comments in the code - The theme being used might have some conflicting CSS with the Code viewer which is resulting in comments being floated to the right and having a background image
You’ll need to scroll to see them.
Unirgy
03. Nov, 2008
A more standard way to get block html:
// get layout object
$layout = Mage::getSingleton(’core/layout’);
// create block object
$block = $layout->createBlock(’catalog/product_ajax’);
/* choose whatever category ID you want */
$block->setCategoryId(3);
$block->setTemplate(’catalog/product/ajaxevents.phtml’);
// output block html
echo $block->toHtml();
Fido
03. Nov, 2008
Thanks unirgy. I’ve incorporated that into my code snippet.
James
04. Nov, 2008
I tried to use the session integration examples with the latest Magento, so far no success.
Still, I have a project that really needs to integrate with the user sessions of a shopping cart and Magento is the most powerful option around.
My testing code:
———————————————————-
loadByEmail(’some@email.address’); /* need a users email address */
//$session = Mage::getSingleton(’customer/session’);
//$session->start();
$session = Mage::getSingleton(’customer/session’, array(’name’=>’frontend’));
echo(”");
print_r($session);
Reflection::export(new ReflectionClass(’Mage_Customer_Model_Session’));
echo(”");
echo($session->getCustomerId());
if ($session->isLoggedIn()) {
/* do something if logged in */
echo(”do something if logged in”);
} else {
/* do something else if not logged in */
echo(”do something else if not logged in”);
}
?>
———————————————————-
Fido
05. Nov, 2008
Check out these files:
app\code\core\Mage\Customer\Model\session.php
and
app\code\core\Mage\Customer\Model\customer.php
$customer = Mage::getModel(’customer/customer’)->loadByEmail(’email@address.com’);
$session = Mage::getModel(’customer/session’)->setCustomer($customer);
//can also try
//->login
//->setCustomerAsLoggedIn
Check out the files (and the ones they extend!) to check out starting a session and all that!
Fido
05. Nov, 2008
\app\code\core\Mage\Core\Model\Session\Abstract\Varien.php
This one contains the “start” function
\app\code\core\Mage\Core\Model\Session\session.php
This seems to mostly deal with session messaging
James
05. Nov, 2008
Found it.
Th secret to reinitializing the logged-in user’s session is to first instantiate ‘core/session’ and THEN ‘customer/session’.
So the magic lines to make the lest example work is:
. . .
Mage::getSingleton(’core/session’, array(’name’=>’frontend’));
$session = Mage::getSingleton(’customer/session’, array(’name’=>’frontend’));
. . .
pejie
16. Nov, 2008
do you have the sample code for ajaxevents.phtml?
Fido
17. Nov, 2008
Pejie, just check out “list.phtml” found here:
app\code\core\Mage\Catalog\Block\Product\list.phtml
This is the file I start with to do any product list output from my modules (it’s equipped to handle any product collection)
pejie
18. Nov, 2008
Thanks Fido, i thought the ajaxevents.phtml is another separate file….
Your magento code works outside magento but when I tried to run magento code in my CMS i got the “Fatal error: Cannot redeclare __autoload() in W:\www\magento\app\code\core\Mage\Core\functions.php on line 62″ because there is __autoload function declared in my CMS….. how can i solve this error?
Sirvash
19. Nov, 2008
Hi,
Above all example generates the records corresponding the category_id and customer depends on session very cool but if we wanna to find out all admin user details and all product list in single page.
anybody assist me.
Thanks
Sirvash Sharma
James
16. Dec, 2008
Anyone know how to load an object where I can fetch the price, discount and other Product related data?
Magento Hosting
14. Jan, 2009
Never tried this but I can see how useful it will be - will let you know my progress!
parky
15. Jan, 2009
pejie did you ever get an answer to your fatal error cannot redeclare autoload? I am getting the same with trying to run code from Joomla my cms here is what I get any help would be much appreciated.
Fatal error: Cannot redeclare __autoload() (previously declared in /home/emaginei/public_html/libraries/loader.php:159) in /home/emaginei/public_html/shop/app/code/core/Mage/Core/functions.php on line 77
Strict Standards: Non-static method JFactory::getDBO() should not be called statically, assuming $this from incompatible context in /home/emaginei/public_html/libraries/joomla/session/storage/database.php on line 84
Strict Standards: Non-static method JTable::getInstance() should not be called statically, assuming $this from incompatible context in /home/emaginei/public_html/libraries/joomla/session/storage/database.php on line 89
Strict Standards: Non-static method JFactory::getDBO() should not be called statically, assuming $this from incompatible context in /home/emaginei/public_html/libraries/joomla/database/table.php on line 112
Fido
15. Jan, 2009
Parky - without knowing for sure, I’d guess that there is a conflict between Magento and Joomla both implementing the __autoload “magic method” within the same scope.
For those who don’t know, __autoload is called automatically by PHP when a class is called that is not available yet. This magic method allows you to create an implementation to include/require(_once) a php file based on the name of the class being called.
I’m not sure for a solution on this off the top of my head - it depends on if there is a way to combine the autoload implementations between the two correctly of if there is a way to move the scope of one of the autoload functions so they are not interfering.
Hope this helps! (php.net will tell more on how __autoload functions!)
Nehal
14. Feb, 2009
Hi Fido,
I am newbie in magneto commerce. I wanted to know how i can make ajax call in magento commerce actually i did it through method which simply call .php file by xmlhttp request and it’s worked but real problem is i need to place them outside means on root which is not correct. I want to use standard way calling them through contoller which i tried without success. I guess real problem is with url rewriting process because of which it’s not able to locate URL or php file if i use controller method.
sana
22. Feb, 2009
Hi
I’m also trying to use the session intergration exemple with no success, the reply of my script is always “not connected”…
I need to test if the current user of magento is connected and in this case to collect some informations about it…
Someone can help me
here is my script :
/* inclusion du fichier Mage.php */
require_once ‘magento_store/app/Mage.php’;
//umask(0);
$app = Mage::app(’default’);
Mage::getSingleton(’core/session’, array(’name’=>’frontend’));
$session = Mage::getSingleton(’customer/session’, array(’name’=>’frontend’));
/* test l’utilisateur est loggĂ© ou pas */
if ($session->isLoggedIn()) {
echo “connected”;
} else {
echo “not connected”;
}
thanks for help
Leave a reply