2012-09-23 30 views
1

我想测试一个Magento块功能。我不知道,如何调用.phtml文件以外的功能。有人知道块为getModel()的功能吗?如何测试Magento块

我发现

getBlockSingleton()

但是,它已被弃用,我无法得到它的工作。

回答

7

假设你的Magento根是你的web根目录。在你的Magento根目录下,创建一个test.php文件。您可以通过http:// base_url /test.php访问它。

ini_set('display_errors',true); //PHP has such friendly errors, show them! 

include 'app/Mage.php';   //include the helper class/bootstrap file 
Mage::setIsDeveloperMode(true); //flag to render Magento's traces 

Mage::app(); 
/** 
    Instantiate the app. Note that this is different from Mage::run()! This can 
    be skipped given the Mage::app() call below. 
*/ 

//block "type" 
$class = 'core/bar'; 

//block instance 
$block = Mage::app()->getLayout()->createBlock($class); 

if (is_object($block)) die("Okay! ".get_class($block)); 

/** 
* If script execution reaches this point, there is one of 
* two problems: 
* 
* 1) bad/missing config 
* 2) bad path based on filename 
*/ 

//the xpath which is used 
$xpath = 'global/blocks/'.strstr($class,'/',true).'/class'; 

//a node from config XML (we hope) 
$node = Mage::getConfig()->getNode($xpath); 

//error condition 1: 
if (!$node) die("Bad xpath, check configuration: ".$xpath); 

//error condition 2: 
$name = uc_words((string) $node . '_' . substr(strrchr($class, '/'), 1)); 
$file = str_replace('_', DIRECTORY_SEPARATOR, $name.'.php'); 
$issue = '<br /><br />'; 

if (!is_readable($file)) { 
    //no file matching classname 
    $issue .= "No file found for $file, tried:<pre> - "; 
    $issue .= str_replace(PATH_SEPARATOR,'/'.$file.'<br /> - ',get_include_path()).$xpath.'</pre>'; 
} else { 
    $issue .= "Wrong class name in $file"; 
} 

echo sprintf('Xpath ok, looking for class <span style="font-family: Courier New">%s</span>%s',$name,$issue); 
3

如果你只需要块实例本身来测试方法,下面的函数可以这样做:

/** 
* Create block instance for given block classAlias. 
* 
* @param string $classAlias Magento class alias for this block, e.g. 'catalog/product_price' 
* 
* @return Mage_Core_Block_Abstract 
*/ 
public static function getBlockInstance($classAlias) 
{ 
    $className = Mage::getConfig()->getBlockClassName($classAlias); 
    $result = new $className; 
    return $result; 
}