Slim PHP - 使用请求和响应对象的正确方式
问题描述:
我是Slim和PHP的新手,但我正在尝试使用Slim做一个简单的其他API。它正在工作,但我不知道我是否以正确的方式进行,我找不到另一种方式来做到这一点。Slim PHP - 使用请求和响应对象的正确方式
例如,我有个路线那样:
$app->get('/contacts', '\Namespace\Class:method');
的方法:
public function searchContacts($request, $response) {
return Contact::searchContacts($resquest, $response);
}
因此,独特的方式,我发现从其他类访问的请求和响应是通过使作为参数的对象。这是正确的还是有更好的(正确)方法来做到这一点?
答
我认为你的方式不好。
控制器应处理请求并返回响应。 您的型号(Contact
)不应处理请求。它应该采取必要的参数并返回数据。
简单的例子:
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
答
最简单的方法是让从PARAMS的值和收到的方法响应。
$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;
});
现在很清楚。谢谢! – Alan