Professional Documents
Culture Documents
Version 1.0
(Team JustLook)
JustLook
Yii Framework
Trang 1/34
Introduction
Yii l PHP framework h tr tt cho vic pht trin Web 2.0
Yii gip nh pht trin xy dng nhng ng dng phc tp vi thi gian nhanh
nht
Yii c pht m l Yee hoc [ji:], Yii l vit tt ca Yes It Is!. ngha ca n l Is
it fast? ... Is it secure? ... Is it professional? ... Is it right for my next project? ... Yes, it
is!
Yii hon ton min ph, l ng dng Web m ngun m c pht trin bng ngn ng
PHP5. Yii gip cho vic pht trin ng dng Web tun theo mt khun kh nhm m
bo tnh hiu qu, tnh m rng, v tnh bo tr ca sn phm.
Ti u hiu sut, Yii l s la chn hon ho cho cc d n c quy m. Yii cho php
nh pht trin kim sot ton b cu hnh. Yii cung cp cc cng c gip kim tra v
sa li ng dng d dng.
Lch s
Yii c sng lp bi Qiang Xue, ngi trc y pht trin v bo tr Prado
framework. D n Yii c bt u t ngy 01/01/2008 v sau gn mt nm pht trin,
ngy 03/12/2008 Yii 1.0 c chnh thc pht hnh.
tng
Yii kt hp nhiu tng t cc framework v cc ng dng Web ni ting khc. Di
y l mt s tng Yii tham kho:
Prado: l ngun gc ch yu cho tng pht trin Yii, bao gm: component v
m hnh lp trnh hng s kin, cc lp database, m hnh kin trc ng dng,
i18n v l10n, v nhiu tnh nng khc
Ruby on Rails: Yii k tha quy c v cu hnh
jQuery: c tch hp trong Yii framework
Symfony: Yii k tha tng v filter v kin trc plug-in
Joomla: Yii k tha cch thit k module v message translation
JustLook
Yii Framework
Trang 2/34
Contents
Introduction ....................................................................................................................... 1
Overview MVC ................................................................................................................. 4
MVC....................................................................................................................................................... 4
Model ................................................................................................................................................. 4
View ................................................................................................................................................... 5
Controller ........................................................................................................................................... 5
JustLook
Yii Framework
Trang 3/34
Extensions Library........................................................................................................... 31
Classified extension ............................................................................................................................. 31
Using extension .................................................................................................................................... 31
Creating extension ................................................................................................................................ 32
JustLook
Yii Framework
Trang 4/34
Overview MVC
Controller
Model
View
MVC
MVC l mt m hnh kin trc phn mm c s dng ph bin trong pht trin ng
dng Web. Mc ch chnh ca MVC l:
Tch ring cc thnh phn logic vi giao din ngi dng
Gip cho vic thay i cc thnh phn d dng m khng lm nh hng n cc
thnh phn khc
D dng pht trin v bo tr ng dng
Model
L th hin ca mt cu trc d liu c bn. Model c s dng lu tr d liu v
cc quy tc business lin quan.
Model i din cho mt i tng d liu duy nht. N c th l mt row trong
database table hoc l mt form input ca ngi dng. Mi trng (field) ca object l
mt thuc tnh (attribute) ca model.
JustLook
Yii Framework
Trang 5/34
View
View ch yu l cc yu t giao din ngi dng. Chu trch nhim trnh by cc th
hin ca model dng m ngi dng mong mun. N c th cha cc cu lnh (PHP,
ASP, ) nhng ch vi mc ch trnh by.
Controller
Cng vic ch yu ca controller l iu kin, x l cc request ca ngi dng. Lin
kt model vi view. Kim sot cc response.
JustLook
Yii Framework
Trang 6/34
Model
Nn
o Cha cc thuc tnh i din cho cc d liu c th
o Cha cc business logic nhm m bo cc d liu p ng c yu cu
thit k
o C th cha cc m thao tc vi database
Trnh
o S dng $_GET, $_POST hoc cc bin trc tip gn lin vi request ca
ngi dng
o Nhng cc m HTML hoc cc m trnh din khc (echo, )
View
Nn
o Cha cc m trnh din, nh HTML, PHP, ASP, n gin th hin,
nh dng d liu
o C th truy cp cc thuc tnh (property) v phng thc (method) ca
controller v model nhng ch vi mc ch trnh by
Trnh
o Cha cc m truy vn d liu
JustLook
Yii Framework
Trang 7/34
Controller
Nn
o C th truy cp $_GET, $_POST v cc bin tng t khc i din cho
request ca ngi dng
o C th to ra cc thc th (instance) ca model
Trnh
o Cha cc cu lnh truy vn SQL
o Cha bt k m HTML hoc cc ngn ng trnh din khc
JustLook
Yii Framework
Trang 8/34
CakePHP vs Yii
Model
View
Widget
Controller
Index.php
CakePHP Framework
Applicatio
n
App
component
Yii Framework
Ghi ch: ti liu ny ch yu s gii thiu v Yii, hin ti cty Green Global rt mnh
trong mng CakePHP framework. V vy trong qu trnh gii thiu Yii, team JustLook
s a s khc nhau gia CakePHP v Yii. mi ngi c th so snh, bit c s
khc bit gia CakePHP v Yii.
JustLook
Yii Framework
Trang 9/34
Model
View
8
9
Widget
Controller
1
Index.php
Application
App
2 component
JustLook
Yii Framework
Trang 10/34
i khi chng ta cn thay i workflow ty bin trang web. Yii cho php chng ta
lm c iu ny qua workflow sau:
Model
View
Widget
Controller
Index.php
Application
App
components
JustLook
Yii Framework
Trang 11/34
Yii Components
Cc thnh phn chnh ca Yii bao gm:
1.
2.
3.
4.
5.
6.
Application
Controller
Component
Model
View
Widget
1. Application
Nhim v chnh ca Application l gii quyt cc request ca ngi dng. Gi chng
cho controller thch hp tip tc x l. Application l trung tm qun l ton b cu
hnh ca ng dng.
Cc cng vic ch yu ca Application l:
Chun b khi to Application (Pre-initializes the application)
Thit lp autoloader v iu khin error (Set up class autoloader and error
handling)
ng k cc App Component ct li (Register core application components)
Np cu hnh ng dng (Load application configuration)
Khi to Application (Initialize the application)
Raise onBeginRequest event
X l request ca ngi dng (Process the user request)
Gii quyt request ca ngi dng (Resolve the user request)
To v thc thi Controller (Create & Run controller)
Raise onEndRequest event
cu hnh Application ta s dng file (hoc array) khi to gi tr ca cc thuc
tnh. File cu hnh c cha trong th mc protected/config/main.php ca ng dng.
Cu trc nh sau:
JustLook
Yii Framework
Trang 12/34
'name'=>'Yii Framework',
'defaultController'=>'site',
'components'=>array(
'db'=>array('connectionString'=>
'mysql:host=localhost;dbname=database'),
),
)
2. Controller
Nhim v ch yu ca controller l thc thi action. Controller ca Yii gm c 2 thnh
phn c bn l Filter v Action.
Action
Action l cc phng thc c tn bt u l action (v d: actionIndex). V c bn, cch
s dng action ca Yii tng t nh CakePHP.
JustLook
Yii Framework
Trang 13/34
CakePHP Framework
Yii Framework
Ngoi ra, Yii cn h tr cch vit cc action nng cao hn bng cch t chc cc action
theo kiu m-un ha. Ta c th xem cu trc th mc sau:
);
}
// ...
}
protected/controllers/SiteController.php
protected/controllers/site/ContactAction.php
JustLook
Yii Framework
Trang 14/34
JustLook
Yii Framework
Trang 15/34
Filter
L phng thc c x l trc (hoc sau) khi thc thi action. Trong Yii, mt action
c th c nhiu filter. Filter c th ngn chn vic thc thi cc action.
khai bo filter ta s dng phng thc filters(). Xem v d:
}
Ti v d trn, ta to mt filter AccessControl cho ton b cc action thuc controller
Post. Phng thc filterAccessControl s c thc thi trc cc action ca controller
Post.
Ngoi ra, ta c th ty bin s dng filter bng cch s dng ton t cng (+) v tr (-).
Ton t (+) cho php filter c p dng i vi controller km theo. Ton t (-) cho
php filter c p dng cho tt c cc action ngoi tr action km theo. Xem v d:
JustLook
Yii Framework
Trang 16/34
}
V d trn cho thy, filter CheckAdmin s c p dng cho 2 action update v delete.
Filter CheckLogin s c p dng cho tt c cc action ca controller Post ngoi tr
action view.
Ngoi ra, Yii cn h tr cch vit cc filter nng cao hn bng cch t chc cc filter
theo kiu m-un ha. (tng t phn action). Xem v d:
JustLook
Yii Framework
Trang 17/34
// file: protected/filters/PerformanceFilter.php
// file: protected/controllers/PostContrller.php
protected/controllers/PostContrller.php
protected/filters/PerformanceFilter.php
3. Component
ng dng Yii c xy dng da trn cc Component. S dng cc Component ch
yu lin quan n vic truy cp cc thuc tnh ca n v nng cao x l s kin.
Component l i tng qun l Event v Behavior.
Event
Yii h tr k thut lp trnh hng s kin. Cc phng thc c gn trong mt s
kin s c t ng thc thi mi khi s kin c gi (raise)
4. Model
Nhim v chnh ca model l lu d liu v cc quy tc business lin quan.
JustLook
Yii Framework
Trang 18/34
Model i din cho mt i tng d liu duy nht. N c th l mt hng (row) trong
bng (table) c s d liu hoc l mt input form ca ngi dng.
Mi trng (field) ca i tng c biu din thnh mt thuc tnh (property) trong
model. Thuc tnh ny c mt nhn (label) v c th c xc lp mt quy tc xc thc
(validate).
Yii h tr 2 loi model
FormModel: s dng cho vic x l cc form input ca ngi dng. Cc d liu
ny thng c x l v sau b i. V d: trn mt trang ng nhp, ta ch
s dng model cho vic kim tra user.
ActiveRecord: s dng cho vic truy cp c s d liu tru tng.
Working with model
lm vic vi model, ta cn ch n cc vn sau:
a) Cc quy tc xc thc (Validation Rules)
b) Relational Active Record
c) Mt vi phng thc lin quan n truy vn CSDL
a) Validation Rules (Cc quy tc xc thc)
khai bo quy tc xc thc, trong model ta s dng phng thc rules() tr v mt
array chc cc quy tc. Xem v d:
JustLook
Yii Framework
Trang 19/34
Vi v d trn, ta khai bo quy tc required cho 2 thuc tnh username, password (quy
tc ny yu cu ngi dng phi nhp liu cho 2 thuc tnh, khng c php trng).
Ngoi ra, thuc tnh password cn c khai bo quy tc authenticate (quy tc ny s
thc thi phng thc authenticate kim tra password c ng khng).
C 3 loi quy tc xc thc (Validator) sau:
1. Validator c th l tn ca mt phng thc trong model (nh v d trn, s dng
phng thc authenticate)
2. Validator c th l tn ca mt lp (class) validator
3. Validator c th l mt b danh c xc nh trc ca Yii (nh v d trn, s
dng b danh required)
b) Relational Active Record
Phn ny s c gii thiu chi tit hn trong phn Active Record (Working with
Database)
c) Mt vi phng thc lin quan n truy vn CSDL
Protected Methods
o beforeSave() / afterSave()
o beforeDelete() / afterDelete()
o beforeValidate() / afterValidate()
o beforeFind() / afterFind()
Events
o onBeforeSave / onAfterSave
o onBeforeDelete / onAfterDelete
o onBeforeValidate / onAfterValidate
o onBeforeFind / onAfterFind
5. View
View l mt PHP script bao gm ch yu l cc yu t giao din ngi dng. N c th
cha cc cu lnh PHP n gin nhng ch vi mc ch trnh by.
Lm vic vi view cn ch n cc phng thc sau:
Public methods
o render(): Renders a view with a layout
JustLook
Yii Framework
Trang 20/34
6. Widget
Widget l thnh phn ch yu cho mc ch trnh by. N to ra cc giao din ngi
dng phc tp nhng khp kn.
JustLook
Yii Framework
Trang 21/34
SQLite: sqlite:/path/to/dbfile
MySQL: mysql:host=localhost;dbname=testdb
PostgreSQL: pgsql:host=localhost;port=5432;dbname=testdb
SQL Server: mssql:host=localhost;dbname=testdb
Oracle: oci:dbname=//localhost:1521/testdb
JustLook
Yii Framework
Trang 22/34
//
//
//
//
//
//
Mt cu lnh SQL c thc thi thng qua CDbCommand bng mt trong 2 cch sau:
execute(): thc hin non-query SQL, nh INSERT, UPDATE v DELETE
query(): thc hin cu truy vn tr v tp hp cc hng (row) d liu, nh
SELECT
Fetching Query Results (Ly kt qu truy vn)
ly kt qu truy vn ta s dng CdbDataReader->read()
JustLook
Yii Framework
Trang 23/34
$dataReader=$command->query();
// calling read() repeatedly until it returns false
while(($row=$dataReader->read())!==false) { ... }
// using foreach to traverse through every row of data
foreach($dataReader as $row) { ... }
// retrieving all rows at once in a single array
$rows=$dataReader->readAll();
Binding Parameters
trnh cc tn cng SQL Injection v ci thin hiu sut cc cu lnh truy vn SQL ta
s dng cc tham s rng buc (binding parameters). Xem v d sau:
// an SQL with two placeholders ":username" and ":email"
$sql="INSERT INTO tbl_user (username, email) VALUES(:username,:email)";
$command=$connection->createCommand($sql);
// replace the placeholder ":username" with the actual username value
$command->bindParam(":username",$username,PDO::PARAM_STR);
// replace the placeholder ":email" with the actual email value
$command->bindParam(":email",$email,PDO::PARAM_STR);
$command->execute();
// insert another row with a new set of parameters
$command->bindParam(":username",$username2,PDO::PARAM_STR);
$command->bindParam(":email",$email2,PDO::PARAM_STR);
$command->execute()
JustLook
Yii Framework
Trang 24/34
bit chi tit cc tham s rng buc, vui lng xem thm link
http://www.php.net/manual/en/pdostatement.bindparam.php
2. Query Builder
Yii Query Builder cung cp vic vit cc cu lnh SQL theo hng i tng. N cho
php s dng cc phng thc v thuc tnh chia nh cu lnh SQL thnh cc phn
n gin hn. Cc phn sau c Yii kt hp li v thc thi thng qua DAO.
Di y l mt cch s dng in hnh ca Query Builder xy dng cu lnh SQL
SELECT
$user = Yii::app()->db->createCommand()
->select('id, username, profile')
->from('tbl_user u')
->join('tbl_profile p', 'u.id=p.user_id')
->where('id=:id', array(':id'=>$id))
->queryRow();
JustLook
Yii Framework
Trang 25/34
$users = Yii::app()->db->createCommand()
->select('*')
->from('tbl_user')
->queryAll();
$user = Yii::app()->db->createCommand()
->select('id, username, profile')
->from('tbl_user u')
->join('tbl_profile p', 'u.id=p.user_id')
->where('id=:id', array(':id'=>$id))
->queryRow();
JustLook
Yii Framework
Trang 26/34
'name'=>'Tester',
), 'id=:id', array(':id'=>1));
3. Active Record
Mc d Yii DAO c th x l tt c cc nhim v lin quan n CSDL. Nhng vic s
dng DAO dn n mt s bt li cho vic lp trnh:
Mt kh nhiu thi gian xy dng cc cu lnh truy vn thc hin cc cng
vic CRUD (to, c, cp nht, xa) ni chung
Kh bo tr ng dng v cc cu lnh truy vn SQL trn ln chung vi cu lnh
khc
gii quyt cc vn trn, chng ta c th s dng Active Record.
Mi Active Record (AR) i din cho mt bng (table) CSDL. Cc trng (field) ca
bng tng ng vi cc thuc tnh ca AR. Mi thc th (instance) ca AR i din
cho mt hng (row) trong bng.
JustLook
Yii Framework
Trang 27/34
Establishing DB Connection
thit lp kt ni
protected/config/main.php
CSDL,
ta
thit
lp
cu
hnh
trong
file
return array(
'components'=>array(
'db'=>array(
'class'=>'system.db.CDbConnection',
'connectionString'=>'sqlite:path/to/dbfile',
// turn on schema caching to improve performance
// 'schemaCachingDuration'=>3600,
),
),
);
Defining AR Class
Mt lp (class) AR c cu trc nh sau:
class Post extends CActiveRecord
{
public static function model($className=__CLASS__)
{
return parent::model($className);
}
public function tableName()
{
return 'tbl_post';
}
}
JustLook
Yii Framework
Trang 28/34
Creating Record
chn mt hng mi vo bng CSDL, ta to ra mt thc th AR, thit lp gi tr cc
thuc tnh (tng ng vi gi tr cc trng ca bng) cho n. Sau gi phng
thc save() chn. Xem v d:
$post=new Post;
$post->title='sample post';
$post->content='content for the sample post';
$post->create_time=time();
$post->save();
Reading Record
c d liu trong mt bng CSDL, ta s dng phng thc find():
// find the first row satisfying the specified condition
$post=Post::model()->find($condition,$params);
// find the row with the specified primary key
$post=Post::model()->findByPk($postID,$condition,$params);
// find the row with the specified attribute values
$post=Post::model()->findByAttributes($attributes,$condition,$params);
// find the first row using the specified SQL statement
$post=Post::model()->findBySql($sql,$params);
JustLook
Yii Framework
$transaction->rollBack();
}
Xem v d, vi s ER sau:
Ta khai bo cc lp AR nh sau:
class Post extends CActiveRecord
{
......
public function relations()
{
return array(
'author'=>array(self::BELONGS_TO, 'User', 'author_id'),
'categories'=>array(self::MANY_MANY, 'Category',
'tbl_post_category(post_id, category_id)'),
);
Trang 29/34
JustLook
Yii Framework
Trang 30/34
}
}
class User extends CActiveRecord
{
......
public function relations()
{
return array(
'posts'=>array(self::HAS_MANY, 'Post', 'author_id'),
'profile'=>array(self::HAS_ONE, 'Profile', 'owner_id'),
);
}
}
bit chi tit hn v Relational AR, vui lng truy cp trang ch Yii
http://www.yiiframework.com/doc/guide/1.1/en/database.arr
JustLook
Yii Framework
Trang 31/34
Extensions Library
Classified extension
application component
behavior
widget
controller
action
filter
validator
helper
module
Using extension
Cc extension (phn m rng) s c t trong th mc protected/extensions ca ng
dng.
Vi extension tn l xyz, chng ta c th s dng b danh theo ng dn ext.xyz
truy cp n extension . Xem v d:
);
}
// ...
}
protected/controllers/SiteController.php
protected/extensions/action/ContactAction.php
JustLook
Yii Framework
Trang 32/34
Creating extension
to extension, trc ht ta cn ch n cc vn sau:
Mt extension l mt thnh phn c lp
Cc tp tin extension cn c t chc trong cng mt th mc
Tn cc lp (class) thuc trong mt extension nn c bt u bng mt tin t
(Yii kin ngh s dng tin t s) ( phn bit vi cc class khc ca ng
dng).
Mt extension nn c i km cc ti liu API v hng dn ci t
Mt extension nn c s dng mt giy php (license) thch hp nu mun
chia s n cho cng ng
Ty vo mi loi extension ta c th to ra cc extension ph hp. V d: extension
action c cu trc class khc vi extension validator. Ta xem v d sau:
class MyValidator extends CValidator
{
protected function validateAttribute($model,$attribute)
{
$value=$model->$attribute;
if($value has error)
$model->addError($attribute,$errorMessage);
}
}
JustLook
Yii Framework
Trang 33/34