我目前正在使用Silex 1.3内部的Doctrine DBAL 2.5版来对MySQL DB进行REST调用。我设法让我的GET / GET / {id}和DELETE / {id}相当容易,但我似乎无法让我的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()并使用我自己的值。
我的curl将所有内容反馈给我后,我一直收到此错误消息
<span class="exception_message">Controller "Closure" requires that you provide a value for the "$firstName" 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"
答案 0 :(得分: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";
});