2011-04-11 128 views
10

我已經在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); 
    } 

} 

寫了一個樣本控制器,但是當我試圖打網址http://localhost/k/album?id=4 我收到NULL值。 如何使用request-> param訪問kohana中的請求變量,而不使用$ _GET和$ _POST方法?

+0

爲什麼你傳遞第二個參數','value是null''? – 2011-04-11 13:06:50

+1

如果值不存在,那麼它是選項參數。它將用該值替換該值。 如果值不存在,第二個值是默認值。 – 2011-04-11 13:09:00

+3

什麼是你的Kohana版本?使用'$ this-> request-> query('id')'如果使用Ko3.1 – biakaveron 2011-04-11 14:06:02

回答

24

在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->execute()調用)。

4

在Konana(3.0)中,您無法通過Request類訪問$ _GET/$ _ POST。您必須直接使用$ _GET/$ _ POST

$this->request->param('paramname', 'defaultvalue')用於訪問路由中定義的參數。對於像<controller>/<action>/<id>這樣的路由網址,您可以使用$this->request->param('id')訪問路由網址中的部分。

編輯:在Kohana 3.1有postquery獲取/設置請求數據的方法;請檢查文檔http://kohanaframework.org/3.1/guide/api/Request

+2

3.1請求類'有query()'和'post()'getters/setters。例如,'$ request-> query('var1')'返回$ _GET ['var1']'值(如果存在),而$ request-> post('var2','val2')'將發送'var2 = val2'作爲POST數據。 – biakaveron 2011-04-11 14:04:37

+0

@biakaveron你可以請你的答案,作爲答案,以便我可以接受你的答案 – 2011-04-12 04:44:12

+0

@biakaveron啊,我不知道(仍與ko3.0工作)。我已經更新了我的答案 – SpadXIII 2011-04-20 09:54:11

0

如果我沒記錯,如果您沒有更改默認路由,則可以嘗試在該控制器上使用url http://localhost/k/album/4

默認路由的形式是:/<controller>/<action>/<id>

希望它能幫助。

1

注意altough它更明確使用$這 - >請求 - >參數(),您可以定義行動PARAMS:

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

,並直接訪問這些增值經銷商。您必須按照它們在相應路徑中定義的順序來定義這些變量(不包括動作和控制器參數,它們在請求級別上定義,因此無需將它們傳遞給動作方法)。

編輯:此功能已在3.1中棄用,並已從3.2中刪除,因此最好避免。您可以在這裏閱讀更多:http://kohanaframework.org/3.2/guide/kohana/upgrading#controller-action-parameters