CodeIgniter路由 [英] CodeIgniter Routing

查看:124
本文介绍了CodeIgniter路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个具有产品类别和产品的电子商务网站。我想路由URL,以便它将转到products控制器,然后为第一个段运行getCategoryByName函数,然后为第二个段运行getProductByName。这是我有:

I am developing an ecommerce website with CI that has product categories and products. I want to route the URL so that it will go to the products controller, then run the getCategoryByName function for the first segment, then run the getProductByName for the second segment. Here is what I have:


URL:
products/docupen/rc805




routes.php:
$route['products/([a-z]+)'] = "products/getCategoryByName/$1";
$route['products/([a-z]+)/([a-z0-9]+)'] = "products/$1/getProductByName/$2";

但它不工作。 docupen是类别,rc805是产品。

But its not working. "docupen" is the category, and "rc805" is the product.

提前感谢。

感谢大家的帮助。这是我最终为我需要的。

Thank you all for your help. This is what I ended up with for what I needed.


$route['products/:any/:num'] = "products/getProductByID";
$route['products/:any/:any'] = "products/getProductByName";
$route['products/:any'] = "products/getCategoryByName";


推荐答案

我的回答在Colin的回答上有所不同。

My answer builds a bit on Colin's answer.

当我使用CodeIgniter中的路由进行游戏时,我得出结论,路由的顺序很重要。当它找到第一个有效路由时,它不会执行列表中的其他路由。如果没有找到任何有效的路由,那么它会处理默认路由。

When I played around with the routes in CodeIgniter I came to the conclusion that the order of the routes was important. When it finds the first valid route it won't do the other routes in the list. If it doesn't find any valid routes then it will handle the default route.

我为我的特定项目工作的路由工作如下:

My routes that I played around with for my particular project worked as follows:

$route['default_controller'] = "main";
$route['main/:any'] = "main";
$route['events/:any'] = "main/events";
$route['search/:any'] = "main/search";
$route['events'] = "main/events";
$route['search'] = "main/search";
$route[':any'] = "main";

如果输入 http://localhost/index.php/search/1234/4321 它将路由到main / search,然后可以使用 $ this-> uri-> segment(2); 可检索 1234

If I entered "http://localhost/index.php/search/1234/4321" It would be routed to main/search and I can then use $this->uri->segment(2); to retrieve the 1234.

在你的情况下,我会尝试(顺序是非常重要的):

In your scenario I would try (order is very important):

$route['products/:any/:any'] = "products/getProductByName";
$route['products/:any'] = "products/getCategoryByName";

我不知道如何路由你想要的方式( products / $ 1 / getProductByName / $ 2 ),但我不知道你将如何创建一个控制器来处理这种特定形式的URI。使用控制器中的Colin提到的 $ this-> uri-> segment(n); 语句,你应该能够做你想要的。

I don't know enough to route the way you wanted (products/$1/getProductByName/$2), but I'm not sure how you would create a controller to handle this particular form of URI. Using the $this->uri->segment(n); statements as mentioned by Colin in your controller, you should be able to do what you want.

这篇关于CodeIgniter路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆