本帖最后由 吖晋 于 2011-8-27 14:51 编辑
不知道标题是否对应内容,但实在想不出更贴切的。如果斑竹想到,就帮我改了吧!哈
首先这篇帖子 我在老外CI论坛看到,也不知道有人转了没有。
首先提问者:想问如何才能创建一个用户的URL。
例如: http://www.example.com/username
然后有一位用户回到说:设置一下URI配置文件
PHP复制代码 $route['(:any)'] = "yourcontroller/$1"; 复制代码
但显然这是有bug的,如果我访问的是我的Controller呢?显然是不现实的……
然后出现了一位大大,给出了一个解答方案!用Hook
我们去代码!
1.先开启我们的钩子,怎么开启?开手册!
PHP复制代码 $config['enable_hooks'] = TRUE; 复制代码
2.配置我们的钩子!
PHP复制代码 $hook=array(
'pre_system' => array(
array(
'class' => 'Userlookup',
'function' => 'check_uri',
'filename' => 'Userlookup.php',
'filepath' => 'hooks',
'params' => NULL,
),
),
);
复制代码
3.最后当然是我们钩子的方法
PHP复制代码 <?php defined('BASEPATH') or die('No direct script access allowed');
class Userlookup {
protected $uri_username;
protected $connection_method;
protected $hostname;
protected $username;
protected $password;
protected $database;
public function __construct ()
{
// Configure database connection
include(APPPATH .'config/database'.EXT );
$this->hostname = $db[$active_group]['hostname'];
$this->username = $db[$active_group]['username'];
$this->password = $db[$active_group]['password'];
$this->database = $db[$active_group]['database'];
}
public function check_uri ()
{
// First, we need get the uri segment to inspect
$request_uri = explode('/',substr($_SERVER['REQUEST_URI'], 1));
$this->uri_username = array_shift($request_uri);
$connection_router = array_shift($request_uri);
$this->connection_method = empty($connection_router) ? 'index' : $connection_router;
// Connect to database, and check the user table
mysql_connect($this->hostname, $this->username, $this->password) AND mysql_select_db($this->database);
$res = mysql_query("SELECT user_id FROM user WHERE user_url='".$this->uri_username."'");
if ($row = mysql_fetch_object($res))
{
// If, there is a result, then we should modify server data
// Below line means, we told CodeIgniter to load
// 'User' controller on 'index', 'info' or any valid connection/method and we send 'id' parameter
$_SERVER['REQUEST_URI'] = '/user/'.$this->connection_method.'/'.$row->user_id;
}
mysql_free_result($res);
}
} 复制代码
|