Codeigniter路由-使用太多了吗? [英] Codeigniter Routing - Using it too much?
问题描述
我是Codeigniter的新手,我正试图通过将旧站点转换为CI来习惯它。
I'm new to Codeigniter, and I'm trying to get accustomed to it by converting an old site into CI.
我无法理解的一件事是路由。如果我不想使用/ controller / method / id这样的url结构,则必须将其更改为 $ route ['controller /(:num)'] = controller / method / $ 1;
在route.php中。在我看来,这似乎效率低下,还有什么我应该做的吗?
One thing I'm having trouble understand is the routing. If I don't want to have my url structure like /controller/method/id, I have to change it to something like $route['controller/(:num)'] = "controller/method/$1";
in routes.php. It just seems inefficient to me, is there something else I should be doing?
例如,在我的网站上,URL是/ game / 4242和/ player / SomeDude
For example, on my site, the urls are /game/4242 and /player/SomeDude
推荐答案
好的,路由是有效的-替代方法是重新映射控制器。
Well, routing is effecient - the alternative is remapping your controllers.
让我们来看看这两种可能性。
Let's take a look at both possibilities.
一种虚构的情况:
稍后,您希望允许用户在其个人资料上显示徽章/勋章/成就/物品。
An imaginary situtation: At a later point, you'd like to allow your users to show badges/medals/achievements/something on their profile.
使用路由,您可以这样实现:
$route['player/(:any)/(:any)'] = "player/show_$2/$1";
$route['player/(:any)'] = "player/show_profile/$1";
然后您的控制器可能看起来像这样:
And your controller could in turn look like this:
class Player extends CI_Controller
{
public function show_profile( $username )
{
// the profile info
}
public function show_badges( $username )
{
// the profiles badges
}
public function show_scores( $username )
{
// the profiles scores
}
}
}
基本上,这使您可以在控制器中简单地添加另一个方法,并在该方法的前面加上 show _
(例如公共方法show_friends($ username)
),您可以通过访问 / player / SomeDude / friends
Basically, this allows you to simply add another method in your controller prefixing the method with show_
(like public method show_friends( $username )
)and you can access it instantly by going to /player/SomeDude/friends
看看替代方案,重新映射控制器将使您不使用路由,而是编写如下所示的控制器:
Looking at the alternative, remapping your controller would allow you not to use routes, but write a controller like this:
class Player extends CI_Controller
{
public function _remap($username, $params = array())
{
if(empty($username))
show_404();
$this->user = $this->user_model->find($username);
if(count($params) == 0)
$method = 'index';
else
$method = $params[0];
unset($params[0]); //No need to send the method along as a parameter
$method = 'process_'.$method;
if (method_exists($this, $method))
{
return call_user_func_array(array($this, $method), $params);
}
show_404();
}
public method process_index()
{
// the profile info
}
public method process_badges()
{
// the profiles badges
}
public method process_scores()
{
// the profiles scores
}
}
我个人喜欢路由。我认为它是透明的,可以使我的控制器看起来更干净。
Personally, I like routing. I think it's transparent and makes my controllers look cleaner.
这篇关于Codeigniter路由-使用太多了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!