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

}

四、附錄

 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章