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的時候一定要注意這個問題,不然出現問題時可能都不容易發現;

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