TP5 专题、分类、商品详情接口编写

一、专题接口编写

       目录

//控制器
<?php

namespace app\api\controller\v1;

use app\api\validate\IDCollection;
use app\api\model\Theme as ThemeModel;
use app\api\validate\IDMustBePostiveInt;
use app\lib\exception\ThemeException;

class Theme
{
    public function getSimpleList($ids = ''){
        (new IDCollection()) -> goCheck();

        $ids = explode(',', $ids);
        $result = ThemeModel::with('topicImg,headImg')
            ->select($ids);
        if($result -> isEmpty()){
            throw new ThemeException();
        }
        return $result;
    }

    public function getComplexOne($id){
        (new IDMustBePostiveInt()) -> goCheck();
        $theme = ThemeModel::getThemeWithProducts($id);
        if(!$theme){
            throw new ThemeException();
        }
        return $theme;
    }
}
//路由
<?php

use think\Route;

Route::get('api/:version/banner/:id', 'api/:version.Banner/getbanner');
Route::get('api/:version/theme', 'api/:version.Theme/getSimpleList');
Route::get('api/:version/theme/:id', 'api/:version.Theme/getComplexOne');
Route::get('api/:version/product/recent', 'api/:version.Product/getRecent');
Route::get('api/:version/product/by_category', 'api/:version.Product/getAllInCategory');
Route::get('api/:version/category/all', 'api/:version.Category/getAllCategory');
//验证器
<?php

namespace app\api\validate;

class IDCollection extends BaseValidate
{
    protected $rule =[
      'ids' => 'require|checkIDs',
    ];

    protected $message = [
        'ids' => 'ids参数必须是以逗号分隔的多个正整数'
    ];

    protected function checkIDs($value){
        $value = explode(',', $value);
        if(empty($value)){
            return false;
        }
        foreach ($value as $id){
            if(!$this -> isPostiveInteger($id)){
                return false;
            }
        }

        return true;

    }
}
//将公共方法提取到基类验证器
<?php

namespace app\api\validate;

use app\lib\exception\ParameterException;
use think\Exception;
use think\Request;
use think\Validate;

class BaseValidate extends Validate
{
    public function goCheck(){
        //获取http传入的参数
        //对这些参数做校验
        $request = Request::instance();
        $params = $request -> param();

        $result = $this -> batch() -> check($params);
        if(!$result){
            $e = new ParameterException([
                'msg' => $this -> error,
//                'code' => 400,
//                'error' => 10002
            ]);
            throw $e;
        }else{
            return true;
        }
    }
    
    //field是字段名
    protected function isPostiveInteger($value, $rule = '', $data = '', $field = ''){
        if(is_numeric($value) && is_int($value + 0) && ($value + 0) > 0){
            return true;
        }else{
            return false;
        }
    }
    
}
//主题 模型
<?php

namespace app\api\model;

use think\Model;

class Theme extends BaseModel
{
    protected $hidden = [
      'delete_time', 'update_time',
      'topic_img_id', 'head_img_id'
    ];
    public function topicImg(){
        //$this->hasOne()  表中主键被别的外键关联
        //belongsTo 表中有外键关联别的库
        return $this -> belongsTo('Image', 'topic_img_id', 'id');
    }

    public function headImg(){
        return $this -> belongsTo('Image', 'head_img_id', 'id');
    }

    public function products(){
        return $this -> belongsToMany('product', 'theme_product', 'product_id','theme_id');
    }

    public static function getThemeWithProducts($id){
        $themes = self::with('products,topicImg,headImg')
        ->find($id);
        return $themes;
    }


}
//database.php配置返回结果集
// 数据集返回类型
'resultset_type'  => 'collection',
//Image  Model
<?php

namespace app\api\model;

class Image extends BaseModel
{
    protected $hidden = ['id', 'delete_time', 'update_time'];

    public function getUrlAttr($value, $data){
        return $this -> prefixImgUrl($value, $data);
    }
}
//Product  Model
<?php

namespace app\api\model;

use think\Model;

class Product extends BaseModel
{
    protected $hidden = [
      'delete_time', 'category_id',
        'from', 'create_time',
        'update_time', 'pivot'
    ];

    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;
    }

    public static function getProductsByCategoryID($categoryID){
        $products = self::where('category_id', '=', $categoryID);
        return $products;
    }

}
//Base Model
<?php

namespace app\api\model;

use think\Model;

class BaseModel extends Model
{
    protected function prefixImgUrl($value, $data){
        $finalUrl = $value;
        if($data['from'] == 1){
            $finalUrl = config('setting.img_prefix').$value;
        }
        return $finalUrl;
    }
}

二、分类

//控制器
<?php

namespace app\api\controller\v1;

use app\api\model\Category as CategoryModel;
use app\lib\exception\CategoryException;

class Category
{
    public function getAllCategory(){

        $catetories = CategoryModel::all([], 'img');
        if($catetories -> isEmpty()){
            throw new CategoryException();
        }
        return $catetories;
    }
}
//分类model
<?php

namespace app\api\model;

class Category extends BaseModel
{
    protected $hidden = ['delete_time', 'create_time', 'create_time'];
    public function img(){
        return $this -> belongsTo('Image', 'topic_img_id', 'id');
    }
}

三、商品详情接口

//控制器
<?php

namespace app\api\controller\v1;

use app\api\validate\Count;
use app\api\validate\IDMustBePostiveInt;
use app\lib\exception\ProductException;
use app\api\model\Product as ProductModel;
class Product
{
    public function getRecent($count=15){
        (new Count()) -> goCheck();

        $products = ProductModel::getMostRecent($count);
        if($products -> isEmpty()){
            throw new ProductException();
        }
        $products = $products ->  hidden(['summary']);

        return $products;
    }

    public function getAllInCategory($id){
        (new IDMustBePostiveInt()) -> goCheck();
        $products = ProductModel::getProductsByCategoryID($id);
        if(!$products){
            throw new ProductException();
        }
        $products = $products ->  hidden(['summary']);
        return $products;
    }
}
<?php

namespace app\api\validate;

class Count extends BaseValidate
{
    protected $rule = [
      'count' => 'isPostiveInteger|between:1,15'
    ];
}
//model
<?php

namespace app\api\model;

use think\Model;

class Product extends BaseModel
{
    protected $hidden = [
      'delete_time', 'category_id',
        'from', 'create_time',
        'update_time', 'pivot'
    ];

    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;
    }

    public static function getProductsByCategoryID($categoryID){
        $products = self::where('category_id', '=', $categoryID);
        return $products;
    }

}

四、附录

 

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值