开发者

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

I have written a sample controller in 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开发者_如何学运维);
  }

}

But when I am trying to hit url http://localhost/k/album?id=4 I am getting NULL value. how can I access request variable in kohana using request->param and without using $_GET and $_POST method ?


In Kohana v3.1+ Request class has query() and post() methods. They work both as getter and 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'));

But remember that setting GET/POST data will not overload current $_GET/$_POST values. They will be sent after request executing ($request->execute() call).


In Konana (3.0) you can't access $_GET/$_POST through the Request class. You'll have to directly use $_GET/$_POST

$this->request->param('paramname', 'defaultvalue') is for accessing params defined in the route. For route-urls like <controller>/<action>/<id> you would use $this->request->param('id') to access the portion in the route url.

edit: in Kohana 3.1 there are post and query methods for getting/setting data of the request; check the documentation at http://kohanaframework.org/3.1/guide/api/Request


Notice that altough it's more clear to use $this->request->param(), you can define action params as :

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

and access those vars directly. You have to define these vars in the same order they're defined in the corresponding route (excluding the action and controller params, they're defined on request level anyways so there's no need to pass them to the action method).

EDIT: This functionality was deprecated in 3.1 and has been removed from 3.2, so it is best to avoid. You can read more here: http://kohanaframework.org/3.2/guide/kohana/upgrading#controller-action-parameters


If I remember well, if you have not changed the default routes, you can try using the url http://localhost/k/album/4 with that controller.

As the default route is in the form: /<controller>/<action>/<id>

Hope it helps.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜