Slim PHP - 使用请求和响应对象的正确方法
Slim PHP - Right way to use request and response objects
我是 Slim 和 PHP 的新手,但我正在尝试使用 Slim 做一个简单的休息 API。它正在工作,但我不知道我是否以正确的方式进行操作,而且我找不到其他方法来进行操作。
例如,我有这样一条路线:
$app->get('/contacts', '\Namespace\Class:method');
方法:
public function searchContacts($request, $response) {
return Contact::searchContacts($resquest, $response);
}
因此,我发现访问来自其他 类 的请求和响应的独特方法是将对象作为参数传递。它是正确的还是有更好(正确)的方法来做到这一点?
我觉得你的方法不好
控制器应处理请求和 return 响应。
您的模型 (Contact
) 不应处理请求。它应该采用所需的参数和 return 数据。
简单示例:
public function searchContacts($request, $response)
{
// to example, you pass only name of contact
$results = Contact::searchContacts($request->get('contactName'));
$response->getBody()->write(json_encode($results));
return $response;
}
您不需要从另一个 类 访问 Request
和 Response
对象。如果需要,可能你的架构是错误的。
来自官方网站的好例子:http://www.slimframework.com/docs/tutorial/first-app.html#create-routes
最简单的方法是从参数中获取值并在方法中接收响应。
$app->get('/contacts', function (Request $request, Response $response) {
$Contactname = $request->getAttribute('contact');
//You can put your search code here.
$response->getBody()->write("Contact name is, $name");
return $response;
});
我是 Slim 和 PHP 的新手,但我正在尝试使用 Slim 做一个简单的休息 API。它正在工作,但我不知道我是否以正确的方式进行操作,而且我找不到其他方法来进行操作。
例如,我有这样一条路线:
$app->get('/contacts', '\Namespace\Class:method');
方法:
public function searchContacts($request, $response) {
return Contact::searchContacts($resquest, $response);
}
因此,我发现访问来自其他 类 的请求和响应的独特方法是将对象作为参数传递。它是正确的还是有更好(正确)的方法来做到这一点?
我觉得你的方法不好
控制器应处理请求和 return 响应。
您的模型 (Contact
) 不应处理请求。它应该采用所需的参数和 return 数据。
简单示例:
public function searchContacts($request, $response)
{
// to example, you pass only name of contact
$results = Contact::searchContacts($request->get('contactName'));
$response->getBody()->write(json_encode($results));
return $response;
}
您不需要从另一个 类 访问 Request
和 Response
对象。如果需要,可能你的架构是错误的。
来自官方网站的好例子:http://www.slimframework.com/docs/tutorial/first-app.html#create-routes
最简单的方法是从参数中获取值并在方法中接收响应。
$app->get('/contacts', function (Request $request, Response $response) {
$Contactname = $request->getAttribute('contact');
//You can put your search code here.
$response->getBody()->write("Contact name is, $name");
return $response;
});