Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

kohana

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 ?

like image 877
Vivek Goel Avatar asked Apr 11 '11 13:04

Vivek Goel


3 Answers

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).

like image 127
biakaveron Avatar answered Oct 31 '22 22:10

biakaveron


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

like image 30
SpadXIII Avatar answered Oct 31 '22 21:10

SpadXIII


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

like image 42
Kemo Avatar answered Oct 31 '22 21:10

Kemo