相关知识
准备工作
application oute.php
Route::get('api/:version/product/recent', 'api/:version.Product/getRecent');
异常处理
applicationlibexceptionProductException.php
<?php
namespace applibexception;
class ProductException extends BaseException
{
public $code = 404;
public $msg = '指定商品不存在,请检查商品ID';
public $errorCode = 20000;
}
参数检验
applicationapivalidateCount.php
<?php
namespace appapivalidate;
class Count extends BaseValidate
{
protected $rule = [
'count' => 'isPositiveInteger|between:1,15',
];
}
Product模型
applicationapimodelProduct.php,省略部分代码
<?php
namespace appapimodel;
class Product extends BaseModel
{
//...
public static function getMostRecent($count) {
$products = self::limit($count)->order('create_time desc')->select();
return $products;
}
}
Product控制器
applicationapicontrollerv1Product.php
<?php
namespace appapicontrollerv1;
use appapimodelProduct as ProductModel;
use appapivalidateCount;
use applibexceptionProductException;
class Product
{
public function getRecent($count = 15)
{
(new Count())->goCheck();
$products = ProductModel::getMostRecent($count);
if (!$products)
{
throw new ProductException();
}
return $products;
}
}
测试
上面返回的结果中有一个summary摘要字段仅最近新品的接口不需要,不能通过模型的$hidden属性,需要在接口中对summer做隐藏
使用数据集类
applicationdatabase.php
return [
//...
'resultset_type' => 'collection',
//...
];
applicationapicontrollerv1Product.php
<?php
namespace appapicontrollerv1;
use appapivalidateCount;
use appapimodelProduct as ProductModel;
use applibexceptionProductException;
class Product
{
public function getRecent($count = 15) {
(new Count())->goCheck();
$products = ProductModel::getMostRecent($count);
// 如果要判断数据集是否为空,不能直接使用empty判断,而必须使用数据集对象的isEmpty方法判断
if ($products -> isEmpty()) {
throw new ProductException();
}
$products = $products->hidden(['summary']);
return $products;
}
}