composer global require "fxp/composer-asset-plugin:^1.2.0"
composer create-project --prefer-dist yiisoft/yii2-app-basic basic
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官网
composer install
composer update
composer require [options] [--] [vendor/packages]...
Yii的数据库读取对象,在PDO之上,DAO后有了Query Builder和AR
$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]);
Yii::$app->db->createCommand('INSERT INTO user (email, password) VALUES("[email protected]", "test3");')->execute();
Yii::$app->db->createCommand()->insert('user', [
'email' => '[email protected]',
'password' => 'changeme7',
'first_name' => 'Test'
])->execute();
Yii::$app->db->createCommand()->batchInsert('user', ['email', 'password', 'first_name'],
[
['[email protected]', 'changeme7', 'James'],
['[email protected]', 'changeme7', 'Linda']
['[email protected]', '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();
日志功能
Yii::trace($message,$category) //记录一条消息去跟踪一段代码是怎样运行的。这主要在开发的时候使用。
Yii::info($message,$category) //记录一条消息来传达一些有用的信息。
Yii::warning($message,$category) //记录一个警告消息用来指示一些已经发生的意外。
Yii::error($message,$category) //记录一个致命的错误,这个错误应该尽快被检查。
数据验证,最常用于模型的rules()函数
["username",'required']
[["username","email"],'required']
[["username"],'required',"message"=>"{attribute}必须填写"]
[["username"],'required','requiredValue'=>"abei"] //用户填写的值必须等于requiredValue才能通过验证。
["email",'email']
[["email","work_email"],'email']
['sex', 'boolean', 'trueValue' => true, 'falseValue' => false, 'strict' => true]; //可以认为置顶 true / false 值。
['verificationCode', 'captcha'];
['username', 'compare', 'compareAttribute' => 'province','message'=>'username和province必须一样'] //错误信息将提示给username
['age', 'compare', 'compareValue' => 30, 'operator' => '>=','type' => 'number'];//compareValue:比较常量值 operator:比较操作符 type为值类型,默认为string,会一个每个字符对比,若为number则直接判断数值
//operator 待选值==、===、!=、!==、>、>=、<、<=
["birth","date","format"=>"Y-m-d"]
['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'));
}]
['v','double'] //判断v是否为数字
['v','double','max'=>90,'min'=>1]//判断v是否为数字且大于等于1、小于等于90
["categoryIds","each","rule"=>['integer']]
/* 所谓对存在的检查实质为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中存在
/* 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;
}],
/* 上传png/jpg格式,最大宽度不能超过1000px,最小宽度不能低于100px,最大高度不能高于1000px。最小高度不能低于100px */
['primaryImage', 'image', 'extensions' => 'png, jpg','minWidth' => 100, 'maxWidth' => 1000,'minHeight' => 100, 'maxHeight' => 1000]
["ip_addess","ip"]
["level","in","range"=>[1,2,3]]
["age",'integer'];
["age","integer","max"=>90,"min"=>1]
["username","match","pattern"=>"/^[a-z]\w*$/i"]
["description","safe"]
["username","string","length"=>[4,24]];
["username","string","min"=>4];
["username","string","max"=>32];
["username","string","encoding"=>"UTF-8"];
["username","unique"]
["username","unique","targetAttribute"=>"province"]
["website","url"]
["website","url","validSchemes"=>["http","https"]]
Session被封装成一个应用组件,直接通过Yii::$app->session来访问;Cookie通过Request和Response来操作。
$session = Yii::$app->session;
Yii::$app->session->isActive
Yii::$app->session->open()
Yii::$app->session->close();
Yii::$app->session->destroy();
/* 以下三种方法效果等同 */
$language = $session->get('language');
$language = $session['language'];
$language = isset($_SESSION['language']) ? $_SESSION['language'] : null;
/* 以下三种方法效果等同 */
$session->set('language', 'en-US');
$session['language'] = 'en-US';
$_SESSION['language'] = 'en-US';
/* 下面三种方法效果等同 */
$session->remove('language');
unset($session['language']);
unset($_SESSION['language']);
/* 以下三种方法效果一致 */
if ($session->has('language')) ...
if (isset($session['language'])) ...
if (isset($_SESSION['language'])) ...
$cookies = Yii::$app->request->cookies;
$cookies = Yii::$app->response->cookies;
$language = $cookies->getValue('language', 'en'); //如果获取language失败,则返回"en"代替
if (($cookie = $cookies->get('language')) !== null) {
$language = $cookie->value;
}
if (isset($cookies['language'])) {
$language = $cookies['language']->value;
}
if ($cookies->has('language')) ...
if (isset($cookies['language'])) ...
$cookies->add(new \yii\web\Cookie([
'name' => 'language',
'value' => 'zh-CN',
]));
$cookies->remove('language');
unset($cookies['language']);
Request 被配置为一个应用组件,我们可以通过Yii::$app->request访问它。
Yii::$app->request->getAbsoluteUrl();
Yii::$app->request->getHostInfo();
Yii::$app->request->getQueryString()
Yii::$app->request->getServerPort();
Yii::$app->request-> getAcceptableContentTypes (); //Header Accept
Yii::$app->request-> getAcceptableLanguages(); //Header Accept-Language
Yii::$app->request->get();
Yii::$app->request->get("id");
Yii::$app->request->POST();
Yii::$app->request->POST("username");
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请求
Yii::$app->request->getUserIP();
和Request一样,Response被封装成Yii的一个组件,你可以通过Yii::$app->response轻松的访问它。
Yii::$app->response->statusCode = 200;
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.
throw new \yii\web\HttpException(402); //如果系统没有,可以通过HttpException自己写状态码
throw new \yii\web\HttpException(402,"message");
$headers = Yii::$app->response->headers;
$headers->add('Pragma', 'no-cache');
$headers->set('Pragma', 'no-cache');
$values = $headers->remove('Pragma');
Yii::$app->response->content = 'hello world!';
Yii::$app->response->format = Response::FORMAT_JSON;
return $results;
$command->queryAll(\PDO::FETCH_ASSOC);
通过Html类的一些静态方法生成Html标签。
Html::a('链接的文本', $url);
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("阿北",'[email protected]',$options);
$list = ['china','usa'];
Html::ol($list);
$list = ['china','usa','japan'];
Html::ul($list);
Html::script("alert('hello world');")
Html::style("color:#F60");
Html::style(".list {background:#FFF;}");
Html::cssFile("http://baidu.com/style.css",[]);
Html::jsFile($url,[]);
Html::encode($html);
Html::decode($string);
定义和使用
Yii::setAlias('@baidu', 'http://www.baidu.com');
Yii::getAlias($name);
Yii::getAlias('@yii')
Yii::getAlias('@app')
Yii::getAlias("@vendor")
Yii::getAlias("@bower");
Yii::getAlias("@npm");
Yii::getAlias("@runtime");
Yii::getAlias("@webroot");
Yii::getAlias("@web");
Yii::getAlias("@common");
Yii::getAlias("@frontend");
Yii::getAlias("@backend");
Yii::getAlias("@console");
主要解决DAO在查询语句上的繁琐问题,无需输入原生SQL语句就可以完成数据库检索。
$query = (new \yii\db\Query());
//yii2使用Query对象来采集SQL的各个部分,然后由Query Builder组成SQL语句后由DAO发给数据库获得请求。
$query->select("id,username"); //字符串形式
$query->select(['id','username']); //数组形式
$query->select(["userId"=>"id","fName"=>"user.frist_name"]); //起别名
$query->select(["full_name"=>"CONCAT(id,'-',username)"]); //支持MYSQL函数
$query->from("user"); //字符串形式
$query->from(["u"=>"user"]); //数据表别名
$query->select("username")->distinct()->from("user"); //distinct
/* 传递字符串 */
$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用于检查子查询是否至少会返回一行数据,该子查询实际上并不返回任何数据,而是返回值True或False */
$query->where(['exists', (new Query())->select('id')->from('user')->where(['id' => 1])]);
$query->orderBy("id DESC");
$query->orderBy(["id"=>SORT_DESC]);
$query->orderBy(["id"=>SORT_DESC,'create_time'=>SORT_ASC]);
$query->groupBy(["username"]);
$query->groupBy(["id"])->having([">",'id',20]);
$query->createCommand()->sql;
$query->all(); //二维数组
$query->one();
(new \yii\db\Query)->from('user')->exists();
$query->count();
$query->scalar();
$query->column(); //一维数组
$query = new \yii\db\Query;
$query->from("user");
$query->select(["fname"=>"username"]);
$query->where([">",'id',10]);
$query->all();
[1] http://www.yiiframework.com/doc-2.0/guide-index.html
[2] http://nai8.me/tool-sc.html