CI基本URL路由 [英] CI Base URL Routing
问题描述
例如,在Twitter中,您可以使用以下网址格式:
http://twitter.com/ username /
For example, in Twitter you can have this URL format: http://twitter.com/username/
username是用户的用户名。
With "username" being the username for the user.
关于在Codeigniter中有正确的方法。我需要相同的格式。我有其他页面,如用户帐户管理,关于等等。我需要路由它通过一个功能,检查该用户是否存在,然后将其传递到另一个控制器?感谢!
I am wondering on the proper method to have that in Codeigniter. I would need the same format. I have other pages such as user account management, about, etc. Would I need to route it through one function, check if that user exists and then pass it onto another controller? Thanks!
推荐答案
通过放置 MY_Router.php
在 application\libraries
目录中,并使用以下代码:
Extend the Router Class by placing a MY_Router.php
in your application\libraries
directory and use this code:
<?php
class MY_Router extends CI_Router {
function _validate_request($segments)
{
// Does the requested controller exist in the root folder?
if (file_exists(APPPATH.'controllers/'.$segments[0].EXT))
{
return $segments;
}
// Is the controller in a sub-folder?
if (is_dir(APPPATH.'controllers/'.$segments[0]))
{
// Set the directory and remove it from the segment array
$this->set_directory($segments[0]);
$segments = array_slice($segments, 1);
if (count($segments) > 0)
{
// Does the requested controller exist in the sub-folder?
if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$segments[0].EXT))
{
show_404($this->fetch_directory().$segments[0]);
}
}
else
{
$this->set_class($this->default_controller);
$this->set_method('index');
// Does the default controller exist in the sub-folder?
if ( ! file_exists(APPPATH.'controllers/'.$this->fetch_directory().$this->default_controller.EXT))
{
$this->directory = '';
return array();
}
}
return $segments;
}
// **
// THIS IS THE NEW CODE BELOW
// **
// It forces the segments to your known class (user) & method (index)
// for all controller calls that don't exist as files or inside
// directories
$my_segments = array('user', 'index', $segments[0]);
return $my_segments;
}
}
现在,创建一个用户
控制器,其索引方法接受用户名作为第一个参数:
Now, just create a User
controller with an index method that accepts username as the first parameter:
<?php
class User extends Controller {
function index($username = '')
{
// Validate the HECK out of $username
// Validate the HECK out of $username
// VALIDATE THE HECK OUT OF $username
echo $username;
exit();
}
}
在CI 1.7.2上测试。不知道2.0,虽然...
That's a ballin' answer! Tested on CI 1.7.2. Don't know about 2.0, though...
这篇关于CI基本URL路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!