简单的URL路由不使用CodeIgniter

时间:2013-03-21 18:36:57

标签: php codeigniter routing

我对CodeIgniter很新,并完成了我的第一个项目。但是,在我把它放在我的托管网站上之前,我想使用CodeIgniter在config文件夹中提供的routes.php文件来清理URL。

我的网站将使用以下网址加载:

http://fakehost:8888/TheWorksPlumbing/index.php/theWorksPlumbingController/index/home
http://fakehost:8888/TheWorksPlumbing/index.php/theWorksPlumbingController/index/about
http://fakehost:8888/TheWorksPlumbing/index.php/theWorksPlumbingController/index/services

它还将使用默认控制器网址http://fakehost:8888/TheWorksPlumbing/

加载主页

但是,我希望网站的每个网页都有一个网址,但无法让它工作。例如,我想:

http://fakehost:8888/TheWorksPlumbing/home
http://fakehost:8888/TheWorksPlumbing/about
http://fakehost:8888/TheWorksPlumbing/services

以下是theWorksPlumbingController控制器文件的代码:

class TheWorksPlumbingController extends CI_Controller {

    public function index($page = 'home'){

        if ( !file_exists('application/views/'.$page.'.php') ) {
            show_404();
        }

        $this->load->view('templates/header');
        $this->load->view($page);
        $this->load->view('templates/footer');
    }
}

以下是我的routes.php文件中无效的代码:

$route['default_controller'] = "theWorksPlumbingController";
$route['404_override'] = '';
$route['(:any)'] = "index.php/theWorksPlumbingController/index";

我需要添加或更改以使网站只加载/ home或/ about或/ services?

1 个答案:

答案 0 :(得分:7)

$route['home'] = 'theWorksPlumbingController/index/home';
$route['about'] = 'theWorksPlumbingController/index/about';
$route['services'] = 'theWorksPlumbingController/index/services'; 

可能会这样做..虽然我从来没有尝试过这样的设置。通常在CI中,您为每个页面创建一个方法,如下所示:

class TheWorksPlumbingController extends CI_Controller {

    public function home(){

        $this->load->view('templates/header');
        $this->load->view('home');
        $this->load->view('templates/footer');
    }

    public function about(){

        $this->load->view('templates/header');
        $this->load->view('about');
        $this->load->view('templates/footer');
    }

    public function services(){

        $this->load->view('templates/header');
        $this->load->view('services');
        $this->load->view('templates/footer');
    }
}

可以通过

访问
http://www.example.com/index.php/theWorksPlumbingController/home
http://www.example.com/index.php/theWorksPlumbingController/about
http://www.example.com/index.php/theWorksPlumbingController/services

可通过

路由
$route['home'] = 'theWorksPlumbingController/home';
$route['about'] = 'theWorksPlumbingController/about';
$route['services'] = 'theWorksPlumbingController/services';

https://www.codeigniter.com/user_guide/general/routing.html