简体   繁体   English

使用SLIM Framework创建REST API。 与REST保持一致,但提供正确的视图

[英]Creating a REST API with SLIM Framework. Keeping in line with REST but providing the correct view

I am trying to wrap my head around how to create a RESTful API with SLIM. 我试图围绕如何使用SLIM创建RESTful API进行思考。 I understand REST and I have a good understanding of slim but what I can understand is how to render the correct view templates. 我了解REST,并且对slim非常了解,但是我能理解的是如何呈现正确的视图模板。

This is a typical REST API 这是典型的REST API

$app->get('/wines', 'getWines');
$app->get('/wines/:id',  'getWine');
$app->post('/wines', 'addWine');
$app->put('/wines/:id', 'updateWine');
$app->delete('/wines/:id',   'deleteWine');

Now what I don't understand is if all the routes have the same URL how can you render the correct view template. 现在我不明白的是,如果所有路线都具有相同的URL,那么如何呈现正确的视图模板。 The first GET request displays all the wines. 第一个GET请求显示所有葡萄酒。 The next GET displays only the wine with the specified id. 下一个GET仅显示具有指定ID的葡萄酒。 Now this is where my understanding falters. 现在,这是我的理解力下降的地方。 When I want to add a wine I write a route that reacts differently to either a GET or POST request. 当我想添加葡萄酒时,我写的路由对GETPOST请求的反应不同。

$app->map('/wines', function() {
    echo "I respond to multiple HTTP methods!";
})->via('GET', 'POST'); 

So for the get request I want show a form so I can enter a new wine but as the URL is the same as getting all the wines and they are both GET requests how can I render the correct template. 因此,对于get请求,我想显示一个表单,以便我可以输入新的葡萄酒,但是由于URL与获取所有葡萄酒相同,而且它们都是GET请求,因此我该如何呈现正确的模板。

I hope this makes sense. 我希望这是有道理的。

Thanks 谢谢

You should add a form to the response to GET /wines/ which describes the POST /wines/ and you should add links for each of the GET /wines/:id -s. 您应该在对GET /wines/的响应中添加一个表单,其中描述了POST /wines/并且应该为每个GET /wines/:id -s添加链接。

You can use HAL for the links, and some ad-hoc solution for the form. 您可以将HAL用于链接,并将某些临时解决方案用于表单。 If you want a more sophisticated solution, you can use Hydra with JSON-LD. 如果需要更复杂的解决方案,可以将Hydra与JSON-LD一起使用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM