繁体   English   中英

如何使用$ this-> request-> param of Kohana来获取请求变量

[英]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() call)。

在Konana(3.0)中,您无法通过Request类访问$ _GET / $ _ POST。 你必须直接使用$ _GET / $ _ POST

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

编辑:在Kohana 3.1中有获取/设置请求数据的postquery方法; 查看http://kohanaframework.org/3.1/guide/api/Request上的文档

请注意,尽管使用$ this-> request-> param()更清楚,但您可以将action params定义为:

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

并直接访问这些变量。 您必须按照它们在相应路径中定义的相同顺序定义这些变量(不包括动作和控制器参数,它们在请求级别上定义,因此不需要将它们传递给动作方法)。

编辑:此功能在3.1中已弃用,已从3.2中删除,因此最好避免使用。 你可以在这里阅读更多内容: http//kohanaframework.org/3.2/guide/kohana/upgrading#controller-action-parameters

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

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

希望能帮助到你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM