gpt4 book ai didi

php - 使用 magento 创建一个没有索引的好 url

转载 作者:行者123 更新时间:2023-12-02 04:47:53 27 4
gpt4 key购买 nike

我想制作一个显示特定品牌产品的 phtml 文件。

网址需要如下所示:

brands/Subway
brands/Mcdonalds
brands/Lego
brands/Barbie
brands/Duplo
brands/.....

我怎样才能让这个 url 在品牌是变量的情况下工作。

我试图制作一个模块,但在那种情况下我得到了一个像 brands/index/brands/Subway 这样的 url

我也不想为每个品牌(100+)重写

最佳答案

您可以在您的模块中创建一个自定义路由器来处理像brands/Subway 这样的路由。 .
这就是您所需要的。

首先,您需要让页面在不重写的情况下正常工作。
让我们假设在这个网址 mysite.com/brands/index/index - 你有品牌列表
在网址 mysite.com/brands/index/view/id/12 - 你有 id 为 12 的品牌。

在您的 config.xml 中,您需要将其添加到 <global> 中标签:

<events>
<controller_front_init_routers>
<observers>
<[namespace]_[module]>
<class>[Namespace]_[Module]_Controller_Router</class>
<method>initControllerRouters</method>
</[namespace]_[module]>
</observers>
</controller_front_init_routers>
</events>

这将在现有路由器上添加一个新路由器。现在路由器类 app/code/local/[Namespace]/[Module]/Controller/Router.php :

<?php 
class [Namespace]_[Module]_Controller_Router extends Mage_Core_Controller_Varien_Router_Abstract{
public function initControllerRouters($observer){
$front = $observer->getEvent()->getFront();
$front->addRouter('[module]', $this);
return $this;
}
public function match(Zend_Controller_Request_Http $request){
if (!Mage::isInstalled()) {
Mage::app()->getFrontController()->getResponse()
->setRedirect(Mage::getUrl('install'))
->sendResponse();
exit;
}
$urlKey = trim($request->getPathInfo(), '/');
$check = array();
$parts = explode('/', $urlKey);
if ($parts[0] == 'brands'){//if url key starts with 'brands'
if (!isset($parts[1])){ //if the url is just 'brands' - then redirect to brand list
return false;//do nothing...the request will be handled by the default router and you will see `brands/index/index/`.
}
elseif ($parts[1] == 'index'){//if your controller is named differently change 'index' to your controller name
return false; //do nothing...the request will be handled by the default router and you will see `brands/index/index/`.
}
else {
//if a name is specified
//get the entities with that name.
$collection = Mage::getModel('[module]/[entity]')->getCollection()
//if the field is named differently change 'name' to your field name.
->addAttributeToFilter('name', $parts[1]);
$collection->getSelect()->limit(1);//limit to only one
$itemId = (int)$collection->getFirstItem()->getId();
//redirect to 'brands/index/view/id/$itemId'
$request->setModuleName('brands')
->setControllerName('index') //if your controller is named differently change 'index' to your controller name
->setActionName('view') //if your action is named differently change 'view' to action name
->setParam('id', $itemId);
$request->setAlias(
Mage_Core_Model_Url_Rewrite::REWRITE_REQUEST_PATH_ALIAS,
$urlKey
);
return true;
}
}
return false;
}
}

就是这样。清除缓存并试一试。

关于php - 使用 magento 创建一个没有索引的好 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19445440/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com