1

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

我发现

getBlockSingleton()

但是,它已被弃用,我无法让它工作。

4

2 回答 2

7

假设您的 Magento 根是您的网络根。在您的 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);
于 2012-09-23T19:48:49.370 回答
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;
}
于 2015-03-09T09:57:55.370 回答