1. 程式人生 > >Magento中helper的一個坑

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的時候,在helper中宣告變數的時候一定要注意helper天生單例的特性;