今天在做项目的时候发现了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天生单例的特性;