Magento Request - Frontend or Backend?
This is one of those areas where there's no good answer. Magento itself doesn't provide an explicit method/API for this information, so with any solution you'll need to examine the environment and infer things.
I was using
Mage::app()->getStore()->isAdmin()
for a while, but it turns out there are certain admin pages (the Magento Connect Package manager) where this isn't true. For some reason this page explicitly sets the store id to be 1, which makes isAdmin
return as false.
#File: app/code/core/Mage/Connect/controllers/Adminhtml/Extension/CustomController.php
public function indexAction()
{
$this->_title($this->__('System'))
->_title($this->__('Magento Connect'))
->_title($this->__('Package Extensions'));
Mage::app()->getStore()->setStoreId(1);
$this->_forward('edit');
}
There may be other pages with this behavior,
Another good bet is to check the "area" property of the design package.
This seems less likely to be overridden for a page that's in the admin, since the area impacts the path to the admin areas design templates and layout XML files.
Regardless of what you choose to infer from the environment, create new Magento module, and add a helper class to it
class Namespace_Modulename_Helper_Isadmin extends Mage_Core_Helper_Abstract
{
public function isAdmin()
{
if(Mage::app()->getStore()->isAdmin())
{
return true;
}
if(Mage::getDesign()->getArea() == 'adminhtml')
{
return true;
}
return false;
}
}
and then whenever you need to check if you're in the admin, use this helper
if( Mage::helper('modulename/isadmin')->isAdmin() )
{
//do the thing about the admin thing
}
This way, when/if you discover holes in your admin checking logic, you can correct everything in one centralized place.
If you're able to use an observer, you can limit it to the 'adminhtml' event area.
<config>
...
<adminhtml>
<events>
<core_block_abstract_prepare_layout_after>
<observers>
<mynamespace_mymodule_html_before>
<type>singleton</type>
<class>mynamespace_mymodule/observer</class>
<method>adminPrepareLayoutBefore</method>
</mynamespace_mymodule_html_before>
</observers>
</core_block_abstract_prepare_layout_after>
</events>
</adminhtml>
</config>
Have a look at the methods inside Mage/Core/Model/Store.php
you'll want to use:
Mage::app()->getStore()->isAdmin()
In conjunction with
Mage::getDesign()->getArea() == 'adminhtml'
To act as a fallback where the store ID isn't set as you expect (Magento connect etc.)