Trong bài viết này tôi sẽ hướng dẫn các bạn lấy đường dẫn hiện tại trong Magento 2. Đầu tiên để lấy được đường dẫn hiện tại các bạn phải khởi tạo đối tượng Magento\Store\Model\StoreManagerInterface và lấy được store hiện tại như bên dưới:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
protected $storeManager; protected $urlInterface; public function __construct( \Magento\Store\Model\StoreManagerInterface $storeManager, \Magento\Framework\UrlInterface $urlInterface ) { $this->storeManager = $storeManager; $this->urlInterface = $urlInterface; } public function getName() { $currentStore = $this->_storeManager->getStore(); } |
Lấy đường dẫn hiện tại:
1 2 |
$currentStore->getBaseUrl(); //Output: https://example.com/ |
Lấy đường dẫn media:
1 2 |
$currentStore->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA); //Output: https://example.com/media/ |
Lấy đường dẫn static:
1 2 |
$currentStore->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_STATIC); //Output: https://example.com/static/version1599299905/ |
getUrl()
1 2 |
$currentStore->getUrl('helloworld/post/index'); //Output: https://example.com/helloworld/post/index/ |