Yii2使用速查表

安裝

安裝yii2初級程序

composer global require "fxp/composer-asset-plugin:^1.2.0"
composer create-project --prefer-dist yiisoft/yii2-app-basic basic

安裝yii2高級模板程序

composer global require "fxp/composer-asset-plugin:^1.2.0"
composer create-project --prefer-dist yiisoft/yii2-app-advanced yii-application
/path/to/php-bin/php /path/to/yii-application/init

詳情參考GitHub官網javascript

經過composer.json安裝擴展

composer install

更新本地composer擴展庫

composer update

直接安裝某個composer擴展

composer require [options] [--] [vendor/packages]...

DAO

Yii的數據庫讀取對象,在PDO之上,DAO後有了Query Builder和ARphp

基本使用方法

得到數據庫鏈接
$conn = Yii::$app->db;
執行數據庫查詢語句
Yii::$app->db->createCommand("SELECT * FROM `user`");
Yii::$app->db->createCommand("SELECT * FROM `user` WHERE uid=:uid",[":uid"=>1]);
Yii::$app->db->createCommand("SELECT * FROM `user` WHERE uid=:uid")->addValue([":uid"=>1]);
SQL語句插入數據
Yii::$app->db->createCommand('INSERT INTO user (email, password) VALUES("test3@example.com", "test3");')->execute();
數組形式插入數據
Yii::$app->db->createCommand()->insert('user', [
    'email' => 'test4@example.com',
    'password' => 'changeme7',
    'first_name' => 'Test'
])->execute();
批量插入數據
Yii::$app->db->createCommand()->batchInsert('user', ['email', 'password', 'first_name'],
[
['james.franklin@example.com', 'changeme7', 'James'],
['linda.marks@example.com', 'changeme7', 'Linda']
['roger.martin@example.com', 'changeme7']
])->execute();
更新數據
Yii::$app->db->createCommand()->update('user', ['updated_at' => time()], 'id = 2')->execute();
刪除數據
Yii::$app->db->createCommand()->delete('user', 'id = 3')->execute();

獲取結果方法

獲取全部數據(數組形式返回)
Yii::$app->db->createCommand("SELECT * FROM `user`")->queryAll();
獲取一條數據(一維數組)
Yii::$app->db->createCommand("SELECT * FROM `user` WHERE id = 1")->queryOne();
獲取一個值
Yii::$app->db->createCommand("SELECT count(*) AS total FROM `user` WHERE id = 1")->queryScalar();
獲取某一列(放到一位數組中)
Yii::$app->db->createCommand("SELECT username FROM `user`")->queryColumn();

Logging

日誌功能css

基本用法

trace
Yii::trace($message,$category) //記錄一條消息去跟蹤一段代碼是怎樣運行的。這主要在開發的時候使用。
info
Yii::info($message,$category) //記錄一條消息來傳達一些有用的信息。
warning
Yii::warning($message,$category) //記錄一個警告消息用來指示一些已經發生的意外。
error
Yii::error($message,$category) //記錄一個致命的錯誤,這個錯誤應該儘快被檢查。

Validator

數據驗證,最經常使用於模型的rules()函數html

方法列表(Model中rules函數)

required 必須值
["username",'required']
[["username","email"],'required']
[["username"],'required',"message"=>"{attribute}必須填寫"]
[["username"],'required','requiredValue'=>"abei"] //用戶填寫的值必須等於requiredValue才能經過驗證。
Email驗證
["email",'email']
[["email","work_email"],'email']
Boolean驗證
['sex', 'boolean', 'trueValue' => true, 'falseValue' => false, 'strict' => true]; //能夠認爲置頂 true / false 值。
captcha驗證碼
['verificationCode', 'captcha'];
compare比較
['username', 'compare', 'compareAttribute' => 'province','message'=>'username和province必須同樣'] //錯誤信息將提示給username
['age', 'compare', 'compareValue' => 30, 'operator' => '>=','type' => 'number'];//compareValue:比較常量值 operator:比較操做符 type爲值類型,默認爲string,會一個每一個字符對比,若爲number則直接判斷數值
//operator 待選值==、===、!=、!==、>、>=、<、<=
date驗證
["birth","date","format"=>"Y-m-d"]
default驗證
['age','default','value'=>null] //當age爲空的時候設置爲null
['country','default','value'=>'USA'] //當 country爲空時設置爲USA
/* 若是from爲空,則=今天+3天,若是to爲空,則=今天+6天 */
[['from','to'],'default','value'=>function($model,$attribute){
    return date('Y-m-d', strtotime($attribute === 'to' ? '+3 days' : '+6 days'));
}]
double/number驗證
['v','double'] //判斷v是否爲數字
['v','double','max'=>90,'min'=>1]//判斷v是否爲數字且大於等於一、小於等於90
數組各元素驗證
["categoryIds","each","rule"=>['integer']]
exist是否存在驗證
/* 所謂對存在的檢查實質爲where的與操做,必須同時瞞住的記錄存在方可。兄弟們能夠研究下,exist是對sql語句EXISTS的應用*/
["username","exist"] //username輸入的值已經存在
["username","exist","targetAttribute"=>"province"] //username的輸入值必須在province列存在
["username","exist",'targetAttribute' => ['username', 'province']] //username的輸入值必須在username和province中存在
[["username","province"],"exist",'targetAttribute' => ['username', 'province']] //username和province的輸入值必須在username和province中存在
file驗證
/* maxFiles表明一次最多傳幾個,mimeTypes表明上傳文件類型 */
['primaryImage', 'file', 'extensions' => ['png', 'jpg', 'gif'],'mimeTypes'=>["image/*"], 'maxSize' => 1024*1024,'minSize'=>100*1024,'maxFiles'=>6,'checkExtensionByMimeType'=>true],
filter過濾驗證函數
[['username', 'email'], 'filter', 'filter' => 'trim', 'skipOnArray' => true],
['phone', 'filter', 'filter' => function ($value) {
        //normalize phone input here
        return $value;
}],
image驗證
/* 上傳png/jpg格式,最大寬度不能超過1000px,最小寬度不能低於100px,最大高度不能高於1000px。最小高度不能低於100px */
['primaryImage', 'image', 'extensions' => 'png, jpg','minWidth' => 100, 'maxWidth' => 1000,'minHeight' => 100, 'maxHeight' => 1000]
ip驗證
["ip_addess","ip"]
in方法驗證
["level","in","range"=>[1,2,3]]
integer驗證
["age",'integer'];
["age","integer","max"=>90,"min"=>1]
正則匹配驗證
["username","match","pattern"=>"/^[a-z]\w*$/i"]
safe驗證(多用於設置一個model的attribute)
["description","safe"]
string驗證
["username","string","length"=>[4,24]];
["username","string","min"=>4];
["username","string","max"=>32];
["username","string","encoding"=>"UTF-8"];
unique惟一驗證
["username","unique"]
["username","unique","targetAttribute"=>"province"]
url驗證
["website","url"]
["website","url","validSchemes"=>["http","https"]]

Session&Cookie

Session被封裝成一個應用組件,直接經過Yii::$app->session來訪問;Cookie經過Request和Response來操做。前端

Session

得到session

$session = Yii::$app->session;java

檢查session是否開啓
Yii::$app->session->isActive
開啓一個session
Yii::$app->session->open()
關閉session
Yii::$app->session->close();
銷燬session中全部已註冊的數據
Yii::$app->session->destroy();
訪問一個session
/* 如下三種方法效果等同 */
$language = $session->get('language');
$language = $session['language'];
$language = isset($_SESSION['language']) ? $_SESSION['language'] : null;
設置一個session
/* 如下三種方法效果等同 */
$session->set('language', 'en-US');
$session['language'] = 'en-US';
$_SESSION['language'] = 'en-US';
刪除一個session變量
/* 下面三種方法效果等同 */
$session->remove('language');
unset($session['language']);
unset($_SESSION['language']);
檢查一個session變量是否存在
/* 如下三種方法效果一致 */
if ($session->has('language')) ...
if (isset($session['language'])) ...
if (isset($_SESSION['language'])) ...
獲取cookie
$cookies = Yii::$app->request->cookies;
設置cookie
$cookies = Yii::$app->response->cookies;
獲取一個cookie值
$language = $cookies->getValue('language', 'en'); //若是獲取language失敗,則返回"en"代替
另外一種獲取cookie值方法
if (($cookie = $cookies->get('language')) !== null) {
    $language = $cookie->value;
}
數組方式獲取cookie值
if (isset($cookies['language'])) {
    $language = $cookies['language']->value;
}
檢查一個cookie是否存在
if ($cookies->has('language')) ...
if (isset($cookies['language'])) ...
新增一個cookie
$cookies->add(new \yii\web\Cookie([
    'name' => 'language',
    'value' => 'zh-CN',
]));
刪除一個cookie
$cookies->remove('language');
unset($cookies['language']);

Request

Request 被配置爲一個應用組件,咱們能夠經過Yii::$app->request訪問它。git

URL相關

得到當前請求的絕對url
Yii::$app->request->getAbsoluteUrl();
返回一個請求URL的hostInfo部分
Yii::$app->request->getHostInfo();
得到URL問號後的參數字符串
Yii::$app->request->getQueryString()
返回服務器端口
Yii::$app->request->getServerPort();

HTTP頭

返回用戶接受的內容類型
Yii::$app->request-> getAcceptableContentTypes (); //Header Accept
返回用戶可接受的語言
Yii::$app->request-> getAcceptableLanguages(); //Header Accept-Language
返回GET/POST請求
Yii::$app->request->get();
Yii::$app->request->get("id");
Yii::$app->request->POST();
Yii::$app->request->POST("username");
判斷請求類型(返回boolean)
Yii::$app->request->isAjax //判斷是否爲ajax請求
Yii::$app->request->isConsoleRequest //判斷是否爲控制發起的請求
Yii::$app->request->isDelete //判斷是否爲DELETE請求
Yii::$app->request->isGet //判斷是否爲GET請求
Yii::$app->request->isPost //判斷是否爲POST請求
Yii::$app->request->isPjax //判斷是否爲isPjax請求

客戶端信息

返回用戶的 IP
Yii::$app->request->getUserIP();

Response

和Request同樣,Response被封裝成Yii的一個組件,你能夠經過Yii::$app->response輕鬆的訪問它。github

Status Code狀態碼

設置一個Status Code
Yii::$app->response->statusCode = 200;
Yii內置的經過異常形式返回狀態碼
yii\web\BadRequestHttpException: status code 400.
yii\web\ConflictHttpException: status code 409.
yii\web\ForbiddenHttpException: status code 403.
yii\web\GoneHttpException: status code 410.
yii\web\MethodNotAllowedHttpException: status code 405.
yii\web\NotAcceptableHttpException: status code 406.
yii\web\NotFoundHttpException: status code 404.
yii\web\ServerErrorHttpException: status code 500.
yii\web\TooManyRequestsHttpException: status code 429.
yii\web\UnauthorizedHttpException: status code 401.
yii\web\UnsupportedMediaTypeHttpException: status code 415.
拋出其餘Status Code
throw new \yii\web\HttpException(402); //若是系統沒有,能夠經過HttpException本身寫狀態碼
throw new \yii\web\HttpException(402,"message");

HTTP Headers

添加設置刪除Http Headers內容
$headers = Yii::$app->response->headers;
add a Pragma header. Existing Pragma headers will NOT be overwritten.
$headers->add('Pragma', 'no-cache');
set a Pragma header. Any existing Pragma headers will be discarded.
$headers->set('Pragma', 'no-cache');
remove Pragma header(s) and return the removed Pragma header values in an array
$values = $headers->remove('Pragma');

Response Body

相應主體
Yii::$app->response->content = 'hello world!';

ActiveForm

重點!列出最經常使用的ActiveForm方法。web

Html

經過Html類的一些靜態方法生成Html標籤。ajax

生成Html標籤方法

生成一個超級連接
Html::a('連接的文本', $url);
經過Yii2的路由生成一個連接
Html::a('連接文本', Url::to(['/site/index'], true));
Html::a('連接文本', Yii::$app->urlManager->createUrl(['/site/index']));
生成一個圖片連接
Html::img("/images/logo.png",['class'=>'img']);
生成一個按鈕
Html::button("按鈕文本",['class'=>'button-action']);
發送郵件連接
Html::mailto("阿北",'abei@nai8.me',$options);
生成有序列表
$list = ['china','usa'];
Html::ol($list);
生成無需列表
$list = ['china','usa','japan'];
Html::ul($list);
生成javascript代碼
Html::script("alert('hello world');")
生成style代碼
Html::style("color:#F60");
Html::style(".list {background:#FFF;}");

文件引用及編碼

生成一個css引用連接
Html::cssFile("http://baidu.com/style.css",[]);
生成一個js文件引用
Html::jsFile($url,[]);
把字符 "<" (小於)和 ">" (大於)轉換爲HTML實體
Html::encode($html);
將特點的HTML實體轉化爲>和<
Html::decode($string);

Alias

定義和使用

定義一個別名
Yii::setAlias('@baidu', 'http://www.baidu.com');
得到一個別名
Yii::getAlias($name);
得到Yii框架所在的目錄
Yii::getAlias('@yii')
正在運行的應用的根目錄
Yii::getAlias('@app')
Composer第三方庫所在目錄
Yii::getAlias("@vendor")
bower庫所在位置
Yii::getAlias("@bower");
npm庫所在位置
Yii::getAlias("@npm");
運行時存放文件路徑
Yii::getAlias("@runtime");
index.php所在目錄
Yii::getAlias("@webroot");
當前應用的根URL,主要用於前端。
Yii::getAlias("@web");
高級版-通用文件夾
Yii::getAlias("@common");
高級版-前臺應用所在位置
Yii::getAlias("@frontend");
高級版-後臺應用所在位置
Yii::getAlias("@backend");
命令行庫所在位置
Yii::getAlias("@console");

Query Builder

主要解決DAO在查詢語句上的繁瑣問題,無需輸入原生SQL語句就能夠完成數據庫檢索。

基本用法

使用Query Builder須要使用的類
$query = (new \yii\db\Query());
//yii2使用Query對象來採集SQL的各個部分,而後由Query Builder組成SQL語句後由DAO發給數據庫得到請求。
SELECT方法
$query->select("id,username"); //字符串形式
$query->select(['id','username']); //數組形式
$query->select(["userId"=>"id","fName"=>"user.frist_name"]); //起別名
$query->select(["full_name"=>"CONCAT(id,'-',username)"]); //支持MYSQL函數
FROM方法
$query->from("user"); //字符串形式
$query->from(["u"=>"user"]); //數據表別名
過濾掉重複記錄
$query->select("username")->distinct()->from("user"); //distinct
WHERE函數用法
/* 傳遞字符串 */
$query->where("id = 1");
$query->where("id = :id")->addParams([":id"=>1]);
$query->where("id = :id",[":id"=>1]);

/* 傳遞數組 */
$query->where(["username"=>"abei","age"=>[20,19,26]])->from("user"); //select * from user where username="abei" AND age in (20,19,26)

/* 操做符 */
$query->where([">","id",10]); //id > 10
$query->where(["<","id",10]); //id < 10
$query->where(["<>","id",10]); //id <> 10
$query->where(["in","id",[10,12]]); //id in (10,20)
$query->where(["not in","id",[10,12]]); //id not in (10,20)
$query->where(["and","id=1","id=2"]); id=1 AND id=2
$query->where(['or', ['type' => [7, 8, 9]], ['id' => [1, 2, 3]]]); //(type IN (7, 8, 9) OR (id IN (1, 2, 3)))
$query->where(["between", 'id', 1, 10]); //id between 1 AND 10
$query->where(["not",["id"=>5]]); //not (id=5)
$query->where(["not between","id",1,10]); //id not between 1 AND 10
$query->where(["like","username","abei"]); //username like "%abei%"
$query->where([['like', 'username', ['abei', 'liuhuan']]]); //username like "%abei%" AND username like "%liuhuan%"
$query->where(['like', 'username', '%abei', false]); //username like "%abei"
$query->where(["or like", 'username', ['abei', 'liuhuan']]); //username like "%abei%" OR username like "%liuhuan%",只做用於範圍爲數組的形式
$query->where(["not like",xxxxx]); //與like用法一致
$query->where(["or not like",xxx]) //與not like用法一致
一個要單獨說明的exists
/* EXISTS用於檢查子查詢是否至少會返回一行數據,該子查詢實際上並不返回任何數據,而是返回值True或False */
$query->where(['exists', (new Query())->select('id')->from('user')->where(['id' => 1])]);
ORDER BY 方法
$query->orderBy("id DESC");
$query->orderBy(["id"=>SORT_DESC]);
$query->orderBy(["id"=>SORT_DESC,'create_time'=>SORT_ASC]);
GROUP BY && HAVING
$query->groupBy(["username"]);
$query->groupBy(["id"])->having([">",'id',20]);
獲取生成的SQL語句
$query->createCommand()->sql;

得到查詢結果

獲取全部結果
$query->all(); //二位數組
獲取一條記錄
$query->one();
檢查一個數據庫中是否含有某個表
(new \yii\db\Query)->from('user')->exists();
獲取count
$query->count();
獲取一個值
$query->scalar();
獲取一列值
$query->column(); //一位數組

一個例子

獲取一個user表的內容
$query = new \yii\db\Query;
$query->from("user");
$query->select(["fname"=>"username"]);
$query->where([">",'id',10]);
$query->all();

FileHelper

幾個經常使用也好用的文件幫助方法

基本方法
// 遍歷一個文件夾下文件&子文件夾
FileHelper::findFiles('/path/to/search/');
FileHelper::findFiles('.', ['only' => ['*.php', '*.txt']]); // 只返回php和txt文件
FileHelper::findFiles('.', ['except' => ['*.php', '*.txt']]); // 排除php和txt文件
// 得到指定文件的MIME類型
FileHelper::getMimeType('/path/to/img.jpeg');
// 複製文件夾
FileHelper::copyDirectory($src, $dst, $options = [])
// 刪除一個目錄及內容
FileHelper::removeDirectory($dir, $options = [])
// 生成一個文件夾(同時設置權限)
FileHelper::createDirectory($path, $mode = 0775, $recursive = true)
參考:

1.http://nai8.me/tool-sc.html

相關文章
相關標籤/搜索