yii2開發總結(一)

使用yii2的基礎版本進行開發。javascript

 

1. 部署php

    runtimePath 若是有修改  須要 在config/web.php 中置頂新路徑  而且確保此路徑具備讀寫權限html

    應用的靜態文件  AppAsset  會在模板佈局中使用   也須要保證 web/assets 具備讀寫權限。java

    vendorPath  若是依賴的yii2框架文件目錄發生變化   須要在 config/web.php  中指定新的 vendorPath 路徑web

index.php

<?php

// comment out the following two lines when deployed to production
defined('YII_DEBUG') or define('YII_DEBUG', true);
defined('YII_ENV') or define('YII_ENV', 'dev');

defined('YII_VENDOR_PATH') or define('YII_VENDOR_PATH', '/xxx/xxx/xxx/yii2/2.0.9');

require(YII_VENDOR_PATH . '/autoload.php');
require(YII_VENDOR_PATH . '/yiisoft/yii2/Yii.php');

$config = require(__DIR__ . '/../config/web.php');

(new yii\web\Application($config))->run();

   

$config = [

    'params' => require(__DIR__ . '/params.php'),
    //運行環境路徑指到公共目錄,不然在@app/runtime 而且有寫入權限
    'runtimePath'=>'app\runtime',
    'vendorPath'=>YII_VENDOR_PATH, //若是此路徑有變動,必需要在這裏配置,不然會出錯誤
];

 

 

2. 代碼json

    編寫統一的基礎展現對象,提供帶參數的構造函數和parse方法 填充對象數據。   yii2

namespace app\vo;

use yii;

class BaseVo extends  yii\base\Object{

    function __construct(array $data=NULL)
    {
        if(!empty($data) && is_array($data)){
            foreach ($data as $name => $value) {
                if ($this::hasProperty($name)) {
                    $this->$name = $value;
                }
            }
        }
    }

    public function parse(array $data){
        if(!empty($data) && is_array($data)){
            foreach ($data as $name => $value) {
                if ($this::hasProperty($name)) {
                    $this->$name = $value;
                }
            }
        }
    }

}

 

統計的API接口輸出類     共有屬性能夠在json格式化時輸出,私有屬性不會輸出。app

<?php

namespace app\common;

use yii;
use yii\helpers\Json;
use yii\base\Object;

/**
 * Api 輸出結構類
 * Class ApiResult
 * @package app\common
 */
class ApiResult extends Object{

    public $code;
    public $msg;
    public $start_time;
    public $end_time;
    public $data;

    /**
     * 支持js var, json, jsonp
     *
     * @var type
     */
    private $resultFormat = 'json';

    /**
     *
     * @var type
     */
    private $resultCallBack = '';

    /**
     *
     * @var type 輸出變量名
     */
    private $reaultVarName = '';

    /**
     * @return mixed
     */
    public function getCode()
    {
        return $this->code;
    }

    /**
     * @param mixed $code
     */
    public function setCode($code)
    {
        $this->code = $code;
    }

    /**
     * @return mixed
     */
    public function getMsg()
    {
        return $this->msg;
    }

    /**
     * @param mixed $msg
     */
    public function setMsg($msg)
    {
        $this->msg = $msg;
    }

    /**
     * @return mixed
     */
    public function getStartTime()
    {
        return $this->start_time;
    }

    /**
     * @param mixed $start_time
     */
    public function setStartTime($start_time)
    {
        $this->start_time = $start_time;
    }

    /**
     * @return mixed
     */
    public function getEndTime()
    {
        return $this->end_time;
    }

    /**
     * @param mixed $end_time
     */
    public function setEndTime($end_time)
    {
        $this->end_time = $end_time;
    }

    /**
     * @return mixed
     */
    public function getData()
    {
        return $this->data;
    }

    /**
     * @param mixed $data
     */
    public function setData($data)
    {
        $this->data = $data;
    }

	/**
	 * 初始化,根據參數返回輸出類型
	 */
	public function __construct() {
		//檢查設置
		$callback = Yii::$app->request->get('callback');
		$varName = Yii::$app->request->get('varname');
		
		switch (true) {
			case !is_null($callback):
				if (preg_match("/^[a-zA-Z][a-zA-Z0-9_\.]+$/", $callback)) {
					$this->setReturnTypeJsonp($callback);
					break;
				}else{
					//輸出錯誤
				}
			case !is_null($varName):
				if (preg_match("/^[a-zA-Z][a-zA-Z0-9_\.]+$/", $callback)) {
					$this->setReturnTypeJsVar($varName);
					break;
				}else{
					//輸出錯誤
				}
			default:
				$this->setReturnTypeJson();
				break;
		}
        $this->start_time=time();
	}

	/**
	 * 
	 */
	public function setReturnTypeJsVar($varName){
		$this->resultFormat = 'jsvar';
		$this->reaultVarName = $varName;
	}
	
	/**
	 * 
	 */
	public function setReturnTypeJson(){
		$this->resultFormat = 'json';
	}
	
	/**
	 * 
	 */
	public function setReturnTypeJsonp($callback){
		$this->resultFormat = 'jsonp';
		$this->resultCallBack = $callback;
	}
	
	/**
	 * 
	 */
	private function toJson (){
		return Json::encode($this,JSON_UNESCAPED_UNICODE);
	}
	
	/**
	 * 返回jsonp形式
	 * var a = {};
	 */
	private function toJsonp (){
		
		return htmlentities($this->resultCallBack).'('.Json::encode($this,JSON_UNESCAPED_UNICODE).');';
	}
	
	/**
	 * 返回js變量形式
	 * var a = {};
	 */
	private function toJsVar (){
		return 'var '.htmlentities($this->resultCallBack).'='
			. Json::encode($this,JSON_UNESCAPED_UNICODE).';';
	}


    /**
     * 默認 錯誤
     * @param $code
     * @param string $msg
     * @return $this
     */
	public function setError($code=RespCode::DEF_ERROR,$msg='失敗'){
		$this->setCode($code);
		$this->setMsg($msg);
        $this->setEndTime(time());
		return $this;
	}

    /**
     * 默認成功
     * @param string $data
     * @param number $code
     * @return $this
     */
	public function setSuccess($data=null, $code=RespCode::SUCCESS){
		$this->setCode($code);
		$this->setData($data);
        $this->setEndTime(time());
		return $this;
	}



	/**
	 * 
	 */
	public function __toString(){
		$result = '';
        try{
            $this->outputHeader();
            switch ($this->resultFormat) {
                case 'json':
                    $result = $this->toJson();
                    break;
                case 'jsonp':
                    $result = $this->toJsonp();
                    break;
                case 'jsvar':
                    $result = $this->toJsVar();
                    break;
                default:
                    break;
            }
        }catch (yii\base\Exception $e){
            var_dump($e);
        }

		
		return $result;
	}
	
	/**
	 *  根據類型設置編碼
	 */
	public function outputHeader(){
		switch ($this->resultFormat) {
			case 'json':
				header('Content-Type: application/json; charset=utf-8');
				break;
			case 'jsonp':
				header('Content-Type: application/javascript; charset=utf-8');
				break;
			case 'jsvar':
				header('Content-Type: application/javascript; charset=utf-8');
				break;

			default:
				header('Content-Type: text/html; charset=utf-8');
				break;
		}
	}	
}
相關文章
相關標籤/搜索