【发布时间】:2016-09-08 14:30:27
【问题描述】:
如何创建一个扩展给定类的 Magento 2 模块,并能够在 Magento 的每个 .phtml 中的任何位置调用我新定义的函数?
我已经尝试创建我的模块,这是块:
etc/module.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
<module name="Chapagain_HelloWorld" setup_version="1.0.0" schema_version="1.0.0">
<sequence>
<module name="Magento_Footer"/>
</sequence>
</module>
</config>
块/HelloWorld.php
<?php
namespace Chapagain\HelloWorld\Block;
class HelloWorld extends \Magento\Framework\View\Element\Template
{
protected $_storeManager;
public function __construct(
\Magento\Backend\Block\Template\Context $context,
\Magento\Store\Model\StoreManagerInterface $storeManager,
array $data = []
)
{
$this->_storeManager = $storeManager;
parent::__construct($context, $data);
}
/**
* Get store identifier
*
* @return int
*/
public function getStoreId()
{
return $this->_storeManager->getStore()->getId();
}
/**
* Get website identifier
*
* @return string|int|null
*/
public function getWebsiteId()
{
return $this->_storeManager->getStore()->getWebsiteId();
}
/**
* Get Store code
*
* @return string
*/
public function getStoreCode()
{
return $this->_storeManager->getStore()->getCode();
}
/**
* Get Store name
*
* @return string
*/
public function getStoreName()
{
return $this->_storeManager->getStore()->getName();
}
/**
* Get current url for store
*
* @param bool|string $fromStore Include/Exclude from_store parameter from URL
* @return string
*/
public function getStoreUrl($fromStore = true)
{
return $this->_storeManager->getStore()->getCurrentUrl($fromStore);
}
/**
* Check if store is active
*
* @return boolean
*/
public function isStoreActive()
{
return $this->_storeManager->getStore()->isActive();
}
}
?>
稍后我尝试调用 footer.phtml 和 header.phtml 中的函数(我需要它们的地方)
<?php
echo $block->getStoreId() . '<br />';
echo $block->getStoreCode() . '<br />';
echo $block->getWebsiteId() . '<br />';
echo $block->getStoreName() . '<br />';
echo $block->getStoreUrl() . '<br />';
echo $block->isStoreActive() . '<br />';
?>
但 Magento 不允许我这样做。
上面的函数没有回显,函数为 NULL。
【问题讨论】:
-
“Magento 不允许我这样做”是什么意思?具体说明您面临的问题。
-
@tvo 函数返回 NULL。