在codeigniter中使用get变量时更改uri


Changing uri when using get variable in codeigniter

我刚刚开始学习Codeignitor。我正在开发一个web应用程序,我使用get变量,并从数据库加载数据并显示它。所以我的url是:

http://localhost/abc/book/?isbn=123456

我想让我的url看起来像

http://localhost/abc/book/123456

我认为这可以很容易地完成与URI库和URI段的帮助,但我必须严格使用GET方法只。请建议解决方案,以便使用GET方法我得到URL像上面。

下面是我的控制器的book方法:

public function book()
{
    $slug = $this->input->get('isbn',TRUE);
    if($slug == FALSE)
    {
        $this->load->view('books/error2');
    }
    else
    {
        $data['book'] = $this->books_model->get_book($slug);
        if (empty($data['book'])) 
        {
            $data['isbn'] = $slug;
            $this->load->view('books/error',$data);
        }
        else
        {
        $data['title'] = $data['book']['title'];
        $this->load->view('templates/header',$data);
        $this->load->view('books/view',$data);
        $this->load->view('templates/footer');
        }
    }
}

如果您唯一的目的是不必改变html表单,为什么我们不只是写一个小包装器?

你只需要一个合适的路由来实现这个小技巧。

class book extends MY_Controller{
    public function __construct()
    {
        parent::__construct();
        // If the isbn GET Parameter is passed to the Request 
        if($this->input->get('isbn'))
        {
            // Load the URL helper in order to make the 
            // redirect function available
            $this->load->helper('url');
            // We redirect to our slugify method (see the route) with the 
            // value of the GET Parameter
            redirect('book/' . $this->input->get('isbn'));
        }
    }
    public function slugify($isbn)
    {
        echo "Put your stuff here but from now on work with segments";
    }
}

现在路由

$route['book/(:any)'] = "book/slugify/$1";

当你做http://example.com/book/?isb=4783

它将路由到http://example.com/book/4783

GET参数被传递给我们的slugify方法,在那里您可以处理URI段。不需要修改HTML表单

但是,如果您坚持要在脚本中处理GET参数,这当然是行不通的。

也许我错过了一些东西,但是您可以使用get方法将参数传递给使用URI段的函数:

public function book($slug)
{
    if($slug == FALSE)
    {
        $this->load->view('books/error2');
    }
    else
    {
        $data['book'] = $this->books_model->get_book($slug);
        if (empty($data['book'])) 
        {
            $data['isbn'] = $slug;
            $this->load->view('books/error',$data);
        }
        else
        {
        $data['title'] = $data['book']['title'];
        $this->load->view('templates/header',$data);
        $this->load->view('books/view',$data);
        $this->load->view('templates/footer');
        }
    }
}

如CodeIgniter用户指南所述:

如果你的URI包含两个以上的片段,它们将作为参数传递给你的函数。

例如,假设您有一个这样的URI:
example.com/index.php/products/shoes/sandals/123

你的函数将被传递URI段3和4 ("sandals"answers"123"):

<?php
class Products extends CI_Controller {
    public function shoes($sandals, $id)
    {
        echo $sandals;
        echo $id;
    }
}
?>