安装
安装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官网
通过composer.json安装扩展
composer
install
更新本地composer扩展库
composer
update
直接安装某个composer扩展
composer
require [options] [--] [vendor/packages]
...
DAO
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]);
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
日志功能
trace
Yii::trace(
$message,
$category)
info
Yii::info(
$message,
$category)
warning
Yii::warning(
$message,
$category)
error
Yii::error(
$message,
$category)
Validator
数据验证,最常用于模型的rules()函数
required 必须值
[
"username",
'required']
[[
"username",
"email"],
'required']
[[
"username"],
'required',
"message"=>
"{attribute}必须填写"]
[[
"username"],
'required',
'requiredValue'=>
"abei"]
Email验证
[
"email",
'email']
[[
"email",
"work_email"],
'email']
Boolean验证
[
'sex',
'boolean',
'trueValue' =>
true,
'falseValue' =>
false,
'strict' =>
true];
captcha验证码
[
'verificationCode',
'captcha'];
compare比较
[
'username',
'compare',
'compareAttribute' =>
'province',
'message'=>
'username和province必须一样']
[
'age',
'compare',
'compareValue' =>
30,
'operator' =>
'>=',
'type' =>
'number'];
date验证
[
"birth",
"date",
"format"=>
"Y-m-d"]
default验证
[
'age',
'default',
'value'=>
null]
[
'country',
'default',
'value'=>
'USA']
[[
'from',
'to'],
'default',
'value'=>
function($model,$attribute){
return date(
'Y-m-d', strtotime(
$attribute ===
'to' ?
'+3 days' :
'+6 days'));
}]
double/number验证
[
'v',
'double']
[
'v',
'double',
'max'=>
90,
'min'=>
1]
数组各元素验证
[
"categoryIds",
"each",
"rule"=>[
'integer']]
exist是否存在验证
[
"username",
"exist"]
[
"username",
"exist",
"targetAttribute"=>
"province"]
[
"username",
"exist",
'targetAttribute' => [
'username',
'province']]
[[
"username",
"province"],
"exist",
'targetAttribute' => [
'username',
'province']]
file验证
[
'primaryImage',
'file',
'extensions' => [
'png',
'jpg',
'gif'],
'mimeTypes'=>[
"image/*"],
'maxSize' =>
1024*
1024,
'minSize'=>
100*
1024,
'maxFiles'=>
6,
'checkExtensionByMimeType'=>
true],
[[
'username',
'email'],
'filter',
'filter' =>
'trim',
'skipOnArray' =>
true],
[
'phone',
'filter',
'filter' =>
function ($value) {
return $value;
}],
image验证
[
'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 = Yii::
$app->session;
检查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
获取cookie
$cookies = Yii::
$app->request->cookies;
设置cookie
$cookies = Yii::
$app->response->cookies;
获取一个cookie值
$language =
$cookies->getValue(
'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访问它。
获得当前请求的绝对url
Yii::
$app->request->getAbsoluteUrl();
返回一个请求URL的hostInfo部分
Yii::
$app->request->getHostInfo();
获得URL问号后的参数字符串
Yii::
$app->request->getQueryString()
返回服务器端口
Yii::
$app->request->getServerPort();
返回用户接受的内容类型
Yii::
$app->request-> getAcceptableContentTypes ();
返回用户可接受的语言
Yii::
$app->request-> getAcceptableLanguages();
返回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
Yii::
$app->request->isConsoleRequest
Yii::
$app->request->isDelete
Yii::
$app->request->isGet
Yii::
$app->request->isPost
Yii::
$app->request->isPjax
返回用户的 IP
Yii::
$app->request->getUserIP();
Response
和Request一样,Response被封装成Yii的一个组件,你可以通过Yii::$app->response轻松的访问它。
设置一个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);
throw new \yii\web\HttpException(
402,
"message");
$headers = Yii::
$app->response->headers;
$headers->add(
'Pragma',
'no-cache');
$headers->set(
'Pragma',
'no-cache');
remove Pragma header(s) and return the removed Pragma header values in an array
$values =
$headers->remove(
'Pragma');
响应主体
Yii::
$app->response->content =
'hello world!';
返回JSON格式
Yii::
$app->response->format = Response::FORMAT_JSON;
return $results;
查询返回数组形式
$command->queryAll(\PDO::FETCH_ASSOC);
Html
通过Html类的一些静态方法生成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());
SELECT方法
$query->select(
"id,username");
$query->select([
'id',
'username']);
$query->select([
"userId"=>
"id",
"fName"=>
"user.frist_name"]);
$query->select([
"full_name"=>
"CONCAT(id,'-',username)"]);
FROM方法
$query->from(
"user");
$query->from([
"u"=>
"user"]);
过滤掉重复记录
$query->select(
"username")->distinct()->from(
"user");
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");
$query->where([
">",
"id",
10]);
$query->where([
"<",
"id",
10]);
$query->where([
"<>",
"id",
10]);
$query->where([
"in",
"id",[
10,
12]]);
$query->where([
"not in",
"id",[
10,
12]]);
$query->where([
"and",
"id=1",
"id=2"]); id=
1 AND id=
2
$query->where([
'or', [
'type' => [
7,
8,
9]], [
'id' => [
1,
2,
3]]]);
$query->where([
"between",
'id',
1,
10]);
$query->where([
"not",[
"id"=>
5]]);
$query->where([
"not between",
"id",
1,
10]);
$query->where([
"like",
"username",
"abei"]);
转载请注明原文地址: https://ju.6miu.com/read-668505.html