Yii2框架学习
环境要求
yii2: Yii.2.0.6-advanced
php:>= 5.4
yii2亮点
1、采用标准和最新技术
2、坚实的基础类
3、开发工具
4、安全
5、数据库
(new query)
-> from(‘customer’)
-> where([’’ => ‘’])
-> orderBy(‘id’)
-> asArray()
-> all();
6、RESTFUL APIS
7、缓存
8、表单
9、身份验证和授权
10、小插件
11、辅助类
12、国际化
13、模板引擎
14、测试
15、应用程序模板
16、扩展
17、入门
composer create-project yiisoft/yii2-app-basic basic 2.0.0
localhost/basic/web/index.php
使用composer依赖管理工具:composer
gii生成器:提高工作效率
活动记录(active record)
强大的缓存机制
学习yii2framework的2个重要网站
www.yiiframework.com
https://github.com/yiisoft/yii2
基础入门
composer安装Yii2.0框架
composer安装:https://blog.csdn.net/qq_28286687/article/details/106179768
Packagist仓库:https://packagist.org
搜索yiisoft/yii2-app-basic,点击进入可看需要的环境
composer安装流程
composer安装yii2
先安装composer(Composer安装与使用、Composer各大厂商镜像地址)
升级composer( composer self-update)
composer global require “fxp/composer-asset-plugin:~1.0.0”
这将在一个名为 basic 的目录中安装Yii应用程序模板的最新稳定版本。 如果需要,您可以选择不同的目录名称
composer create-project yiisoft/yii2-app-basic basic
composer install (没有出现vender文件夹)
如果你想安装 Yii 的最新开发版本,可以使用下面的命令代替
composer create-project --prefer-dist --stability=dev yiisoft/yii2-app-basic basic
归档文件安装
1、下载地址:http://www.yiiframework.com/download/
2、修改 config/web.php 文件,给 cookieValidationKey 配置项添加一个密钥(若你通过 Composer 安装,则此步骤会自动完成)
3、// !!! 在下面插入一段密钥(若为空) - 以供 cookie validation 的需要
‘cookieValidationKey’ => ‘在此处输入你的密钥’
Yii2.0框架参考文档
• 中文文档:http://www.yiichina.com/doc/guide/2.0
• 英文文档:http://www.yiiframework.com/doc-2.0/guide-index.html
配置文件httpd.conf
LoadModule rewrite_module modules/mod_rewrite.so
LoadModule vhost_alias_module modules/mod_vhost_alias.so
配置域名
访问yii2.hd
访问指定控制器中的方法
方法index要加上action为actionIndex
访问方式为:http://yii2.hd/index.php?r=home%2Findex
<?php
namespace app\controllers;
use yii\web\Controller;
class HomeController extends Controller
{
public function actionIndex(){
echo 1;
}
}
自定义全局工具函数
在根目录下创建helper文件夹,在helper文件下创建function.php文件
在根目录的web文件夹下找到入口文件index.php,配置
require DIR . ‘/…/helper/function.php’;
访问 http://yii2.hd/index.php?r=home%2Findex
获取get或者post值
public function actionIndex()
{
// $data = [
// 'name' => 'bob',
// 'age' => '20'
// ];
//
// p($data);
$request = \Yii::$app -> request;
// # id默认为1
// $id = $request -> get('id',1);
// dd($id);
dd($request -> isGet);
dd($request -> isPost);
}
获取用户ip
KaTeX parse error: Undefined control sequence: \Yii at position 11: request = \̲Y̲i̲i̲::app -> request;
dd($request -> userIP);
compact方法分配多个参数
return $this -> renderPartial(‘index’,compact(‘user’,‘article’));
渲染
render 和renderpartial之间最大的区别就是:一个是渲染父模板,一个不渲
染父模板。
• 其中render 输出父模板的内容,将渲染的内容,嵌入父模板。
• renderPartial 则不输出父模板的内容。只对本次渲染的局部内容,进行输出
return $this ->renderPartial('index',compact('user','article'));
return $this -> render('index',compact('user','article'));
视图打印
<h2><?php echo $user['username'];?>,<?php echo $user['age'];?>岁</h2>
<h2><?php echo $article['title'];?></h2>
<?= $str;?>
字符串过滤
控制器中
$data = [
‘str’ => ‘Hello,world!’
];
return $this -> render('index',$data);
视图中
<?php
use yii\helpers\Html;
use yii\helpers\HtmlPurifier;
?>
//原样输出
**<?= Html::encode($str) ?>**
//过滤js。html代码
<p><?= HtmlPurifier::process($str) ?></p>
模板的继承与互相调用
在home控制器中定义继承模板以及设置渲染模式为render
public $layout = 'home';
return $this -> render('about');
在view文件夹的layouts文件夹下创建home.php文件,内容为:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Hello,home</h1>
// 重要语句
<?= $content;?>
</body>
</html>
在home文件夹下创建about.php,内容为:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h2>Hello,about</h2>
</body>
</html>
访问http://yii2.hd/index.php?r=home/about,继承了layouts中的home.php中的内容
相互调用,在views文件夹中的home文件中的index.php文件,内容为:
<h1>Hello,index</h1>
<?= $this -> render('about') ?>
访问http://yii2.hd/index.php?r=home/index,相互调用about.php中的内容
模型创建及数据读取
在根目录下的config文件夹下的db.php文件中配置数据库
在models目录下创建Article.php文件,内容如下:
<?php
namespace app\models;
use \yii\db\ActiveRecord;
class Article extends ActiveRecord{
}
在控制器中,内容如下:
use app\models\Article;
$sql = "select * from article where id = 1";
$r = Article::findBySql($sql) -> all();
dd($r);
防止sql注入(使用占位符)
$request = \Yii::$app -> request;
$id = $request -> get('id');
$sql = "select * from article where id = :id";
$r = Article::findBySql($sql,[':id' => $id]) -> all();
dd($r);
sql基本操作
// $request = \Yii::$app -> request;
// $id = $request -> get('id');
// $sql = "select * from article where id = :id";
// $r = Article::findBySql($sql,[':id' => $id]) -> all();
// dd($r);
// 获取全部数据
// $data = Article::find() -> all();
// 查询单条数据
// $data = Article::find() -> where(['id' => 1]) -> all();
// $data = Article::find() -> where(['>','id',3]) -> all();
// $data = Article::find() -> where(['between','id',2,5]) -> all();
// $data = Article::find() -> where(['like','title','巴菲特']) -> all();
// $data = Article::find() -> where(['id' => 1]) -> one();
// $data = Article::findOne(5);
$data = Article::findAll([3,4,5]);
添加记录
// 添加
$article = new Article();
$article -> title = '阿里3万亿GMV水分几何?';
$article -> num = 4;
// $data = $article -> insert();
$data = $article -> save();
$id = $article -> attributes['id'];
dd($id);
修改
// $article = Article::findOne(10);
// $article -> title = '玫瑰金';
$data = $article -> update(); //正确返回1
// $data = $article -> save(); //返回的是boolean值
// dd($data);
// 修改查看字数(单个字段)
$data = Article::updateAllCounters(['num' => 1],['id' => 8]);
dd($data);
删除
删除单条数据
$article = Article::findOne(13);
$data = $article -> delete();
删除多条数据
$data = Article::deleteAll(“id > :id and num < :num”,[’:id’ => 10,’:num’ => 100]);
一对多
在models中创建category.php文件,代码如下
<?php
namespace app\models;
use \yii\db\ActiveRecord;
class Category extends ActiveRecord{
public function getArticles(){
return $this -> hasMany(Article::className(),['cate_id' => 'id']);
}
}
在控制器中进行调用,代码如下:
$category = Category::findOne(1);
$articles = $category -> getArticles()
-> asArray()
-> all();
一对一
在models中创建Article.php,代码如下:
<?php
namespace app\models;
use \yii\db\ActiveRecord;
class Article extends ActiveRecord{
public function getCategory(){
return $this -> hasOne(Category::className(),['id' => 'cate_id']) -> asArray();
}
}
在控制器中如调用,代码如下:
$articles = Article::find() -> all();
foreach($articles as $article){
$category = $article -> category;
var_dump($category);
}
使用gii生成model