2015-08-14 35 views
0

我目前使用Silex 1.3裏面的Doctrine DBAL版本2.5來調用MySQL DB的REST調用。我設法讓GET/GET/{id}和DELETE/{id}工作相當簡單,但我似乎無法讓我的POST/PUT工作。Silex - 我的REST POST/PUT調用沒有接收參數

這裏是休耕代碼

$app->post('/student', function($firstName, $lastName) use($app) { 
    $sql = "INSERT INTO tbl_students (firstName, lastName) 
      VALUES (:firstName, :lastName)"; 
    $student = $app['db']->prepare($sql); 
    $student->bindValue(':firstName', $firstName, PDO::PARAM_STR); 
    $student->bindValue(':lastName', $lastName, PDO::PARAM_STR); 

    $student->execute(); 

    return "insert successful"; 
}); 

$app->put('/student/{id}', function($id, $firstName, $lastName) use($app){ 
    $sql = "UPDATE tbl_students 
      SET firstName = :firstName, lastName = :lastName 
      WHERE id = :id"; 
    $student = $app['db']->prepare($sql); 
    $student->bindValue(':id', $id, PDO::PARAM_INT); 
    $student->bindValue(':firstName', $firstName, PDO::PARAM_STR); 
    $student->bindValue(':lastName', $lastName, PDO::PARAM_STR); 
    $student->execute(); 

    return "student succesfully updated"; 
}); 

如果我硬編碼的默認值,它工作完全正常,以及使用bindParam(),並用自己的價值觀。

我把我的捲曲後收到此錯誤消息在我轉儲一切恢復

<span class="exception_message">Controller &quot;Closure&quot; requires that you provide a value for the &quot;$firstName&quot; argument (because there is no default value or because there is a non optional argument after this one).</span> 

下面是我用

休耕捲曲命令
curl -X POST -d "firstName=First123&lastName=Last456" URL/student 
curl -X POST -d '{"firstName":"First123","lastName":"Last456"}' URL/student --header "Content-Type:application/json" 
curl -X POST -d "firstName=First123&lastName=Last456" URL/student --header "Content-Type:text/html" 
+1

'firstName'和'lastName'是不是你的路線的一部分 - 因此,爲什麼您會收到錯誤消息。您必須從'請求'中讀取這些信息,或者將它們包含在您的路線中。 – Artamiel

回答

1

的Silex不會自動爲您創造方法的參數對應於你的發佈變量。您必須從@Artamiel建議的請求對象中獲取它們。

參見http://silex.sensiolabs.org/doc/usage.html#example-post-route

爲您的文章操作更新的代碼應該是這樣的:

$app->post('/student', function(Request $request) use($app) { 
    $firstName = $request->get('firstName'); 
    $lastName = $request->get('lastName'); 
    $sql = "INSERT INTO tbl_students (firstName, lastName) 
      VALUES (:firstName, :lastName)"; 
    $student = $app['db']->prepare($sql); 
    $student->bindValue(':firstName', $firstName, PDO::PARAM_STR); 
    $student->bindValue(':lastName', $lastName, PDO::PARAM_STR); 

    $student->execute(); 

    return "insert successful"; 
}); 
相關問題