yii2 RESTful 接口 api -6: 写一个自己的api

时间:2022-08-08 19:34:11


1. 创建api的 应用分区,类似backend   frontend   这样可以用一个单独的域名,以及单独的配置

可以复制frontend过来,然后改改

然后在\common\config\bootstrap.php中加入

Yii::setAlias('api', dirname(dirname(__DIR__)) . '/api');


1.配置:

'request' => [
			'class' => '\yii\web\Request',
            'enableCookieValidation' => false,
            'parsers' => [
                'application/json' => 'yii\web\JsonParser',
            ],
			'cookieValidationKey' => 'O1d232trde1xww-M97_7QvwPo-5QGdkLMp#@#@',
		],


'urlManager' =>  [
			'class' => 'yii\web\UrlManager',
			'enablePrettyUrl' => true,
			'enableStrictParsing' => true,
			'showScriptName' => false,
			'rules' => [
				'' => 'site/index',
				['class' => 'yii\rest\UrlRule', 'controller' => 'customer/api',
				  'pluralize' => false,
				],
				#  定义方法: public function actionSearch($id);   <id> 就是search方法传入的参数
				#  http://10.10.10.252:599/v1/wishorder/2015-08-11+12:12:12/2015-09-11+12:12:12?access-token=pBJi3hyFsLsTuvUM9paFpWjYRatn3qwS
				#  分页:http://10.10.10.252:599/v1/wishorder/2015-08-11+12:12:12/2015-09-11+12:12:12?page=2&access-token=pBJi3hyFsLsTuvUM9paFpWjYRatn3qwS
				'GET v1/wishorder/<begin_datetime>/<end_datetime>' => 'v1/wishorder/viewbydate',
				'GET v1/ebayorder/<begin_datetime>/<end_datetime>' => 'v1/ebayorder/viewbydate',
			],
			
		];


 

2.myapp\code\core\Api\V1\controllers\WishorderController;

<?php
namespace myapp\code\core\Api\V1\controllers;
use yii\web\Response;
use Yii;
use yii\filters\auth\QueryParamAuth;
use yii\filters\auth\CompositeAuth;
use yii\rest\ActiveController;
use myapp\code\core\Api\V1\models\wish\WishOrder;
use yii\data\ActiveDataProvider;
use backend\models\core\Request;
class WishorderController extends ActiveController
{
	public $modelClass = 'myapp\code\core\Api\V1\models\wish\WishOrder';
	
	public function behaviors()
	{
		$behaviors = parent::behaviors();
		
		$behaviors['authenticator'] = [
			'class' => CompositeAuth::className(),
			'authMethods' => [
				# 下面是三种验证access_token方式
				//HttpBasicAuth::className(),
				//HttpBearerAuth::className(),
				# 这是GET参数验证的方式
				# http://10.10.10.252:600/user/index/index?access-token=xxxxxxxxxxxxxxxxxxxx
				QueryParamAuth::className(),
			],
		
		];
		
		#定义返回格式是:JSON
		$behaviors['contentNegotiator']['formats']['text/html'] = Response::FORMAT_JSON;
		return $behaviors;
	}
	
	public function actionViewbydate($begin_datetime,$end_datetime){
		# 分页参数处理
		$numPerPage = Request::param('numPerPage');
		if(!$numPerPage || $numPerPage <1 || $numPerPage > 800 ){
			$numPerPage = 100;
		}else{
			$numPerPage = (int)$numPerPage;
		}
		# where条件处理
		$where = '';
		if($begin_datetime){
			$where  .= " last_updated >= '".$begin_datetime."' ";
		}
		if($end_datetime){
			if($where){
				$where  .= " AND last_updated < '".$end_datetime."' ";
			}else{
				$where  .= " last_updated < '".$end_datetime."' ";
			}
		}
		//echo $where;exit;
		if(!$where){
			 throw new \yii\web\HttpException(404, 'You Must Add Where Filter By DateTime');
		}
		$query = WishOrder::find()->where($where);
		if($query->count() <1){
			 throw new \yii\web\HttpException(404, 'No entries found with this query string');
		}
		$provider = new ActiveDataProvider([
            'query' => $query,
            'pagination' => [
				'pageSize' => $numPerPage,
			],
        ]);
		
		return $provider;
	}
}
















3.myapp\code\core\Api\V1\models\wish\WishOrder

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2015/7/23
 * Time: 14:28
 */
namespace myapp\code\core\Api\V1\models\wish;
use yii\db\ActiveRecord;

class WishOrder extends ActiveRecord
{
	
	public static function getDb(){
		return \Yii::$app->wishDb;
	}
	
    public static function tableName()
    {
        return 'wish_order';
    }
	
	
	public  function fields(){
		
		return [
		'id',
		'platform_order_id',
		'platform_order_states',
		'wish_name',
		'transaction_id',
		'sku',
		'qty',
		'adapter',
		'spu',
		'spu_atrribute',
		'order_total',
		'spu_price',
		'spu_shipping',
		'spu_name',
		'sku_china_name',
		'spu_image_url',
		'last_updated',
		'days_to_fulfill',
		'hours_to_fulfill',
		'order_create_time',
		'customer_name',
		'customer_country',
		'customer_province',
		'customer_city',
		'customer_street_address1',
		'customer_street_address2',
		'customer_zipcode',
		'customer_phone',
		'customer_note',
		'shipping_provider',
		'tracking_number',
		'warehouse_id',
		'real_ship_cost',
		'real_ship_cost_currency',
		
		
		];
	}
}



?>


关于账户验证和速度控制参看:

http://blog.csdn.net/terry_water/article/details/49903507