如何使用$this->;请求->;获取请求变量的Kohana的param


how to use $this->request->param of Kohana to get request variables

我在kohana 中编写了一个示例控制器

    <?php
defined('SYSPATH') OR die('No direct access allowed.');
class Controller_Album extends Controller {
  public function action_index() {
    $content=$this->request->param('id','value is null');   
    $this->response->body($content);
  }
}

但是当我尝试访问url时http://localhost/k/album?id=4我得到了NULL值。如何使用request->param访问kohana中的请求变量,而不使用$_GET和$_POST方法?

在Kohana v3.1+中,Request类有query()post()方法。它们既可以作为getter又可以作为setter:

// get $_POST data
$data = $this->request->post();
// returns $_GET['foo'] or NULL if not exists
$foo = $this->request->query('foo'); 
// set $_POST['foo'] value for the executing request
$request->post('foo', 'bar');
// or put array of vars. All existing data will be deleted!
$request->query(array('foo' => 'bar'));

但请记住,设置GET/POST数据不会重载当前的$_GET/$_POST值。它们将在请求执行后发送($request->execute()调用(。

在Konana(3.0(中,您不能通过Request类访问$_GET/$_POST。您必须直接使用$_GET/$_POST

$this->request->param('paramname', 'defaultvalue')用于访问路由中定义的参数。对于像<controller>/<action>/<id>这样的路由url,您可以使用$this->request->param('id')来访问路由url中的部分。

edit:在Kohana 3.1中,有postquery两种方法用于获取/设置请求的数据;查看文档http://kohanaframework.org/3.1/guide/api/Request

注意,尽管使用$this->request->param((更清楚,但您可以将操作参数定义为:

public function action_index($id, $seo = NULL, $something = NULL)..

并直接访问这些vars。您必须按照在相应路由中定义的顺序来定义这些变量(不包括操作和控制器参数,它们无论如何都是在请求级别上定义的,因此不需要将它们传递给操作方法(。

编辑:此功能在3.1中已被弃用,并已从3.2中删除,因此最好避免使用。您可以在此处阅读更多信息:http://kohanaframework.org/3.2/guide/kohana/upgrading#controller-动作参数

如果我记得很清楚,如果你没有更改默认路由,你可以尝试使用urlhttp://localhost/k/album/4使用该控制器。

由于默认路由的形式为:/<controller>/<action>/<id>

希望能有所帮助。