2、模型关联–关联与查询
12、theme接口与验证与重构
\controller\v1\Theme.php
<?php
namespace app\api\controller\v1;
use app\api\validate\IDCollection;
class Theme
{
public function getSimpleList($ids=''){
(new IDCollection())->goCheck();
return 'success';
}
}
\validate\IDCollection.php
<?php
namespace app\api\validate;
class IDCollection extends BaseValidate
{
protected $rule = [
'ids' => 'require|checkIDs'
];
protected $message = [
'ids' => 'ids参数必须为以逗号分割的正整数'
];
protected function checkIDs($value){
$values = explode(',',$value);//以逗号分隔数组
if (empty($values)){
return false;
}
foreach ($values as $id){//遍历数组元素,必须为正整数
if (!$this->isPositiveInteger($id)) {
return false;
}
}
return true;
}
}
18、最近新品接口编写
\controller\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;
class Product
{
function getRencent($count = 15){
(new Count()) -> goCheck();
$products = ProductModel::getMostRencent($count);
if (!$products){
throw new ProductException();
}
return $products;
}
}
\lib\exception\ProductException.php
<?php
namespace app\lib\exception;
class ProductException extends BaseException
{
public $code = 404;
public $msg = '指定的商品不存在';
public $errorCode = 20000;
}
\model\Production.php
<?php
namespace app\api\model;
class Product extends BaseModel
{
protected $hidden = [
'delete_time', 'main_img_id','pivot','create_time',
'update_time', 'from','category_id'
];
//读取器
public function getMainImgUrlAttr($value,$data){
return $this->prefixImageUrl($value,$data);
}
public static function getMostRencent($count){
$products = self::limit($count)
->order('create_time desc')
->select();
return $products;
}
}
标题