Kohana 3 get current controller/action/arguments
Asked Answered
D

3

18

In Kohana 2 you could easily get that information like this:

echo router::$controller;
echo router::$method;
echo router::$arguments[0-x];

Any idea how that works in Kohana 3?

Thanks in advance!

Delldella answered 4/5, 2010 at 8:49 Comment(0)
P
32

From inside a controller:

$this->request->controller

$this->request->action

$this->request->param('paramname')

Unlike K2 arguments in K3 are accessed via kays which you define in your routes.

Take for example this url:

Route::set('default', '(<controller>(/<action>(/<id>)))')    
    ->defaults(array('controller' => 'welcome', 'action' => 'index')); 

To access the "id" argument you'd call

$this->request->param('id')

You can't access the controller / action arguments from the param() method.

Note, you can also use Request::instance() to get the global (or "master") request instance.

For more information see the K3 guide

Parahydrogen answered 4/5, 2010 at 9:51 Comment(2)
Does this mean that for every "action" you have to define a set of keys for each parameter? That sounds like a lot of unnecessary work. I read that simply passing arguments to actions like in action(arg1, arg2, ...) is deprecated in K3.1 and will be eliminated in 3.2Steading
@Steading Every argument that you want to pass via the uri needs to be defined in the route. If you're using a lot of parameters then maybe you should be using the query string instead.Parahydrogen
H
25

Updated answer for Kohana 3.2, from the user guide:

// From within a controller:
$this->request->action();
$this->request->controller();
$this->request->directory();

// Can be used anywhere:
Request::current()->action();
Request::current()->controller();
Request::current()->directory();
Holism answered 4/11, 2011 at 20:10 Comment(0)
O
3

For those using Kohana >= 3.1, it might be useful to notice that some properties of the Request object have been converted to methods.

E.g. Request::controller is now Request::controller() (or $this->request->controller() when you're inside a controller).

For more information, I'd like to reference to the Kohana upgrade guide on http://kohanaframework.org/3.1/guide/kohana/upgrading

Oistrakh answered 28/7, 2011 at 19:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.