记录常用的Magento方法

调用助手类

Mage::helper()->functionInHelper();

获取数据库对象

$object = Mage::Model();

以及可用的方法:

$object -> getData();//取数据
$object -> setData();//写入数据

日志

Mage::log();
Mage::logException();

获取入参,可以设置默认值

$id = $this->getRequest()->getParam('id',null);

获取用户session对象

$session = Mage::getSingleton('customer/session');

以及可以使用方法

$session->login($user,$pass);  //登录
$session->logout();              //登出
$session->isLoggedIn();        //判断是否登录
$customer = $session->getCustomer();

获取系统session对象

$session = Mage::getSingleton('core/session');

获取ip

$ip = Mage::helper('core/http')->getRemoteAddr()

获取顾客对象

根据id获取对象

$customer = Mage::getModel('customer/customer')
				->load($id);

根据email获取对象

$customer = Mage::getModel('customer/customer')
                ->setWebsiteId(Mage::app()->getStore()->getWebsiteId())
                ->loadByEmail($email);

获取产品对象

$product = Mage::getModel('catalog/product');

获取订单对象

$order = Mage::getModel('sales/order');

获取店铺对象

$store = Mage::app()->getStore();

获取商品库存

$qty = (int)Mage::getModel('cataloginventory/stock_item')->loadByProduct($product)->getQty();

获取类名

get_class()

输出magento的配置文件

header('Content-Type: text/plain'); echo $config = Mage::getConfig() ->loadModulesConfiguration('config.xml') ->getNode() ->asXML(); exit;
    }

获取storeId

Mage::app()->getStore()

获取websiteId

Mage::app()->getStore()->getWebsiteId()

补充:几处 M1 与 M2 的术语对照

原文整理的是一批 Magento 常用方法。术语对照如下:

M1 叫法 M2 叫法 说明
Mage::getModel() ObjectManager get() / 构造函数注入 M2 里不推荐用 ObjectManager 直接取对象
Mage::getStoreConfig() ScopeConfigInterface::getValue() 参数变成 path + scope
Mage::helper() 构造函数注入 Helper 静态调用在 M2 被审查
getCollection() 同样有,但返回 SearchCriteria 风格 getCollection() 本身没有失效
Layout ->getBlock() getLayout()->getBlock() 基本一致

M2 最核心的变化不是方法名,而是依赖注入:能通过构造函数注入的东西,就不要通过静态方法去拿。判断标准很简单——写 ObjectManager::getInstance() 的地方,基本都是没想清楚的信号。

本文整理于 2017 年,2026 年 11 月补写。