开发者

How To Extend Parameters on the URL in KohanaPHP?

How do I pass extra parameters in the URL to KohanaPHP (version 3.1+) like so...

http://example.com/blog/edit/4000/3200

...where "blog" is the blog.php in the controllers folder, "edit" is a controller method, 4000 is parameter 1 which I can use for who wants to edit the record, and 3200 is parameter 2 which I can use for the record ID?

I get the blog and edit parts. The problem is the 4000 and开发者_开发问答 3200. When I run that URL, I get an error: "404 - Unable to find a route match blog/edit/4000/3200"

Am I forced to have to do something unusual with the .htaccess file, or pass the parameters as query params after a question mark?


This explains what to do:

http://kohanaframework.org/3.1/guide/kohana/routing

But essentially, I need to edit the application\bootstrap.php file and change this:

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

to this:

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

And now in my blog.php controller file, I can now pass 2 parameters into the "action_edit" class method like so:

public function action_edit() {
  $sParam1 = $this->request->param('param1');
  $sParam2 = $this->request->param('param2');
  $this->response->body('param1=' . $sParam1 . ' param2=' . $sParam2);
}


You need a route like this in your bootstrap.php:

Route::set('blog_edit', 'blog/edit/<param1>(/<param2>)')
        array(
            'param1' => '[[:digit:]]{1,}',
            'param2' => '[[:digit:]]{1,}',
        ))
    ->defaults(array(
        'controller' => 'blog',
        'action'     => 'edit',
    ));

Note: the "()" makes param2 optional.

In your controller you can access the parameters as method arguments or via the Request object:

class Controller_Blog
{
    public function action_edit($param1, $param2)
    {
        // or
        $param1 = $this->request->param('param1');
        $param2 = $this->request->param('param2');
        // [...]
    }
}

I haven't tested this code but it should be very close to what you need.

Referenced from "Kohana PHP 3.0 (KO3) Tutorial Part 6"

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜