Yii 框架学习--01 框架入门
Yii 是一個高性能的,適用于開發 WEB2.0 應用的 PHP 框架。
Yii目前有兩個主要的版本: 2.0 和 1.1。本文以YII 2.0.7為例。
環境需求
Yii2.0 框架有一些系統上的需求:
PHP 版本 >= 5.4
Mcrypt PHP 擴展
OpenSSL PHP 擴展
Mbstring PHP 擴展
特點
安裝
Yii可以通過Composer或者壓縮包安裝。
使用Composer安裝
與安裝Laravel框架類似,很多人會卡在這一步。要么是不會Composer,要么就是無法使用Composer安裝。
如果還不知道Composer,先去學習了解了解:
http://www.cnblogs.com/52fhy/p/5246013.html
如果無法使用用Composer安裝,很有可能是倉庫訪問不了,即被墻了。先更新Composer倉庫源:
composer config -g repo.packagist composer https://packagist.phpcomposer.com接下來正式開始安裝吧!
這里以YII 2.0 版本為例(PHP 版本 >= 5.4)。
yii2的高級版和基本版的區別在哪里呢?
其實沒太大區別。yii2-app-basic只有一個web應用,而yii2-app-advanced是默認帶了前臺和后臺兩個web應用,將兩個應用整合在一個project里面,然后用common應用存放一些兩個應用公共的一些東西。
https://www.zhihu.com/question/27916823
這里以安裝yii2-app-basic為例。
等待安裝(過程會比較長,期間還要github的token,建議還是下載一鍵安裝包吧):
Installing yiisoft/yii2-app-basic (2.0.7)- Installing yiisoft/yii2-app-basic (2.0.7)Downloading: 100%Created project in yii2 Loading composer repositories with package information...Token (hidden): Token stored successfully.- Installing yiisoft/yii2-composer (2.0.3)Downloading: 100%- Installing ezyang/htmlpurifier (v4.6.0)Downloading: 100%- Installing cebe/markdown (1.1.0)Downloading: 100%- Installing bower-asset/jquery (2.1.4)Downloading: 100%- Installing bower-asset/jquery.inputmask (3.1.63)Downloading: 100%- Installing bower-asset/punycode (v1.3.2)Downloading: 100%- Installing bower-asset/yii2-pjax (v2.0.4)Downloading: 100%- Installing yiisoft/yii2 (2.0.4)Downloading: 100%- Installing swiftmailer/swiftmailer (v5.4.1)Downloading: 100%- Installing yiisoft/yii2-swiftmailer (2.0.4)Downloading: 100%- Installing yiisoft/yii2-codeception (2.0.4)Downloading: 100%- Installing bower-asset/bootstrap (v3.3.5)Downloading: 100%- Installing yiisoft/yii2-bootstrap (2.0.4)Downloading: 100%- Installing yiisoft/yii2-debug (2.0.4)Downloading: 100%- Installing bower-asset/typeahead.js (v0.10.5)Downloading: 100%- Installing phpspec/php-diff (v1.0.2)Downloading: 100%- Installing yiisoft/yii2-gii (2.0.4)Downloading: 100%- Installing fzaninotto/faker (v1.5.0)Downloading: 100%- Installing yiisoft/yii2-faker (2.0.3)Downloading: 100%fzaninotto/faker suggests installing ext-intl (*) Writing lock file Generating autoload files chmod('runtime', 0777)...done. chmod('web/assets', 0777)...done. chmod('yii', 0755)...done. ...安裝過程中注意的:
1、提前安裝好Composer 2、安裝插件:php composer.phar global require "fxp/composer-asset-plugin:1.0.0" 3、通過命令行開始安裝: 這一步耗時比較長,因為它在下載yii2框架。需要github賬號,若提示安裝過程中輸入你的GitHub的用戶名和密碼。那就輸入它們并繼續即可。如果需要輸入token,注冊登錄github之后,在setting->Personal access tokens這里生成一個token,然后輸入就可以了。復制粘貼(隱藏的),確認。創建成功會在指定的項目根目錄,如yii2目錄下生成web\文件夾,里面有入口文件index.php。
安裝完便可以訪問了:
http://localhost/yii2/web/index.php顯示:
Congratulations! You have successfully created your Yii-powered application.一鍵安裝包下載
一鍵安裝包是在 YII 源碼的基礎上安裝了依賴庫(也就是已經做過 composer install,已經有了 vendor 目錄),對于剛接觸 YII2 或者使用 Composer 受挫的用戶能夠提供快速上手實踐 YII2 的捷徑。
下載以下歸檔文件之一,然后將其解壓縮到一個Web可訪問的文件夾:
yii2-app-basic
https://github.com/yiisoft/yii2/releases/download/2.0.7/yii-basic-app-2.0.7.tgz
yii2-app-advanced
https://github.com/yiisoft/yii2/releases/download/2.0.7/yii-advanced-app-2.0.7.tgz
下載很慢的話直接去我的百度云下載:
http://pan.baidu.com/s/1gfEsVar
注意:
通過安裝包安裝的需要在配置文件config/web.php,給 cookieValidationKey 配置項輸入你的密鑰:
cookieValidationKey的作用暫時不做詳細講解。
解壓yii-basic-app-2.0.7.tgz到服務器www目錄,并更名為yii2。修改config/web.php填寫密鑰,然后訪問:
http://localhost/yii2/web/index.php提示:
Congratulations! You have successfully created your Yii-powered application.ok了!
下文均以yii-basic-app-2.0.7.tgz源碼進行搭建demo講解。
項目結構
yii-basic-app
assets/ assets資源定義 commands/ 包含控制臺命令類HelloController.php config/ 應用配置db.php 數據庫配置params.php 通用參數配置web.php web配置console.php cli配置 controllers/ 控制器SiteController.php mail/ e-mails的視圖文件 models/ 模型User.php runtime/ 包含 Yii 在運行時生成的文件,例如日志和緩存文件 tests/ contains various tests for the basic application vendor/ 包含已經安裝的 Composer 包,包括 Yii 框架自身 views/ 視圖 web/ 入口文件和靜態資源assets/ 包含 Yii 發布的資源文件(javascript 和 css)index.php 應用入口文件 composer.json Composer 配置文件, 描述包信息 yii Yii 控制臺命令執行腳本 yii.bat Yii 控制臺命令執行腳本(Windows)關于yii-basic-app說明:
在瀏覽器底部可以看到一個工具欄。這是 Yii 提供的很有用的調試工具,可以記錄并顯示大量的調試信息,例如日志信息,響應狀態,數據庫查詢等等。
Yii 實現了模型-視圖-控制器 (MVC)設計模式,這點在上述目錄結構中也得以體現。 models 目錄包含了所有模型類,views 目錄包含了所有視圖腳本,controllers 目錄包含了所有控制器類。
Yii 流程:
控制器(Controllers)
控制器路徑:controllers。使用 app\controllers 命名空間。
示例:TestController.php
namespace app\controllers;use Yii; use yii\web\Controller;class TestController extends Controller{/*** index* Yii 使用 action 前綴區分普通方法和操作。action 前綴后面的名稱被映射為操作的 ID*/public function actionIndex($msg = 'hello') {//index 視圖應該存為 views/test/index.php 文件//按 views/控制器 ID/視圖名.php 路徑加載 PHP 文件return $this->render('index', array('msg' => $msg));}/*** my-index* 操作 ID 總是被以小寫處理,如果一個操作 ID 由多個單詞組成,單詞之間將由連字符連接(如 my-index);* 操作 ID 映射為方法名時移除了連字符,將每個單詞首字母大寫,并加上 action 前綴。例子:操作 ID my-index 相當于方法名 actionMyIndex*/public function actionMyIndex($msg = 'hello') {return $this->render('my-index', array('msg' => $msg));} }創建對應的視圖:
views/test/index.php
views/test/my-index.php
訪問:
http://localhost/yii2/web/index.php?r=test/index&msg=hello http://localhost/yii2/web/index.php?r=test/my-index&msg=welcome生成url
Yii::$app->urlManager->createUrl('index/test');結果:/yii2/web/index.php?r=index%2Ftest
\yii\helpers\Url::to(array('index/test'));結果:/yii2/web/index.php?r=index%2Ftest
路由(Route)
YII 路由與大多數框架如ThinkPHP、CI類似,是自動化的,不需要單獨去配置。這點與Laravel不同。
URL 中的參數 r 代表路由。路由格式是 控制器 ID/操作 ID。
示例:
http://localhost/yii2/web/index.php?r=test/index&msg=hello代表TestController/actionIndex,其中方法actionIndex接收了一個參數,鍵名是msg,鍵值是hello。
實際上我們使用$_GET也可以獲取URL上的所有參數,包括路由r。
配置
入口文件配置
//開啟debug,應用會保留更多日志信息,如果拋出異常,會顯示詳細的錯誤調用堆棧 defined('YII_DEBUG') or define('YII_DEBUG', true);//環境定義 defined('YII_ENV') or define('YII_ENV', 'dev'); //dev,prod全局配置
包含:
db.php 數據庫配置
params.php 通用參數配置
web.php web配置
console.php cli配置
詳見下章:http://www.cnblogs.com/52fhy/p/5349394.html
模型(Model)
Yii2 模型文件都放在 models 目錄下,以及默認使用 app\models 命名空間。
Yii 里模型的類名與文件名是一模一樣的。例如UserAddress.php對應類UserAddress。建議使用駝峰命名。
示例:models/EntryForm.php
namespace app\models;use yii\base\Model;class EntryForm extends Model {public $name;public $email;/*** 返回數據驗證規則的集合*/public function rules(){return [//name 和 email 值都是必須的[['name', 'email'], 'required'],//email 的值必須滿足email規則驗證['email', 'email'],];} }注意:yii\base\Model 被用于普通模型類的父類并但與數據表無關。真正與數據的CURD相關的是yii\db\ActiveRecord,繼承自 yii\base\Model,增加了數據庫處理。
上面的示例中驗證規則(rules)可以在控制器使用 yii\base\Model::validate() 方法觸發數據驗證。
如何在Controller里使用Model?
需要引入命名空間并實例化模型:
namespace app\controllers;use Yii; use yii\web\Controller; use app\models\EntryForm;//引入命名空間class TestController extends Controller{public function actionIndex($msg = 'hello') {$model = new EntryForm();if ($model->load(Yii::$app->request->post()) && $model->validate()) {return $this->render('index', array('msg' => $msg));}} }表達式 Yii::$app 代表應用實例,它是一個全局可訪問的單例。同時它也是一個服務定位器,能提供 request,response,db 等等特定功能的組件。在上面的代碼里就是使用 request 組件來訪問應用實例收到的 $_POST 數據。
視圖(views)
視圖根路徑:views。
視圖與控制器對應關系:
按 views/控制器 ID/視圖名.php 路徑加載 PHP 文件
以上面的TestController為例,有:
$this->render('index', array('msg' => $msg)); $this->render('my-index', array('msg' => $msg));分別對應:
views/test/index.php views/test/my-index.php即控制器/方法與視圖目錄是一一對應的。
視圖內容其實就是html代碼。為了防止跨站腳本(XSS)攻擊,我們可以在視圖中使用yii\helpers\Html::encode()進行處理:
views/test/index.php
<head><meta charset="utf-8"><title>test</title> </head> <body> use yii\helpers\Html; = Html::encode($msg) </body>視圖可以有子目錄:
$this->render('sub/index', array('msg' => $msg));對應:
views/test/sub/index.php傳遞數據到視圖
$this->render('index', array('msg' => $msg));數據庫操作
數據庫配置
數據庫相關配置文件都在 config/db.php:
return ['class' => 'yii\db\Connection','dsn' => 'mysql:host=localhost;dbname=yii2basic','username' => 'root','password' => '','charset' => 'utf8', ];上面配置的數據庫連接可以在應用中通過 Yii::$app->db 表達式訪問。
為了方便下文繼續演示,這里新建一個數據庫yii2basic,并新建表country:
CREATE TABLE `country` (`id` INT NOT NULL PRIMARY KEY AUTO_INCREMENT,`code` CHAR(2) NOT NULL ,`name` CHAR(52) NOT NULL,`population` INT(11) NOT NULL DEFAULT '0' ) ENGINE=InnoDB DEFAULT CHARSET=utf8;INSERT INTO `country` VALUES (null, 'AU','Australia',18886000); INSERT INTO `country` VALUES (null, 'CA','Canada',1147000); INSERT INTO `country` VALUES (null, 'CN','China',1277558000); INSERT INTO `country` VALUES (null, 'US','United States',278357000);使用模型操作數據
為了使用ActiveRecord里面的方法,這里不再繼承\yii\base\Model,而是繼承\yii\db\ActiveRecord。
這里建立一個模型Country:
<?phpnamespace app\models;use yii\db\ActiveRecord;class Country extends ActiveRecord{}在里面寫任何代碼。只需要像現在這樣,Yii就能根據類名去猜測對應的數據表名。如果類名和數據表名不能直接對應,可以覆寫yii\db\ActiveRecord::tableName() 方法去顯式指定相關表名:
public static function tableName() {return 'country'; }控制器里使用模型:
首先引入命名空間:
然后直接使用模型里的數據庫操作方法:
public function actionListCountry() {//獲取所有$list = Country::find()->orderBy('name')->all();//獲取一條$one = Country::findOne('US');print_r($one->name);//更新/ 修改 name 為 U.S.A. 并在數據庫中保存更改$one->name = 'U.S.A.';$one->save();}Active Record
\yii\db\ActiveQuery繼承自\yii\db\Query。
通過\yii\db\ActiveRecord::find()可獲取\yii\db\ActiveQuery實例。
下面以Customer模型及customer作為演示。
新增(create)
yii\db\ActiveRecord::save() yii\db\ActiveRecord::insert()示例:
$customer = new Customer(); $customer->name = 'Qiang'; $customer->save(); // 等同于 $customer->insert();刪除(delete)
yii\db\ActiveRecord::delete()//靜態方法,作用于整張表 yii\db\ActiveRecord::deleteAll()示例:
// 刪除已有客戶記錄 $customer = Customer::findOne($id); $customer->delete();// 刪除多個年齡大于20,性別為男(Male)的客戶記錄 Customer::deleteAll('age > :age AND gender = :gender', [':age' => 20, ':gender' => 'M']);更新(update)
yii\db\ActiveRecord::save() yii\db\ActiveRecord::update()//靜態方法,作用于整張表 yii\db\ActiveRecord::updateCounters() yii\db\ActiveRecord::updateAll() yii\db\ActiveRecord::updateAllCounters()示例:
$customer = Country::findOne('Li'); $customer->name = 'Qiang'; $customer->save(); // 等同于 $customer->update();// 所有客戶的age(年齡)字段加1: Customer::updateAllCounters(['age' => 1]);查詢(read)
yii\db\ActiveRecord::find() //返回ActiveRecord對象 yii\db\ActiveRecord::findBySql() //通過SQL查詢返回ActiveRecord對象// 兩個快捷方法:直接返回一個或者一組結果 yii\db\ActiveRecord::findOne() //返回第一個匹配到的實例 yii\db\ActiveRecord::findAll() //返回所有find()返回一個ActiveRecord對象,需要使用one()或者all()獲取最終數據。
findBySql()接收SQL,返回一個ActiveRecord對象,需要使用one()或者all()獲取最終數據。
findOne()和findAll()直接返回對象數組,不需要再使用one()或者all()。
都支持靜態方法或者直接調用。
示例:
/**find**/$m = new Country();$m->find()->all();//返回對象 $m->find()->one();//返回對象,僅返回一條記錄 $m->find()->asArray()->all();//asArray()返回數組$m->find()->select('name')->column(); //返回指定字段的數組集合 $m->find()->column();//返回第一個字段的數組集合$m->find()->where(['name'=> 'China'] )->one(); $m->find()->where(['name'=> 'China'] )->all(); $m->find()->where(['name' => 'China', 'code' => 'CN'] )->all(); $m->find()->where(['name'=> 'China'] )->offset(1)->limit(1)->all();$m->find()->orderBy('id DESC')->all(); $m->find()->where(['name'=> 'China'] )->orderBy('code desc')->limit(2)->all();//andWhere與where是一樣的,多個建議使用andWhere、orWhere $m->find()->where(['id' => 1])->count(); $m->find()->where(['id' => 1])->andWhere(['code' => 'CN'])->count(); $m->find()->where(['id' => 1])->orWhere(['code' => 'CN'])->count();//findBySql $m->findBySql('select * from country')->one(); $m->findBySql('select * from country')->all();/* where高級用法:當參數大于2個時且無鍵值對,第一個表示操作符 * [操作符, 操作數1, 操作數2, ...] */ //比較:>,<,=,>=,<= $m->find()->where(['=', 'id', '3'])->all(); //id=3 $m->find()->where(['>', 'id', '3'])->all(); //id>=3//邏輯:and,or $m->find()->where(['and', 'id=5', ['code' => 'CN']])->all();//即 id=5 AND code ='CN';字符型操作數需要用數組表示 $m->find()->where(['or', 'id=5', 'id=1'])->all();//between,not between $m->find()->where(['between', 'id', 1, 3])->all(); //id between 1 AND 3//in,not in $m->find()->where(['in', 'id', [1,2,3]])->all(); //id in (1,2,3)//like,or like, not like,or not like 不支持左右like $m->find()->where(['like', 'name', 'A'])->all(); $m->find()->where(['like', 'name', ['A','B']])->all(); //exists,not exists//其它 $m->find()->scalar(); //此方法返回值的第一行第一列的值 $m->find()->count(); //此方法返回記錄的數量 $m->find()->average(); //此方法返回指定列的平均值 $m->find()->min(); //此方法返回指定列的最小值 $m->find()->max(); //此方法返回指定列的最大值 $m->find()->exists();//此方法返回一個bool值指示是否可以查詢數據//返回數組以 ID 為索引 $m->find()->indexBy('id')->all(); //distinct() 方法來去除重復行 $m->find()->select('name')->distinct()->all(); //SELECT DISTINCT `name` FROM `country`//groupBy,having //SELECT `name`, count(*) as sum FROM `country` GROUP BY `name` $m->find()->select(['name','count(*) as sum'])->groupBy('name')->all(); //SELECT `name`, count(*) as sum FROM `country` GROUP BY `name` HAVING `sum` >= 2 $m->find()->select(['name','count(*) as sum'])->groupBy('name')->having(['>=','sum', 2])->all(); //多表關聯建議使用SQL // yii\db\Query::join($type, $table, $on, $params) 類型(join,left,right),需要join的表,連接條件,可選參數 $m->find()->join('inner','articles', 'country.id = articles.id')->all(); $m->find()->innerJoin('articles', 'country.id = articles.id')->all(); //SELECT * FROM `country` INNER JOIN `articles` ON country.id = articles.id/**findOne(),findAll()**/ Country::findOne(1); // 返回 id 為 1 的數據 Country::findOne(['id' => 1,'status' => 1, ]);Country::findAll([1, 2, 3]); // 返回id為1、2、3的一組數據 Country::findAll(['status' => 1,]);/**批量獲取**/// 一次提取 10 個客戶信息 foreach ($m->find()->batch(10) as $customers) {// $customers 是 10 個或更少的客戶對象的數組 } // 一次提取 10 個客戶并一個一個地遍歷處理 foreach ($m->find()->each(10) as $customer) {// $customer 是一個 ”Customer“ 對象 } // 貪婪加載模式的批處理查詢 foreach ($m->find()->with('orders')->each() as $customer) { }注意:
調用 save()、insert()、update() 這三個方法時,會自動調用yii\base\Model::validate()方法。如果驗證失敗,數據將不會保存進數據庫。
更多查看:http://www.yiichina.com/doc/guide/2.0/db-active-record
使用Query查詢
由于ActiveRecord是通過\yii\db\ActiveRecord::find()獲取的\yii\db\ActiveQuery實例,而\yii\db\ActiveQuery繼承自\yii\db\Query,那么其實可以直接使用\yii\db\Query里的方法進行查詢數據。
此時,除了ActiveRecord里的find()、insert()、update()、updateAll、delete()、deleteAll()、findBySql()、asArray()等不能使用外,其它的都是可以用的,例如where()、all、one、limit等等。
可以這么說,對于ActiveRecord里示例里的查詢方法,只要把find()替換成from($table)就可以用了。Query默認返回的數組,不是對象。下面是例子:
$m = new \yii\db\Query(); $table = 'country';$m->from($table)->all();//返回數組 $m->from($table)->one();//返回數組,僅返回一條記錄$m->from($table)->select('name')->column(); //返回指定字段的數組集合 $m->from($table)->column();//返回第一個字段的數組集合$m->from($table)->where(['name'=> 'China'] )->one(); $m->from($table)->where(['name'=> 'China'] )->all(); $m->from($table)->where(['name' => 'China', 'code' => 'CN'] )->all(); $m->from($table)->where(['name'=> 'China'] )->offset(1)->limit(1)->all(); $m->from($table)->orderBy('id DESC')->all(); $m->from($table)->where(['name'=> 'China'] )->orderBy('code desc')->limit(2)->all();//andWhere與where是一樣的,多個建議使用andWhere、orWhere $m->from($table)->where(['id' => 1])->count(); $m->from($table)->where(['id' => 1])->andWhere(['code' => 'CN'])->count(); $m->from($table)->where(['id' => 1])->orWhere(['code' => 'CN'])->count();http://www.yiichina.com/doc/guide/2.0/db-query-builder
事務
在Yii中,使用 yii\db\Transaction 來表示數據庫事務。
一般情況下,我們從數據庫連接啟用事務,通常采用如下的形式:
$connection = \Yii::$app->db; $transaction = $connection->beginTransaction(); try {$connection->createCommand($sql1)->execute();$connection->createCommand($sql2)->execute();// ... 執行其他 SQL 語句 ...$transaction->commit(); } catch(Exception $e) {$transaction->rollBack(); }示例:
$dbTrans= Yii::app()->db->beginTransaction(); try{ $customer = new Customer();$customer->name = 'Qiang';if(!$customer->save()) throw newException("Error Processing Request", 1); $dbTrans->commit(); // $this->_end(0,'添加成功!!!'); }catch(Exception$e){ $dbTrans->rollback(); // $this->_end($e->getCode(),$e->getMessage());總結
以上是生活随笔為你收集整理的Yii 框架学习--01 框架入门的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 细说C#多线程那些事 - 线程同步和多线
- 下一篇: 软件体系结构C2风格