多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
1.定义路由 ~~~ Route::get('api/:version/product/recent','api/:version.Product/getRecent'); ~~~ 2.新添Count.php验证器 ~~~ <?php namespace app\api\validate; class Count extends BaseValidate { protected $rule = [ 'count' => 'isPositiveInteger|between:1,15', ]; } ~~~ 3.新建ProductException.php异常类 ~~~ <?php namespace app\lib\exception; class ProductException extends BaseException { public $code = 404; public $msg = '指定商品不存在,请检查商品ID'; public $errorCode = 20000; } ~~~ 4.更改Product.php模型 ~~~ <?php namespace app\api\model; class Product extends BaseModel { protected $autoWriteTimestamp = 'datetime'; protected $hidden = [ 'delete_time', 'main_img_id', 'pivot', 'from', 'category_id', 'create_time', 'update_time']; public function getMainImgUrlAttr($value, $data) { return $this->prefixImgUrl($value, $data); } public static function getMostRecent($count) { $products = self::limit($count) ->order('create_time desc') ->select(); return $products; } } ~~~ 5.更改Product .php控制器 ~~~ <?php namespace app\api\controller\v1; use app\api\model\Product as ProductModel; use app\api\validate\Count; use app\lib\exception\ProductException; use think\Controller; class Product extends Controller { //获取指定数量的最近商品 public function getRecent($count = 15) { (new Count())->goCheck(); $products = ProductModel::getMostRecent($count); if (!$products){ throw new ProductException(); } //隐藏summary的方法 $collection=collection($products); $products=$collection->hidden(['summary']); return $products; } } ~~~ 结果 ![](https://box.kancloud.cn/56af73553aa89b5adab6fc20f6af45f2_973x631.png)