Magento中helper类的天生单例

今天在做项目的时候发现了magento中的一个很容易忽略的地方,先看一下是哪里的;
先看一下下面的代码:

public static function helper($name)
{
     $registryKey = '_helper/' . $name;
     if (!self::registry($registryKey)) {
         $helperClass = self::getConfig()->getHelperClassName($name);
         self::register($registryKey, new $helperClass);
     }
     return self::registry($registryKey);
 }

这是调用magento中的helper类所要走的核心代码,从代码中发现magento的helper类运用了注册表模式,也就是helper是天生单例模式,也就是当你的一次执行代码中多次调用同一个模块的helper类的时候就容易出现,比如下面的代码:

<?php

class Fun_Core_Helper_Image extends Mage_Core_Helper_Abstract {
	protected $_width = '';
	protected $_height = '';
}

这里面在helper类中声明了两个变量,那么在一次代码运行中多次调用该类的时候,一旦给该helper中声明的变量赋值,那么这个变量就有值了,如果这里面的方法一旦有对该变量进行判断的,那么这个方法中的判断将出现问题,例如:

<?php

class Fun_Core_Helper_Image extends Mage_Core_Helper_Abstract {
	
	protected $_width = '';
	protected $_height = '';

	public function resize($width, $height = null)
    {
        $this->_width = $width;
        $this->_height = $height;
        return $this;
    }
	public function processImage($img)
    {
		echo $this->_width;
		echo  $this->_height;
    }
}

调用该方法:

Mage::helper('core/image')->resize(350,350)->processImage($img);
Mage::helper('core/image')->processImage($img);

执行完结果是:

result  350 350 350 350

我们在看看helper中的注册里面的东西,改进一下:

Mage::helper('core/image')->resize(350,350)->processImage($img);
$a = Mage::registry('_helper/core/image');
Mage::helper('core/image')->resize(700,700)->processImage($img);
$b = Mage::registry('_helper/core/image');
Mage::helper('core/image')->processImage($img);
$c = Mage::registry('_helper/core/image');

打印出来的结果:

result:
350350Fun_Core_Helper_Image Object
(
    [_width:protected] => 350
    [_height:protected] => 350
    [_moduleName:protected] =>
    [_request:protected] =>
    [_layout:protected] =>
)
700700Fun_Core_Helper_Image Object
(
    [_width:protected] => 700
    [_height:protected] => 700
    [_moduleName:protected] =>
    [_request:protected] =>
    [_layout:protected] =>
)
700700Fun_Core_Helper_Image Object
(
    [_width:protected] => 700
    [_height:protected] => 700
    [_moduleName:protected] =>
    [_request:protected] =>
    [_layout:protected] =>
)

从这两个例子可以看出来,magento中的helper类是天生单例,如果不是很了解magento各模块的时候,就很容易将helper模块和model模块当做同一用图来使用,这样就很容易出现我上面举例的问题,所以大家在使用magento中的helper的时候一定要注意这个问题,不然出现问题时可能都不容易发现;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章