【问题标题】:how to use $this->request->param of Kohana to get request variables如何使用 Kohana 的 $this->request->param 获取请求变量
【发布时间】:2011-04-11 13:04:53
【问题描述】:

我用 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 值。 如何在不使用 $_GET 和 $_POST 方法的情况下使用 request->param 访问 kohana 中的请求变量?

【问题讨论】:

  • 你为什么要传递第二个参数,'value is null'
  • 如果值不存在,那是选项参数。它将用该值替换该值。如果值不存在,则第二个值是默认值。
  • 您的 Kohana 版本是什么?如果使用 Ko3.1,请使用 $this-&gt;request-&gt;query('id')

标签: php kohana


【解决方案1】:

在 Kohana v3.1+ 中,请求类具有 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-&gt;execute() 调用)。

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 在 3.1 请求类 has query()post() getters/setters。例如,$request-&gt;query('var1') 返回 $_GET['var1'] 值(如果存在),而 $request-&gt;post('var2', 'val2') 将发送 var2=val2 作为 POST 数据。
    • @biakaveron 你能把你的答案贴出来,作为答案,以便我接受你的答案
    • @biakaveron 啊,我不知道(仍在使用 ko3.0)。我已经更新了答案
    【解决方案3】:

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

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

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

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

    【讨论】:

      【解决方案4】:

      如果我没记错的话,如果你没有更改默认路由,你可以尝试在那个控制器上使用 url http://localhost/k/album/4

      因为默认路由的形式是:/&lt;controller&gt;/&lt;action&gt;/&lt;id&gt;

      希望对你有帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多