我有控制器“包”,函数“tour_package”和参数的URL“1”。 http://www.mysite.in/package/tour_packages/1这里的参数设置为ID。 我需要有相应的URL字符串来改变它http://www.mysite.in/package/tour_packages/American
和另一个例子,如: http://www.mysite.in/package/tour_packages/2到http://www.mysite.in/package/tour_packages/African
如何做到这一点?
首先我会改变URL链接使用url_title()(网址助手)。 如果您使用从我相信什么是数据库调用的ID的文本值创建查询这会给你喜欢的东西
(例如,如果对于ID为1的记录是名称=“美国”);
echo 'http://www.mysite.in/package/tour-packages/'.url_title($name);
会给;
http://www.mysite.in/package/tour-packages/American
如果再加入这个扩展类路由器会自动格式化破折号强调了你。
<?php if (! defined('BASEPATH')) exit('No direct script access allowed');
class MY_Router extends CI_Router {
function set_class($class) {
$this->class = str_replace('-', '_', $class);
}
function set_method($method) {
$this->method = str_replace('-', '_', $method);
}
function _validate_request($segments) {
// Does the requested controller exist in the root folder?
if (file_exists(APPPATH.'controllers/'.str_replace('-', '_', $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().str_replace('-', '_', $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;
}
// Can't find the requested controller...
show_404($segments[0]);
}
}
然后,您可以添加在路由文件(配置)的条目; 就像是;
$route['package/tour_package/(:any)'] = "package/lookup_by_name/$1";
然后,您需要创建封装控制器称为lookup_by_name($名)的方法。 这种方法需要你在哪里得到从名字id的值做一个SQL查询到数据库。 然后,您可以继续加载视图或做任何你想要的。
如
public function lookup_by_id($name) {
// sql to get id from database record
// load the view?
$this->view($id);
}
public function view($id) {
// sql to load full record from id
$this->load->view('foo', $data);
}