代码点火器动态路由

时间:2011-04-21 01:19:18

标签: mysql codeigniter routes

我正在使用代码点火器。

我想做的是,

如果访问的页面不存在

  

example.com/idontexist

然后我想首先检查数据库以查看数据库中是否有idontexist

如果是,那么我想将用户路由到

  

example.com/action/idontexist。

我该怎么做?

2 个答案:

答案 0 :(得分:3)

我觉得每周都会被问到这个问题。

打开application/config/routes.php,然后添加以下内容:

$route['^(:any)'] = "my_controller/get_article/$1";

请注意,它会将所有内容路由到名为action的控制器。如果你有其他控制器,那么你也应该为它们添加一个路径(最好放在这个之前)。

//编辑:使用此功能,您可以转到http://your-site.com/secrets-of-internet-marketing,它将调用get_article控制器中的my_controller函数,并将"secrets-of-internet-marketing"作为第一个参数传递。然后可以使用以下内容处理:

public function get_article($article_name) { 
    // something like this: 
    $article = $this->article_model->get_model_by_name($article_name);
    $this->load->view('article', $article);
}

答案 1 :(得分:2)

一种解决方案是使用您自己的应用程序/ core / MY_Router.php扩展CI_Router类,只需复制类中的方法_set_routing()。 您的更改将在包含routes.php文件后设置为$ this-> routes属性,您可以添加自定义路由。

include(APPPATH.'config/routes'.EXT);
...
$this->routes = ( ! isset($route) OR ! is_array($route)) ? array() : $route;
unset($route);

//Get your custom routes:
$your_routes = $this->_get_custom_routes();
foreach($your_routes as $custom_route)
{
    $this->routes[$custom_route['your_regex_match']] = $custom_route['controller'].'/'.$custom_route['action'];
}

当然你可能不需要这个,但我希望它会给你一些想法。 这样您就可以添加自定义路由,因为您必须从数据库中获取它们,请考虑将它们缓存以获得更快的速度。

相关问题