Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/243.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 路线-精简架构_Php_Slim - Fatal编程技术网

Php 路线-精简架构

Php 路线-精简架构,php,slim,Php,Slim,我正在尝试制作一个简单的API,它将为我打印汽车。到目前为止,我做了3条简单的路线: $app('/api/cars', function($req, $res, $arg) { //Display all cars }); $app('/api/cars/{brand}', function($req, $res, $arg) { //Display all cars based on brand }); $app('/api/cars/{brand}/{model}', fu

我正在尝试制作一个简单的API,它将为我打印
汽车
。到目前为止,我做了3条简单的路线:

$app('/api/cars', function($req, $res, $arg) {
    //Display all cars
});
$app('/api/cars/{brand}', function($req, $res, $arg) {
    //Display all cars based on brand
});
$app('/api/cars/{brand}/{model}', function($req, $res, $arg) {
    //Display all cars based on brand
});
而且效果很好。但是如果我想展示带有“?”
颜色的汽车呢?
比方说:
api/cars/red
我不能


我真的不能这样做,因为它在寻找一个品牌名称而不是一种颜色。

您可以通过附加的过滤器作为URL上的GET参数:

/api/cars?color=red

/api/cars/honda?color=red

/api/cars/honda/civic?color=red

然后,您可以使用
$request->getParam('color')
阅读它。

根据您的路线,您将无法阅读,因为正如您所指出的,它正在寻找一个品牌。如果您想要一个快速而肮脏的解决方案,您可以更新端点,使其更具描述性

例如:

$app('/api/cars/brand/{brand}', function($req, $res, $arg) {
    //Display all cars based on brand
});
$app('/api/cars/color/{color}', function($req, $res, $arg) {
    //Display all cars based on color
});

这减少了端点应该期望的任何模糊性。理想情况下,您的API应该接受查询字符串。

您应该创建API以接受url查询字符串,例如
/API/cars?brand=audi&color=blue