本篇文章主要介绍使用Magento2获取基本URL,存储URL和当前Url,这些都是在我们的日常开发中经常用到的东西
在下面的实力中我将介绍两种方式第一种是使用依赖注入(DI),第二种是使用对象管理器来获取,但是magento2推荐使用依赖注入方式
使用依赖注入:
在这里,我们可能需要在模块类的构造函数中注入\Magento\Store\Model\StoreManagerInterface类的对象,
<?php
namespace YourCompanyName\YourModuleName\Block;
class YourCustomBlock 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);
}
public function getBaseUrl() {
return $this->_storeManager->getStore()->getBaseUrl();
}
public function getLinkUrl() {
return $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_DIRECT_LINK);
}
public function getMediaUrl() {
return $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
}
public function getStaticUrl() {
return $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_STATIC);
}
public function getCurrentUrl() {
return $this->_storeManager->getStore()->getCurrentUrl(false);
}
public function getBaseMediaDir() {
return $this->_storeManager->getStore()->getBaseMediaDir();
}
public function getBaseStaticDir() {
return $this->_storeManager->getStore()->getBaseStaticDir();
}
}
然后我们可以在视图文件中使用这些函数
// 获取基本URL
echo $block->getBaseUrl();
// 获取链接URL
echo $block->getLinkUrl();
// 获取媒体URL
echo $block->getMediaUrl();
// 要获取静态资源URL
echo $block->getStaticUrl();
// 获取当前URL
echo $block->getCurrentUrl();
// 获取媒体目录路径
echo $block->getBaseMediaDir();
// 获取静态目录路径
echo $block->getBaseStaticDir();
使用对象管理器
以下是使用对象管理器在Magento 2中获取商店URL的示例代码。
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$storeManager = $objectManager->get('\Magento\Store\Model\StoreManagerInterface');
$store = $storeManager->getStore();
// 获取基本URL
echo $store->getBaseUrl();
// 获取链接URL
echo $store->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_DIRECT_LINK);
// 获取媒体URL
echo $store->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA);
// 要获取静态资源URL
echo $store->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_STATIC);
// 获取当前URL
echo $store->getCurrentUrl();
// 获取自定义URL
echo $store->getUrl('faq/index');
原创文章转载请注明:转载自:Magento 2:获取基本URL,存储URL和当前URL
发表评论
沙发空缺中,还不快抢~