Web Application Development With Yii and PHP Nov2012 Tiếng Việt

  • Upload
    rep117

  • View
    781

  • Download
    3

Embed Size (px)

DESCRIPTION

Lập trình Web PHP bằng Yii Framework tiếng Việt

Citation preview

Web.Application.Development.with.Yii.and.PHP 2ND Edition

January 1, 2013[Web.Application.Development.with.Yii.and.PHP 2ND Edition]

Web.Application.Development.with.Yii.and.PHP 2ND EditionPublic: Packpub Year: 2013

Translate: Longt8x

Support: [email protected]: [email protected] ni u :

u tin xin chc cc bn mt nm mi ngp trn nim vui, cuc sng hnh phc bn gia nh v ngi thn.i vi nhng ngi mi bt u ti ngh cc bn hc quyn Yii cookbook development xem r hn cu trc h thng ca Yii v khm ph phn khung xng ca n trc khi thc hin hc ebook ny.

Vi nt v Yii framework

Yii framework do mt tn tu kha xy dng ln da vo vic ly nhng ci hay ca rt nhiu framework tng hp li thnh mt framework ring, n ch yu da trn l thuyt Agile v Prado, Zend framework v mt s th vin hu ch m thnh, tn ca anh ta l Quiang Xue.

Mc : N rt thch hp cho cc d n tm trung v cc d n nh gip xy dng nhanh qun tr v thao tc vi ngi dng, c th xy dng lm vic theo nhm , tuy nhin nu bn xy dng d n ln th ng ln s dng framework ny v n khng thch hp cho lm.

Phn 1 : Ci t cu hnh yii frameworkBn vo trang ch : http://www.yiiframework.com/download/Download phin bn mi nht v sau gii nn (extract here), sau rename li l cookbook, copy folder cookbook mi gii nn vo C:\xampp\htdocs\, bn phi down xampp v ri ci t setup thnh cng th chy xampp center thit lp apache v mysql running.

http://localhost/appyii/requirements/index.phpPhn mm chy local: Xampp, Wamp, ko nn dng appserv v b li( nguyn nhn mnh ko bit, tt nht nn trnh).

Hoc xi lun host tht nu nh c iu kin.

1. Chun bTrc tin bn phi cu hnh windows s dng c php vi cmd

-Gi s bn ci apache mc nh trn WinXP (C:\xampp\htdocs).

-Bn thit lp li bin mi trng (Environment Variables) bng cch vo: Start -> My Computer (right click!) -> Advanced Tab -> Environment Variables -> Click Path in System variables (windows 7 l Path) -> Edit.

-Click vo bin PATH v chn Edit. Lu l ng c xo b cc ng dn tn ti trong textbox m ngn cch chng vi nhau bng du ";".

-Tip bn thm vo nhng ng dn sau: "C:\xampp\php" v " C:\xampp\htdocs\appyii\framework". Lu sa ng dn cho ph hp vi my bn nha .-Khi ng my tnh li.

2.To ng dng Yii mi-YiiRoot l th mc ni bn ci t Yii-Webroot l th mc gc cha web-T dng lnh, n webroot ca bn v thc hin: Vo start -> run->cmd

C:\

Cd\

Cd C:\xampp\htdocs\

C:\xampp\htdocs\>appyii/framework/yiic webapp devyii

Nu khng c th g tip cd appyii

G tip cd framework -> g yiic webapp devyii.[devyii]-> Tn ng dng Create a Web application under '/Webroot/devyii? [Yes|No] Yes[y]

Vy l khung xng ca Yii c to ra thnh cng

Trch dn:devyii/

index.php file ng dng

index-test.php file kim tra chc nng

assets/ cha ti nguyn ng dng

css/ cha CSS

images/ cha hnh nh

themes/ cha giao din

protected/ cha cc file c bo v

Vo appyii/framework/ chuyn folder mi to l devyii ra ngoi folder website C:/xampp/htdocs. ng dn mi ca app l C:/xampp/htdocs/devyii.

copy folder framework ca appyii sang devyii.

Vo file index.php thay i ng dn thnh : $yii=dirname(__FILE__).'/framework/yii.php';Bn c th truy cp vo ng dng t trnh duyt

http://localhost/devyii/index.php

Ok, hon tt cu hnh tin hnh coder.

III. To controller

-Vo th mc ng dng

M:

%cd /Webroot/devyiiC:/

Cd C:/xampp/htdocs/devyii

-Khi ng Yii Shell

M:

%YiiRoot/framework/yiic shellCd C:/xampp/htdocs/devyiiC:/xampp/htdocs/devyii> C:/xampp/htdocs/devyii/framework/yiic shell

To th controller tn message c hnh ng l helloWorldC php: controller [action-ID]VD:

M:

controller message helloWorld

-MessageController c to thnh cng th mc: protected/controllers/-Bn cnh n cng to ra view ti th mc: protected\views\message-Chng ta cng c th truy cp vo hnh ng helloWorld t trnh duyt

Default: http://localhost/devyii/index.php?r=message -> chy vo index

http://localhost/devyii/index.php?r=message/helloWorldVIII. To lin kt-Yii c h tr sn hm to lin kt trong class CHtml-VD: To lin kt ti View goodbye

M:

To lin kt ti View Hello

M:

IX.Ci t database1.Yii h tr cc dalabase sau:-MySQL 4.1 or later-PostgresSQL 7.3 or later-SQLite 2 and 3-Microsoft SQL Server 2000 or later-Oracle

2. Kt ni vi database-Thc hin file /protected/config/main.php-Mc nh n ang kch hot ng ny l database ca khung xng Yii

M:

'db'=>array('connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',),

- Gi s ta c 1 bng trong Mysql nh sau:

M:

CREATE TABLE IF NOT EXISTS `tbl_user` (`id` int(11) NOT NULL AUTO_INCREMENT,`username` varchar(128) NOT NULL,`password` varchar(128) NOT NULL,`email` varchar(128) NOT NULL,PRIMARY KEY (`id`));

- Chng ta phi kch hot ng sau trong /protected/config/main.php kt ni vi Mysql (b /* */ v sa li cu hnh)

M:

// uncomment the following to use a MySQL database'db'=>array('connectionString' => 'mysql:host=localhost;dbname=devyii','emulatePrepare' => true,'username' => 'root','password' => '','charset' => 'utf8',),

-Ngoi ra ta c th kt ni vi ci database khc (thay i dng 'connectionString') 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

XI. To CRUD- CRUD l cc chc nng create, read, update v delete 1 bng trong database

1. Kch hot cng c Gii- Gii h tr sinh m t ng cc chc nng nh Controller, Crud, Form, Model, Module.- kch hot Gii ta vo file config /protected/config/main.php- Kch hot on code sau

M:

// uncomment the following to enable the Gii tool'gii'=>array('class'=>'system.gii.GiiModule','password'=>'1111', // If removed, Gii defaults to localhost only. Edit carefully to taste.'ipFilters'=>array('127.0.0.1','::1'),),

- i password mi ng nhp Gii- Vo Gii thng qua url: http:// localhost/devyii/index.php?r=gii2. To user Model-Vo mc Model Generator to Model cho bng user- Table Prefix: vit phn tin t ca bng (nu c) vo y, y bng ca ta tn l tbl_user nn tin t s l tbl_- Table Name: phn cn li ca tn bng l user (ta c th to t ng tt c bng bng cch nhp du * vo y)- Model Class: tn lp ca model l User (t sinh ra)- Cn li mc nh v click Preview- Sau click Generate to file Model ca User ti th mc /protected/models/User.php

3. To CRUD:- Vo mc Crud Generator- Model Class: in chnh xc tn lp Model va to l User- Controller ID: in user (khng vit hoa)- Cn li mc nh v click Preview- Sau click Generate to Crud

4. Truy cp CRUD- Vo url: http://localhost/devyii/index.php?r=user- Click vo cc chc nng nh Create User, Manage User, n s bt ta ng nhp, ta c th s dng user v pass sau: demo/demo (ti khon bnh thng) hay admin/admin (ti khon admin)- Vi ti khon admin ta c th truy cp vo trang qun l sauhttp://localhost/devyii/index.php?r=user/admin5. URL Thn thin

Vo protected/config/main.php b comment urlManager..

$yii=dirname(__FILE__).'/framework/yii.php';XII CC TRNG D LIU TRONG FORM

$this->pageTitle=Thay i tiu trang ti y;Cch 1: Dng form bng cch dng widget.//Khi to widget s dng Ajax cho Form Active

$form=$this->beginWidget('CActiveForm',array(

'id'=>'user-form',

'enableAjaxValidation'=>true,

'enableClientValidation'=>true,

'focus'=>array($model,'name')

));

Thm Captcha cho form

-Nu cha bt "gd2" th ta vo file php.ini ri sa li dng ny

M PHP:

extension=php_gd2.dll

RE: [C Bn] To form trong view Xem thm cc Method add cc Field khc cho form HereNgoi cch dng 'CActiveForm' ta c th dng 'Chtml' d to form: CHtml

Vit Li form trn bng cch dng 'CHtml':

M PHP:







Sau khi to form xong th ti bc tip theo l add cc rng buc cho thng tin m user nhp vo v d nh:

Cc text box khng c b trng

Email phi ng dng

Pass phi ln hn 6 nh hn 15

Repass phi y chang Pass

Date: phi hp l theo kiu (dd-mm-yyyy) hay (mm-dd-yyyy)

Add thm captcha chng ng k hng lot

Thm Captcha cho form

-Yii c h tr sn th vin captcha cho chng ta, v captcha th nhn cng rt l cool.

Test xem c th render captcha hay khng-u tin truy cp th link ny test xem c captcha hay khng ci .http://localhost/devyii/index.php?r=site/captcha nu ra nh vy l ok

-Nu n khng hin captcha th ta nn check li xem load "gd2" hay cha bng cch chy mc test ca Yii

ging nh hnh l load ri, n vng hay th xem li cu hnh webserver

-Nu cha bt "gd2" th ta vo file php.ini ri sa li dng ny

M PHP:

extension=php_gd2.dllbdu";"trcn,mycikhcdefautngtymy,restarwebservervtestli,nuvnli-->thiciliwinchonlnh

- to captcha ta thm vo phn view on code sau:

M PHP:

Vi:

'buttonLabel' : hin th mt link vi ni dung m ta set, khi click vo s i string ca captcha

'clickableImage': khi click vo image s i sang hnh khc.

'imageOptions': set cc thuc tnh Html ca captcha

- Mt captcha c rendered bi mt hnh ng ca lp CCaptchaAction, do nu ch add bn view s khng hin th hnh nh, v captcha khng c render. Do ta vit thm bn Controller:

M PHP:

publicfunctionactions(){returnarray('captcha'=>array('class'=>'CCaptchaAction','backColor'=>'#fff

'),);}Vi

'backColor': mu nn nh #fff l mu en,

'foreColor': mu ch captcha.

'height': chiu cao nh

'width': Chiu rng

'maxLength': chiu di ti da ca ch captcha

'minLength': di ti thiu ca string.

'verifyCode': ly gi tr m xc nhn

Cui cng ra ci form nh vy:

- rng buc cc thng tin m e nhp vo ta vit mt phng thc trong Model nh sau:

M PHP:

publicfunctionrules(){returnarray(array('code','captcha','allowEmpty'=>!CCaptcha::checkRequirements(),'message'=>'MXcNhnNhpKhngng'),array('email','email','message'=>'{attribute}khnghpl'),array('name,email,pass,repass,date,code','required','message'=>"{attribute}khngcbtrng"),array('repass','compare','compareAttribute'=>'pass','message'=>"{attribute}phichnhxc"),array('pass','length','min'=>'6','message'=>"{attribute}khngdi"),array('date','date','format'=>'dd-mm-yyyy','message'=>"{attribute}phichnhxcdng{dd-mm-yyyy}"),);}Chng 1 Bt u vi Yii Framework1. Cun sch ny dnh cho ai ?

Nu bn l mt lp trnh vin php vi cc k nng hiu bit v OOP (Lp trnh hng i tng) v mun xy dng h thng hin i vi cc ng dng web th cun sch ny dnh cho bn,khng c bt k mt yu cu g c cun sch Yii ny.2. To controller helloworld

to nn mt controller trong yii bn c 3 cch, cch mt l nu bn lm vic quen vi yii bn c th to t mt file mi v khai bo n vi tn class c k tha t Ccomponent, cch hai l to t dng lnh trong cmd cch ny bn c th tham kho t ebook yii cookbook hoc trn din n yiivn.com, cch 3 ny c phn d hn cho cc bn mi tm hiu yii l to controller t mt cng c trong yii c tn l Gii.

Cu hnh Gii

Trc khi s dng Gii chng ta cn phi config ng dng , chng ta phi truy cp vo cu hnh ng dng chnh ti file trong a ch : protected/config/main.php (Full cu hnh C:\xampp\htdocs\devyii\protected\config\main.php) cc bn lu ln sau ti ch g tt a ch bn phi t vo webroot (th mc web gc) tm.

Chng ta vo file v thy dng code sau y :return array(

'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..',

'name'=>'My Web Application',

//load thnh phn log'preload'=>array('log'),

// t ng load model v thnh phn class'import'=>array(

'application.models.*',

'application.components.*',

),

'modules'=>array(

// Khng comment sau khi kch hot cng c ny/*

'gii'=>array(

'class'=>'system.gii.GiiModule',

'password'=>'Enter Your Password Here',

//Nu xa i Gii s mc nh t localhost.Hy iu chnh cn thn.

'ipFilters'=>array('127.0.0.1','::1'),

),

*/

),Bn b hai dng check comment i v in mt khu ca bn, hoc bn c th lm theo ti vi mt khu l : 1111Khi on module c thay i nh sau:

'modules'=>array(

'gii'=>array(

'class'=>'system.gii.GiiModule',

'password'=>1111,

'ipFilters'=>array('127.0.0.1','::1'),

),

Chng ta vo trnh duyt kim tra th : http://localhost/devyii/index.php?r=giiSau nhn pass l 1111 bn s truy cp vo c Gii

Bn c th nhn thy 5 cng c chnh Controller Generator (To ra controller) Crud Generator (To ra CRUD (Cp nht-sa-xa)) Form Generator (To ra Form) Model Generator (To ra Model) Module Generator (To ra Module)D nhin to mt controller ta click vo link Controller Generator menu ti y c 2 trng l ControllerID v ActionID bn vit vo controller v action bn mun to ,vi ti th ti to controller message v action l helloworld hon tt chng ta nhn vo Preview sau Generate chng ta s to ra c.

kim tra cc bn vo protected/controller/ cc bn s thy file MessageController.php , kim tra trong protected/views bn s thy folder message v trong folder l action helloworld.phpKim tra trn trnh duyt bn g : http://localhost/devyii/index.php?r=message/helloworld bn thy kt qu sau:

Nh vy l bn c th to c 2 file controller v action helloworld bn c th vo file MessageController tin hnh code theo ca bn .Lc ban u bn s thy nhng dng code sau:class MessageController extends Controller

{

public function actionHelloworld()

{

$this->render('helloworld');

}

}

Nu bn g http://localhost/devyii/index.php?r=message my s tr v thng bo li 404Thng thng khi chy vo controller theo m hnh MVC h thng s tm theo action u tin l index, v th nn controller hin ti bn khi to cha c actionIndex() v khi bn cn thm action mc nh bng dng lnh:

V d thm thi gian ca h thng:

Refresh li trnh duyt bn s thy ngy gi ca h thng.Ngoi cch nhng m php hin th ngy gi ra ta cn c mt cch khc cc k quan trng l generate d liu t model ra view thng qua controller l phng thc hot ng theo m hnh MVC.Chng ta cng xem v d sau: bn vo protected/controller/MessageController.php v thy actionHelloworld():

public function actionHelloworld()

{

$this->render('helloworld');

}Chng ta khai bo mt bin mi v render n sang views bng cch sau:

public function actionHelloworld()

{

$theTime = date("D M j G:i:s T Y");

$this->render('helloworld',array('time'=>$theTime));

}

Tip bn vo protected/views/message/helloworld.php v hin th bin time nh sau :Bay gio la:Lu li file view v vo trnh duyt xem kt qu:

http://localhost/devyii/index.php?r=message

Nh vy l cc bn va lm quen vic thao tc d liu theo m hnh MVC , by gi ta lm th cch mt l t to action mi theo mnh ,gi s ti to action goodbye:

class MessageController extends Controller

{

public function actionGoodbye()

{

$this->render('goodbye');

}

...

}

Tip theo ta vo trong protected/views/message/ v to mi file goodbye.php mt cch n gin l bn copy file helloworld.php v paste ti sau rename thnh goodbye.php v thm vo file mi vi ni dung sau y:Goodbye! kim tra bn vo http://localhost/devyii/index.php?r=message/goodbye

Tin hnh mt s s tr gip ca Yii ChtmlTht may mn, Yii h tr cc phng thc c th s dng trong views template cc phng thc tnh tn ti t s tr gip ca framework vi class CHtml. Trong trng hp chng ta mun to cc link tnh vi controllerID /actionID thay v cc cu trc links c bn ca HTML. s dng link helper chng ta thm on m sau vo file helloworld.php trong folder protected/views/message/helloworld.php:

Vo trnh duyt xem kt qu : http://localhost/devyii/index.php?r=message s hin th tng t nh hnh bn trn.Tng t bn th sa trong file goodbye.php trong protected/views/message/goodbye.php:Goodbye, Yii developer!

Vo trnh duyt ta c kt qu : http://localhost/devyii/index.php?r=message/goodbye

Chng 2 - Gii thiu ng dng Developer Yii Xy dng mt d n mi trn Yii frameworkChng ta c th tip tc gi vic thm cc ng dng n gin nh hello,world t Yii, nhng iu s khng thc s gip bn hiu c v yii framework trong ng cnh ca ng dng ngoi i thc, lm c iu ny chng ta cn xy dng mt ng dng mi, l ni dung ca chng ny. Chng ta s gii thiu project-task-tracking application ( d n : task(nhim v)- tracking (cch thc) ca ng dng c gi l Developer Yii. C nhiu project qun l khc v issue-tracking-application ( cc vn - cch thc ca ng dng trong ngoi i thc. Bn s t ra cu hi : Ta sao phi xy dng n ?, bi v n tr v cc thuc tnh c bn ca ng dng v xa hn c tp lnh trong ng dng.

Gii thiu v Developer YiiDeveloper Yii bao gm 3 yu t chnh l d n (project) , ngi s dng (user), cc vn (issue).Trong user bao gm hai trng thi :

-Anonymous l mt khch ngoi ng nhp vo h thng khng cn phi thng qua vic xc thc quyn truy cp h ch c quyn ng k ti khon v kch hot ti khon, khng c quyn qun tr.

- Ngi dng c xc thc (authenticated) l bt k ngi dng no c xc thc cc tiu chun thng qua qu trnh ng nhp vo h thng,ngi s dng ny c cc quyn y v qun tr d n, thit lp d n, cp nht d n.

Cc d n (Projects)

Qun tr cc d n chnh thc hin trong ng dng TrackStar, mt d n c th hin di nhiu mc c thc hin bi mt hay nhiu ngi

Cc vn (issue):

Cc vn trong d n gm 3 loi sau:

Xa hn: Cc item c trnh din xa hn trong th gii thc khi c thm vo ng dng v d : thc thi hm login xc thc user.

Cc chc nng: Item c hin th cn phi hon thnh cc cng vic khng gp li v s c.Cc li: Item khng hot ng hon ho do li pht sinh trong h thng hoc tc ng bn ngoi.

C 3 trng thi chnh trong cc vn l :

Cha bt u,

Bt u,

Kt thc.

Thnh vin ca d n c th thm nhiu vn ti d n cng nh vic iu chnh v xa item.Chng c th c ng k t bn thn ngi vit hoc thnh vin ca d n.By gi chng ta s xem khung lm vic ca ng dng mi:

T biu ny ta c th nhn s qua chi tit ca d nKhi mt ngi dng bt u truy cp ng dng, h phi ng nhp v xc thc quyn truy cp ti ng dng, nu ng nhp thnh cng h s c xem cc d n hin ti ca h hoc h c th thm mi.

Khi la chn mt d n no s kch hot vo chi tit ca trang ,chi tit ca d n s hin th thng tin danh sch cc vn trong d n,ngoi ra h cng c th thm mi, chnh sa, xa i.

l tt c nhng g trong ng dng bn cn phi quan tm.

Quan h d liu

Chng ta cng phi quan tm v m hnh d liu s lm vic ,chng ta s s dng active-record c k tha t Yii n s lu d d liu m chng ta mun chuyn ti Model. Chng ta c th nhn s qua v biu ca d n :

Chng ta c th nhn s qua vo bng biu v thy c cc thuc tnh sau:

Mt ngi dng s c nhiu vn khc nhau v th bng biu s c lin kt 0 hoc nhiu.

Mt ngi dng cng s c nhiu d n nhng mi mt d n c to ra bi t nht mt ngi bi th nn c quan h 1..* lin quan ti 0 nhiu.

Mi mt d n s c nhiu vn khc nhau, nhng mt vn khc nhau ch thuc trong mt d n m thi v vy nn c quan h 0 ..* vn cha ng trong 1 d n

1 Kt ni ti c s d liu (database)

Yii h tr hu ht cc csdl dng DBMS , PDO bao gm:

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

Ti y ti s s dng mysql lm c s d liu.Bn vo protected/config/main.php v tm dng sau:

'db'=>array(

'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',

),

// uncomment the following to use a MySQL database

/*

'db'=>array(

'connectionString' => 'mysql:host=localhost;dbname=testdrive',

'emulatePrepare' => true,

'username' => 'root',

'password' => '',

'charset' => 'utf8',

),

*/

Bn c th nhn thy hin ti mc nh yii s dng sqlite , tuy nhin ti li mun s dng mysql nn bn sa li thng s v b dng check comment ca mysql, thay vo bn thm dng check comment vo sqlite v bn c kt qu sau:

/*

'db'=>array(

'connectionString' => 'sqlite:'.dirname(__FILE__).'/../data/testdrive.db',

),

*/

// uncomment the following to use a MySQL database

'db'=>array(

'connectionString' => 'mysql:host=localhost;dbname=devyii',

'emulatePrepare' => true,

'username' => 'root',

'password' => '',

'charset' => 'utf8',

)Ti y ti khai bo cc thng s ca mysql gm username, password, database c tn l devyii, cng vic tip theo ca bn l vo phpmyadmin v to database c tn devyii:

Nhn create v database ca bn c to ra.

3. Xy dng CRUD cho project

K hoch nh sau:

kt thc chng ny, d n ca bn cn phi cho php user to mi project, la chn item trong danh sch project, cp nht v sa xa cc project .Cng vic ca chng ta by gi l :

Thit k c s d liu h tr cho project

Xy dng cc bng biu cn thit v cc i tng d liu khc c nh ngha trong bng

To Yii AR (Active-Record) (Kch hot Bn ghi) model class cho php ngi dng d dng thao tc vi bng csdl

To Yii controller class s l ngi nh cha cc hm sau:

1. To mi project

2. Lit k ra danh sch d n

3. Cp nht d liu lin quan vi project

4. Xa cc d liu trong project

To file Views trong yii v hin th cu trc c bn sau:

1. Hin th form cho php ngi dng to mi project

2. Hin th danh sch tt c project

3. Hin th form cho php user cp nht thng tin trong project

4. Thm mt nt xa user c th xa project

Vy l OK, chng ta bt u tin hnh xy dng theo cu trc trn

3.1 To bng cho project

Chng ta hy quay tr li ci biu m hnh user-project-issue cha cc kt ni v chng ta thit k bng theo m hnh , bng project bao gm nhng trng sau: id (integer) index ,name (varchar 255) tn project, description text not null m t project, create_time datetime- ngy to,create_user_id integer ngi dng to ra project ,update_time datetime- ngy cp nht li project,update_time_user_id integer m user cp nht d n , v tt nhin id s l kha chnh, bn c th t to bng bng query sql hoc n gin hn l chp on di y ri dn vo tab query Sql trong phpmyadminCREATE TABLE tbl_project (

`id` INT(11) NOT NULL auto_increment,

`name` varchar(255) NOT NULL,

`description` text NOT NULL,

`create_time` DATETIME default NULL,

`create_user_id` INTEGER default NULL,

`update_time` DATETIME default NULL,

`update_user_id` INTEGER default NULL,

PRIMARY KEY (`id`)

) ENGINE = InnoDB;

3.2 To AR (Active-Record) model classSau khi chng ta c bng d liu tbl_project ri chng ta cn to Yii model class cho php chng ta d dng qun tr d liu trong bng. Chng ti xin gii thiu layer Yiis ORM, Active-RecordBn cn ng nhp vo http://localhost/devyii/index.php?r=gii/default/login g mt khu 1111 sau nhn enter vo Gii

to model bn click vo Model Generator,

Ti y gm cc trng sau:

Table Prefix - Bng chng ta va to l tbl_project v c prefix (tin t ) l tbl_

Table Name : Tn thc ca bng chng ta va to l tbl_project

Model class s t sinh ra l Project nu khng bn hy iu chnh ng nh vy (nhiu bn mc li sai ng ngn on ny nn n khi vo trong code thc mc l sao em generate t trong gii m khng hin th c d liu)

Tip bn in y s ging hnh sau:

Cng vic cn li n gin l click vo Preview -> Generate l bn hon thnh thit k model nhanh chng trong yii .

kim tra bn vo protected/models s thy file mi c to ra c tn Project.php ni y l th m yii t ng sinh ra model cho bn

Bn c th m file project.php ra xem cu trc, n l mt class project c k tha t database layer l CactiveRecord

Tip theo l hm khi to tr v model cha:

public static function model($className=__CLASS__)

{

return parent::model($className);

}

Tip theo l hm khai bo tn bng trong CSDL (tn bng ny trong database phpmyadmin/devyii)

public function tableName()

{

return 'tbl_project';

}

Tip theo l hm rules() cung cp cc quy tc cng l ni nh ngha cc phn t trong bngHm tip theo l relations() s to ra cc mi quan h gia bng ny vi cc bng khc mi th cc bn s c hc ht trong cc chng ti y.

Tip theo l khai bo nhn ca cc phn t trong bng attributeLabels()

V hm mc nh cui cng l hm Search (tm kim ) theo tiu chun c k tha t CdataProvider.

3.3 Kch hot CRUD cho project

Chng ta va to ra AR model, tip n l g ?, theo m hnh MVC th r rng chng ta cn phi c controller thc thi cc hnh ng t model hoc x l u vo t user nh danh, tip chng ta phi generate cc bin d liu v item t model sang view thc hin trng by d liu.K hoch ny tng chng kh khn nhng tht n gin vi Yii nh cng c CRUD (Create-to mi,Read c, Update cp nht, Delete Xa)

Chng ta quay tr li Gii v click vo ng link menu: Crud Generator kch hot tnh nng ny:

Ti y s xut hin 2 trng l Model class l tn Model bn mun generate l Project, v controller class s t ng c sinh ra vi tn Project (lu nu khng vit hoa ch P th phi sa li thnh vit hoa),

tip theo bn nhn preview-> generate. H thng s phn hi thng bo thnh cng tht n gin ng khng bn c th vo trong protected/controller v bn s nhn thy file mi c tn ProjectController.php , tip theo bn vo protected/views/ cc bn cng s nhn thy folder project vi cc file view y , tm kim, cp nht, sa, xa3.4 To mi projectSau khi c hon thnh y m hnh CruD ri bn c th tin hnh kim th v to mi mt project bng vic vo trnh duyt g :http://localhost/devyii/index.php?r=projectTt nhin ban u s khng c bn ghi no v bn s nhn thy dng ch no result found, ta click vo create project menu bn tay phi theo hnh sau:

H thng s yu cu bn ng nhp v bn s ng nhp vi ti khon mc nh ca Yii framework l : Account: demo , Password: demo

y l mt ti khon test user trong yii v g xong bn s thy mt form yu cu nhp cc d n, cc bn in ba vo s c kt qu ging sau y:

iu ny ngha l h thng thc hin thnh cng mt bn ghi v i vo chi tit bn ghi , by gi ta to thm vi bn ghi na ri quay tr li ng link

http://localhost/devyii/index.php?r=project/index s c kt qu tng t sau:

y chnh l list item ca d n, khi bn thm mi bn chuyn sang link ca action Add, bn chnh sa th tc l bn ang thc thi action edit, v bn click vo chi tit mt bn ghi bn i vo action detail3.5 Xc thc hp l cc trng d liu trong FormKhi lm vic vi AR model class khng ch c Form trong Yii, thit lp xc thc cc quy tc xung quanh cc trng d liu ca Form l cn thit, iu gip cho vic kim tra nhng d liu c bit v hn ch li trong csdl, n c thc hin y trong mt mng nh ngha hm rules() nh ti ni trong model Project.phpChng ta vo Protected/models/Project.php v chng ta thy hm ny c nh ngha mc nh khi generate vi mt s quy tc:/**

* @tr v mng d liu xc thc cho cc phn t ca model*/

public function rules()

{

// Bn ch nh ngha cc quy tc cho cc phn t khi m chng // s nhn c thng tin t form input (u vo chng ta va nhp )return array(

array('name, description', 'required'), //tn v m t c yu cu

array('create_user_id, update_user_id', 'numerical', //yu cu kiu s nguyn

'integerOnly'=>true),

array('name', 'length', 'max'=>255),//yu cu ti a khng qu 255 k t

array('create_time, update_time', 'safe'),

// Sau y l khai bo quy tc thng c s dng bi search// Vui lng xa i cc phn t khng mun tm kim.

array('id, name, description, create_time, create_user_id,

update_time, update_user_id', 'safe', 'on'=>'search'),

);

}

Phng thc Rules() tr v mt mng nhng quy tc,mi quy tc l theo nh dng sau:

Array(Danh sch phn t, Xc thc, on=>Danh sch kch bn, thm nhiu thng tin khc);

Sau y l mt lot cc tiu chun xc thc c nh ngha t Yii version 1.1.12

boolean: nh danh ca CBooleanValidator, Kim tra phn t c cha gi tr true hoc false (ng-sai) captcha: nh danh ca CCaptchaValidator, Kim tra gi tr ca phn t c ging vi hnh nh captcha nhp vo hay khng compare: nh danh ca CCompareValidator, So snh hai phn t v kim tra chng ging nhau hay khc nhau email: nh danh ca CEmailValidator, Kim tra gi tr phn t dnge-mail address

date: nh danh ca CDateValidator, Kim tra gi tr phn t dngdate, time, or date-time value

default: nh danh ca CDefaultValueValidator, thm vo mc nh gi tr phn t exist: nh danh ca CExistValidator, Kim tra gi tr phn t c tn ti trong table column trong database

file: nh danh ca CFileValidator, Kim tra gi tr phn t c cha tn uploadfile hay khng filter: nh danh ca CFilterValidator, chuyn i gi tr phn t vi gi tr mi ca filter in: nh danh ca CRangeValidator, validates if the data is within a prespecified

range of values, or exists within a specified list of values//cc dch na mt qu , on cui bao gm kim tra di (length), kim tra ng vi biu thc ton hc (math), kim tra dng s nguyn (numerical), kim tra gi tr c c yu cu bt buc hay khng(required), kim tra thuc tnh c thuc dng c bit hay khng (type), kim tra gi tr c phi l duy nht hay khng (unique), kim tra d liu c phi l on URL hay khng(url) length: Alias of CStringValidator, validates whether the length of the

attribute value is within a specified range

match: Alias of CRegularExpressionValidator, uses a regular expression

to validate the attribute value

numerical: Alias of CNumberValidator, validates whether the attribute value

is a valid number

required: Alias of CRequiredValidator, validates whether the attribute

value is empty or not

type: alias of CTypeValidator, validates whether the attribute value is of a

specific data type

unique: Alias of CUniqueValidator, validates that the attribute value is

unique, and is compared against a database table column

url: Alias of CUrlValidator, validates whether the attribute value is a

valid URL

3.6 c projecty chnh l chi tit ca mt item bn c th vo ng link sau xem th mt item:

http://localhost/devyii/index.php?r=project/view&id=1

3.7 Cp nht v xa project

Khi cc bn nhn vo menu bn tay phi s thy hng lot cc link menu nh sau: Khi bn cp nht v to, xem danh sch, c chi tit u c nhng khng th xa hoc qun l v b bo li access denid bi v bn ang s dng account dnh cho user khng c quyn xc thc, v th bn logout ra ngoi v ng nhp li bng account mi l : Account: admin , Password: admin , bn s hon ton c th xa v xem mc qun l c.

Bn c th nhn thy bn trn c hng lot cc lc tm l do bn khai bo bn hm rules(), bn c th vo trong v xa i ch li 2 trng l id, name th c v hp l hn.

Chng 3 . Qun l cc vn

(Issue)Vy l hm nay l nm mi 14h-52 pht ngy 01/01/2013, ti ang ngi gh bn cnh i din vi tng i Hng o Vng Trn Quc Tun, hm nay tht ng ngi i cu may cu lc, cn ti th vn lm vic, cng vic mang con ngi ta n s cht chc, mt mi cng thng nhng lao ng l vinh quang hy n nhn n, ng ph ng nght ngi c hoa ging kn nhng bng cc vng v bng hng rc, cc i tnh nhn tay trong tay do bc, bn b quy qun bn nhau,nhn sang bn tay tri l i din vi thp ra c knh, mt s yn lng v tnh mch nh vn c ca n,c l chm gi nhiu ch c li ch g cho vic hc ca cc bn nn chng ta tp trung vo cng vic bt u xy dng bng d liu th 2 l issues . qun trc khi vo lm cng phi chc mi ngi nm mi vui v hnh phc ch hehe!Trong cc chng trc chng ta thc thi hm c bn xung quanh thc th project, by gi chng ta thc hin vi issues chng ny kh di v vy cc bn c gng tp trung.Project l thnh phn ch o ca ng dng mi tuy nhin mi d n t chng khng tht s hon ho, project cha ng nhng vn lin quan khi chng ta mun qun tr ng dng,lc qun tr cc vn trong d n l mc tiu chnh thc hin trong ng dng, chng ta s mun thm mt s hm cha vn qun tr c bn. K hoch xa hn

Chng ta to c thnh phn qun tr project, nhng chng ta cha c cch no qun l cc vn (issue) lin quan n d n , khi kt thc chng ny chng ta mong mun l thc hin c tt c CRUD trong vn ca d n hoc cc nhim v (task).trong d liu model,mt nhim v (task) s lun lun ch c mt thuc tnh ca issue. Chng ta cng mun trch ra tt c CRUD trong issues cng vi project, iu c ngha l issues thuc v (belong to) project (Lu y l quan h - relationship).User phi la chn cc d n tn ti v lm vic, lit k danh sch thc hin CRUD vi cc vn trong d n.

Chng ta hy nhn danh sch ngh bn cn lm nh sau:

1. Thit k biu d liu v xy dng i tng h tr cc vn trong d n

2. To Yii model class cho php ng dng d dng khi to kt ni vi d liu trong bng

3. To controller class s cha cc hm cho php chng ta thc hin :

To mi vn

Lc danh sch cc vn tn ti trong project t database

Cp nht/iu chnh cc vn

Xa cc vn

4. To views folder render giao din ngi dng cho cc action

By gi chng ta i vo thc hin

III.1 Thit k biu Trong chng trc chng ta c th nhn s qua v tng ca thc th issues, chng ta thc hin n c cc trng d liu gm : name tn vn , type thuc tnh vn , owner bn thn, requestor ngi yu cu, status trng thi, v description miu t. Chng ti cng ngh sau khi to bng tbl_project chng ta cn mt s thng tin khc nh dates, times,v user cp nht bng .Tuy nhin type , owner, requestor, status bn thn chng l nhng thc th. Trong owner bn thn, requestor ngi yu cu l hai ngi dng s dng h thng v h s tc ng vo bng d liu thng qua bng tbl_user. Chng ta bt u lin tng ti user trong bng tbl_project l create_user_id v update_user_id l nhng nh danh ca user cp nht hay to ra d n, xc thc c chng ta cn kha ngoi (foreign key) tham chiu ti bng tbl_user, lc owner_id v requestor_id trong bng tbl_issues cng s c kha ngoi tham chiu ti bng tbl_user. D hiu con m ln cIII.1.1 nh ngha mt s quan h (relationships)

T khi chng ta gii thiu bng tbl_user , chng ta cn nh ngha li quan h gia user v project, trong chng trc cc user s lin quan ti 0 hoc nhiu project, chng ta cng c th thit lp project c 1 hoc nhiu user. Chng ta gi quan h gia hai bng trn l quan h nhiu nhiu (many to many). Tht d dng xy dng quan h many-to-many trong model, chng ta c th nhn s qua v quan h c bn ca thc th- quan h gia user, project, issues. Project c th c 0 hoc nhiu user,mt user cn lin quan ti t nht mt project nhng c th lin quan nhiu,Issues (belong to) thuc v mt v ch mt project , khi project c th c t 0 n nhiu user. Mt vn c kt thc v c ng k bi (ngi yu cu) v ch duy nht mt user.

1 Or More : 1 hoc nhiu0 or More : 0 hoc nhiu

Exactly One: Ch mt

III.1.2 xy dng i tng t nhng quan h trc

Chng ta s phi to ra 3 bng mi bao gm tbl_issue, tbl_user v bng trung gian tbl_project_user_assignmentBng tbl_issue

create table tbl_issue(

id int(11) not null primary key auto_increment,

name varchar(255) not null,

description text,

project_id int(11) DEFAULT NULL,

type_id int(11) DEFAULT NULL,

status_id int(11) DEFAULT NULL,

owner_id int(11) DEFAULT NULL,

requester_id int(11) DEFAULT NULL,

create_time datetime DEFAULT NULL,

create_user_id int(11) DEFAULT NULL,

update_time datetime DEFAULT NULL,

update_user_id int(11) DEFAULT NULL

)ENGINE=InnoDB;Copy v paste to bng cho n nhanh nhng ch nhn cc trng d liu m nh.

Tip theo l table tbl_user

create table tbl_user(

id int(11) not null primary key auto_increment,

username varchar(30) not null unique key,

email varchar(1000) not null,

password varchar(255) not null,

last_login_time datetime DEFAULT NULL,

create_time datetime DEFAULT NULL,

create_user_id int(11) DEFAULT NULL,

update_time datetime DEFAULT NULL,

update_user_id int(11) DEFAULT NULL

)ENGINE=InnoDB;V cui cng l bng trung giancreate table tbl_project_user_assignment(

project_id int(11) NOT NULL auto_increment,

user_id int(11) NOT NULL,

PRIMARY KEY (`project_id`,`user_id`)

)ENGINE=InnoDB;To kha ngoi quan h gia tbl_issue v tbl_projectAlter table tbl_issue Add constraint fk_issue_project foreign key(project_id) references tbl_project(id) on delete cascade on update restrictTo kha ngoi quan h gia user vi owner (bn thn ngi ) tbl_issue v tbl_useralter table tbl_issue add constraint fk_issue_owner foreign key(owner_id) references tbl_user(id) on delete cascade on update restrictTo kha ngoi quan h gia user v ngi yu cu (requestor)alter table tbl_issue add constraint fk_issue_requester foreign key(requester_id) references tbl_user(id) on delete cascade on update restrictTo kha ngoi quan h gia bng trung gian vi projectalter table tbl_project_user_assignment add constraint fk_project_user foreign key(project_id) references tbl_project(id) on delete cascade on update restrictTo kha ngoi quan h gia bng trung gian v useralter table tbl_project_user_assignment add constraint fk_user_projects foreign key(user_id) references tbl_user(id) on delete cascade on update restrictSau khi thc hin xong cc query xong bn hy m mt s cng c theo di m hnh schema database c th nhn thy m hnh d liu vi cc khaIII.1.3 To AR (Active Record) model class

By gi chng ta c y cc bng, bc tip theo l to model vi Yii model AR cho php chng ta d dng thao tc vi bng trong ng dng, chng ta cng lm vic ny trong vic to model ca Project chng trc v th nn thao tc s khng c g thay i nhiu, chng ta vo GiiIII.1.4 To Issue Model class

Vo Gii vi ng dn : http://localhost/devyii/index.php?r=gii/default/login v nhn 1111 chng ta s vo menu generate

Chng ta click vo Model Generator , ti trng table prefix chng ta in tbl_ (y l tin t bng)

Ti trng table name ta in : tbl_issue, ti trng Model class ta in Issue

Tip theo bn nhn preview -> generated.Chng ta c th vo protected/models kim tra v s thy Issue.phpIII.1.5 To User model class

Vic to User model class l khng cn thit bi v bn thn Yii h tr thao tc vi user khi s dng Yiis DAO , AR model cung cp mt Biu quan h i tng (Object Relational Mapping- ORM) cho ng dng gip chng ta d dng qun l i tng trong domain.III.1.6 To Issue CRUD operationBn vo Gii v click vo menu link CRUD Generator sau in vo trng Model Class : Issue, in vo trng controller id : Issue (Lu I u c vit hoa) -> preview -> generated.

Sau khi thc hin xong ta hon thnh v vo trnh duyt kim tra: http://localhost/devyii/index.php?r=issue

III.1.7 To mi IssueSau khi thc hin xong bn to mi mt vi bn ghi v vo ng nhp vi acc: admin pass: admin khi h thng yu cu ng nhp

III.1.8 Thm thuc tnh drop downChng ta s to 3 thuc tnh dropdown bao gm Bugs,Features, Tasks. Khi chng ta to mi issue s c 3 la chn cho form field.

Vo protected/models/Issue class v nh ngha cc hng sau:

const TYPE_BUG=0;

const TYPE_FEATURE=1;

const TYPE_TASK=2;

Tip theo xy dng hm getTypeOptions() s tr v gi tr cho cc thuc tnh trn:

public function getTypeOptions()

{

return array(

self::TYPE_BUG=>'Bug',

self::TYPE_FEATURE=>'Feature',

self::TYPE_TASK=>'Task',

);

}

III.1.9 Thm thuc tnh drop-down vo viewsVo protected/views/issue/_form.php v tm trng Type trong form:

Tip theo bn nhn ln on u ca file s c on khai bo form:

y l cch nh ngha mt form s dng CactiveForm trong Yii.

Tip theo bn vo IssueController.php trong protected/controller/IssueController v nhn vo hm actionCreate().

public function actionCreate()

{

$model=new Issue;

// Uncomment the following line if AJAX validation is needed

// $this->performAjaxValidation($model);

if(isset($_POST['Issue']))

{

$model->attributes=$_POST['Issue'];

if($model->save())

$this->redirect(array('view','id'=>$model->id));

}

$this->render('create',array(

'model'=>$model,

));

}

Ti y chng ta c th nhn thy views c render, n ang tr v mt khi to ca Issue model, v gi tr tr v gi l $model.

By gi chng ta quay li file views xem cch x l ca trng Type trong form. Dng u l :

$form->labelEx($model,'type_id');

Dng ny s dng CactiveForm::labelEx() phng thc chuyn qua nhn HTML cho issue model vi phn t type_id. N cng c khi to trong model class v s l cc nhn phn t cho nhng nhn ta mun thay i. l hm Issue::attributeLabels() c s dng quyt nh la chn label, nu chng ta nhn vo form th nhn ca type_id l Type c chuyn qua t hm attributeLabels().public function attributeLabels()

{

return array(

'id' => 'ID',

'name' => 'Name',

'description' => 'Description',

'project_id' => 'Project',

'type_id' => 'Type',

'status_id' => 'Status',

'owner_id' => 'Owner',

'requester_id' => 'Requester',

'create_time' => 'Create Time',

'create_user_id' => 'Create User',

'update_time' => 'Update Time',

'update_user_id' => 'Update User',

);

}Tr li view vi trng type_id ta c th nhn s qua nh sau:

S dng labelEx() cng c th x l c dng tch khi fields d liu c yu cu. labelEx() s thm mt css class tn CHtml::requiredCss vi mc nh l required v CHtml::afterRequiredLabel vi mc nh l * sau mi phn t c yu cu.

Dng tip theo s dng CactiveForm::textField() phng thc chuyn qua dng text-input field cho phn t type_id trong Issue model.Bt k quy tc kim tra d liu u c nh ngha trong Issue::rules() , phng thc ny s xc thc cc quy tc vi form u vo.

Cui cng l c s dng CactiveForm::error() chuyn qua xc thc li lin quan vi phn t type_id.Bn th nhn li tnh xc thc cc thuc tnh d liu , type_id ct c nh ngha l integer trong bng MySql v vy Gii generated vi quy tc xc thc trong Issue::rules() phng thc ny nh ngha nh sau:public function rules()

{

// NOTE: you should only define rules for those attributes that

// will receive user inputs.

return array(

array('name', 'required'),

array('project_id, type_id, status_id, owner_id, requester_id,

create_user_id, update_user_id', 'numerical', 'integerOnly'=>true),Chnh v xc thc quy tc ny nn khi bn in dng ch trong form vi trng Type s gp bo li sau y:

Tip theo hin th dropdown list chng ta cn thay th dng c ca type_id trong protected/views/issue/_form.php:

Thay th thnh :

Xong xui vo trnh duyt xem kt qu: http://localhost/devyii/index.php?r=issue/create

xc thc type_id trong form bn cn gii hn xc thc (Range Validation) vi CrangeValidator ca Yii h tr, bn thm vo hm Issue::rules() dng sau:

array('type_id', 'in', 'range'=>self::getAllowedTypeRange()),

public function rules()

{

// NOTE: you should only define rules for those attributes that

// will receive user inputs.

return array(

array('name', 'required'),

array('type_id', 'in', 'range'=>self::getAllowedTypeRange()),

array('project_id, type_id, status_id, owner_id, requester_id, create_user_id, update_user_id', 'numerical', 'integerOnly'=>true),

array('name', 'length', 'max'=>255),

array('description, create_time, update_time', 'safe'),

// The following rule is used by search().

// Please remove those attributes that should not be searched.

array('id, name, description, project_id, type_id, status_id, owner_id, requester_id, create_time, create_user_id, update_time, update_user_id', 'safe', 'on'=>'search'),

);

}Ta xy dng thm hm getAllowedTypeRange() trong class:

public static function getAllowedTypeRange()

{

return array(

self::TYPE_BUG,

self::TYPE_FEATURE,

self::TYPE_TASK,

);

}

Hm validator rules ny kim tra input u vo tr v c nm trong danh sch hay khng, khi bn sa i thng tin vi u vo l 6 kt qu s th ny :

III.1.10 Sa li trng d liu owner v requesterMt vn chng ta gp phi vi vic to form Issue l field owner v requester l freeform text-input . Tuy nhin chng ta bit rng gi tr integer trong bng issue ang gi nh danh kha ngoi (foreign key) ti ct id ca bng tbl_user. V th nn chng ta cn thm drop-down field cho chng. Chng ta khng th bit ch xc mi k hoch chng ta lm cho phn t type v status, cng nh owner v requesters c tin hnh t tbl_user. Nh vy mi ngi dng trong h thng s lin quan vi project bi nhng vn (issue) lin quan. V nhng issue khng th dropdown vi d liu t bng tbl_user. Chng ta cn lc ra danh sch u vo ca nhng ngi dng c lin quan ti project .

iu ny c ngh trong k hoch xa hn chng ny, chng ta cn qun l vn vi khng ch ni dung ca project c bit. Ngha l project c bit s c chn trc khi bn c th to vn (issue) mi. Khi mt project c chn chng ta cn chc chn c bn thn (owner) v ngi yu cu (requester) dropdown la chn c trch lc ra nhng user lin quan ti d n.

III.1.11 Kim tra ni dung projectChng ta mun chc chn rng ni dung project hp l c hin th trc khi chng ta cho php truy cp ti qun tr Issue. lm iu ny chng ta cn lm vic thc thi ci gi l b lc (filter). Mt b lc trong yii l nhng iu chnh cu hnh c thc hin trc khi hoc sau khi mt controller action c thc hin. Mt v d v lnh l nu chng ta mun chc chn ngi dng ng nhp t vic thc hin controller action method. Chng ta c th vit n gin b lc truy cp s kim tra cc yu t trc khi action c thc hin.

III.1.12 nh ngha filters (b lc)

Mt filters(b lc) c th c nh ngha nh mt controller class hoc n c th l mt class. Khi s dng k hoc n gin (simple-method), tn phng thc phi bt u bng t filter v c mt k t c bit. Cho v d nu chng ta ang to mt b lc phng thc : someMethodName, ta s vit filter nh sau:

public function filterSomeMethodName($filterChain)

{

...

}C mt k hoch khc s dng filter l dng class thc hinfilter logic, khi s dng class filter phi c k tha t Cfilter v c ti t nht preFilter() hoc postFilter() method quyt nh mc logic thc hin trc hoc sau mt action c khi to.III.1.13 Thm mt Filter

By gi chng ta s thm mt filter trong IssueController class iu khin kim tra mt project hp l. Chng ta tin hnh k hoch:

M protected/controllers/IssueController.php v vit hm filter sau on di gm class (sau function search).

public function filterProjectContext($filterChain)

{

$filterChain->run();

}

Ok, by gi chng ta nh ngha mt filter, tuy nhin cha c g nhiu y n gin ch l thc thi filter ($filterChain->run()), ci m x l filter v cho php thc hin cc phng thc action c lc bi method, iu ny mang ti mt im khc, Lm cch no chng ta nh ngha ci action method c s dng filter ?

III.1.14 Action filters c bitYii framework c class c bn ca controller l Ccontroller. N l mt filter method cn c ti sau mi thc n c bit ca action trong ci filter cn c p dng. Thc t phng thc ny c ti trong IssueController class.iu c lm y khi chng ta s dng Gii tool t ng to ra class ny. N to ra accessControl filter ci m c nh ngha trong Ccontroller, s l mt s hnh ng c bn chc chn rng ngi dng ang s dng c phn quyn s dng acction ny.Nu bn khng ng nhp v click vo link Create Issue bn s b chuyn hng ti trang login v c nh danh cho ti khi bn c php to mi issue.Access controll filter x l iu ny. Chng ta s khm ph nhiu hn v filter . bt u chng ta cn thm mi filter cho mng cu hnh IssueController::filters() (cho vo cnh hm filter c cng c)public function filters()

{

return array(

'accessControl', // perform access control for CRUD operations

'projectContext + create', //check to ensure valid project context

);

}Filters ny tr v mng cu hnh , trong hm filters trc chng ta to projectContext filter ci m c nh ngha nh mt phng thc v p dng thm c action create . Cu hnh ny cho php vi cc c php +, - s dng vi cc filter c p dng v khng c p dng.Cho v d chng ta mun p dng vi tt c cc action ngoi tr action Update() v actionView() ta lm nh sau:

Return array(

projectContext update, view,

);Bn s khng cng + hay cng - c hai action cng mt lc,III.1.15 Thm mt filter logic

Ok, by gi chng ta nh ngha filter v chng ta cu hnh n gi khi actionCreate() c kch hot vi Issue controller class.

Tuy nhin n vn khng thc hin theo logic,khi chng ta mun chc chn project context filter trc khi action c khi ng,chng ta cn t logic filter trc khi gi $filterChain->run().

Chng ta s thm thuc tnh project t controller class,Chng ta s s dng query string (chui truy vn) t tham s trong URL nh danh project.Ngoi preAction filter s kim tra xem phn t trong project c tn ti hay null,nu ng n s s dng query string tham s khi ng vic la chn project trong nh danh kha chnh (primary key). Nu thnh cng action s thc thi, nu tht bi ngoi l s c xut ra, sau y l code : Bn hy thay th ni dung cc hm filter bng cc hm mi di y trong protected/controller/IssueContrller.phpclass IssueController extends CController

{

....

/**

* @var private property containing the associated Project model instance.

*/

private $_project = null;

/**

* Protected method to load the associated Project model class

* @param integer projectId the primary identifier of the associated Project

* @return object the Project data model based on the primary key

*/

protected function loadProject($projectId)

{

//if the project property is null, create it based on input id

if($this->_project===null)

{

$this->_project=Project::model()->findByPk($projectId);

if($this->_project===null)

{

throw new CHttpException(404,Yeu cau project khong ton tai.');

}

}

return $this->_project;

}

/**

* In-class defined filter method, configured for use in the above filters()

* method. It is called before the actionCreate() action method is run in

* order to ensure a proper project context

*/

public function filterProjectContext($filterChain)

{

//set the project identifier based on GET input request variables

if(isset($_GET['pid']))

$this->loadProject($_GET['pid']);

else

throw new CHttpException(403,Chi cac project dac biet hien ra truoc khi thuc hien action nay.');

//complete the running of other filters and execute the requested action

$filterChain->run();

}

...

}

Sau khi thay th hon chnh bn vo trnh duyt kim tra:http://localhost/devyii/index.php?r=issue/create

III.1.16 Thm Project ID chng to project chng ta thm nhiu project kim tra h thng, tuy nhin nhng ai cha to th vui lng vo http://localhost/devyii/index.php?r=project to khong vi project chun b cho cng vic tip theo ny.Bi v cng vic tip theo yu cu phi c ID ca project c th thm id ny ti vic to mi issue URL.Tip theo chng ta cn iu chnh links trong view file issue : protected/views/issue/index.php. Nhn pha trn u file bn s thy ni links c nh ngha qua mng menu items:

$this->menu=array(

array('label'=>'Create Issue', 'url'=>array('create')),

array('label'=>'Manage Issue', 'url'=>array('admin')),

);

thm chui tham s truy vn (query string paramter) ti links chng ta n gin thm trng name=>value trong phn nh ngha mng tham s url, chng ta th lm vi project id=1 , iu chnh dng Create Issue:

array('label'=>'Create Issue', 'url'=>array('create', 'pid'=>1)),

By gi khi bn xem trang issue listing , bn s nhn thy Create Issue vi link url nh sau: http://localhost/devyii/index.php?r=issue/create&pid=1y l chui tham s truy vn cho php lc thuc tnh thit lp project context, lc ny khi bn click vo link http://localhost/devyii/index.php?r=issue/create s hin li 403 v ch c link trn mi hin thIII.1.17 iu chnh chi tit trang projectVic thm project_id ti url cho vic to mi issue (Create new issue) link l thc s cn thit cho giai on u chc chn rng b lc lm vic hiu qu. Tuy nhin chng ta lun lun nhn thy link url khi to mi issue lun vi project id l 1, tt nhin khng phi iu chng ta mun. Nhng g chng ta mun lm l c mt menu option cho vic to mi issue tr thnh mt phn ca trang chi tit project. Vi cch ny,bn c th la chn mt project t danh sch project , project context c bit s c hin th v chng tay thm ng project id to mi links issue, hy lm n thay i.M protected/views/project/view.php. Nhn trn u file bn s thy mng menu $this->menu=array(.). Chng ta cn thm link khc to mi issue v tr kt thc danh sch menu

$this->menu=array(

array('label'=>'List Project', 'url'=>array('index')),

array('label'=>'Create Project', 'url'=>array('create')),

array('label'=>'Update Project', 'url'=>array('update',

'id'=>$model->id)),

array('label'=>'Delete Project', 'url'=>'#', 'linkOptions'=>array('s

ubmit'=>array('delete','id'=>$model->id),'confirm'=>'Are you sure you

want to delete this item?')),

array('label'=>'Manage Project', 'url'=>array('admin')),

array('label'=>'Create Issue', 'url'=>array('issue/create',

'pid'=>$model->id)),

);Vo trnh duyt g http://localhost/devyii/index.php?r=project/view&id=1

Bn s nhn thy cui menu l link to issue,By gi chng ta c thuc tnh project context c thit lp khi to mi issue, chng ta c th remove trng form project cng nh trng form user input. M protected/views/issue/_form.php xa b on sau:

Tuy nhin dng nh project_id s khng c submit t form,chng ta s cn thit lp tham s project_id t b lc (filter) m chng ta mi thc thi. Sau chng ta bit c project_id lin quan,hy thit lp gi tr ca Issue::project_id t gi tr ca id bng project c ci t bi filter trc . V vy chng ta cn iu chnh IssuesController::actionCreate() method:public function actionCreate()

{

$model=new Issue;

$model->project_id = $this->_project->id;Bn to mi issue vi project_id = 2 v s c kt qu :

III.1.18 Tr li vi dropdown owner requesterCui cng , chng ta tr li vi nhng g chng ta thit lp trc ,vi s thay i owner v requester khi la chn dropdown hp l khi la chn project.

Trong thc n ny chng ta cn mt s user lin quan ti project, sau qun tr user trong focus ca chng sau,chng ta s lm nhiu hn vic thm ng dn lin quan ti database vi ng dn sql chng ta cn thm 2 user vo mysql:

INSERT INTO tbl_user (email, username, password) VALUES ('test1@

notanaddress.com','User One', MD5('test1')), ('test2@notanaddress.

com','User Two', MD5('test2'));

Khi bn chy ng dng mi ny, bn s to 2 user mi trong h thng vi id l 1 v 2. Chng ta cn assign (ng k)hai user ny ti project

INSERT INTO tbl_project_user_assignment (project_id, user_id)

VALUES (1,1), (1,2);Mt iu tuyt vi ca quan h trong Active Record vi Yii l kh nng truy cp hp l thnh vin ca ng dng vi issue vi quan h thuc v (belong to),tham chiu t issue model khi to.Sau khi chng ta s dng Gii tool khi to issue model class, chng ta chc chn tch vo check box trng Build Relations thng l mc nh tch ri.iu ny cho php chng ta xy dng mi quan h gia cc bng. Chng ta c th nhn hm relations() t protected/models/Issue.php

Sau chng ta to class sau khi thm mi qun h trong database:

public function relations()

{

//NOTE: you may need to adjust the relation name and the related

// class name for the relations automatically generated below.

return array(

'requester' => array(self::BELONGS_TO, 'User', 'requester_id'),

'owner' => array(self::BELONGS_TO, 'User', 'owner_id'),

'project' => array(self::BELONGS_TO, 'Project', 'project_id'),

);

} y quan h requester thuc v user.requester_id bi issue.requester tham chiu ti bng tbl_user, tng t vi 2 trng cn li.y l cu hnh c khi to t AR model, vi quan h ny chng ta c th truy cp vo AR class lin quan mt cch d dng.cho v v, chng ta mun truy cp mt project t mt issue lin quan:

//create the model instance by primary key:

$issue = Issue::model()->findByPk(1);

//access the associated Project AR instance

$project = $issue->project;

Khi chng ta to Project model class vi nhng bng khc c nh ngha c mi quan h (relashionship), tuy nhin by gi chng ta c mt s quan h c nh ngha, chng ta cn thm Project::relations(). M /protected/models/Project.php v thay th ni dung trong hm relations():public function relations()

{

return array('issues' => array(self::HAS_MANY, 'Issue', 'project_id'),'users' => array(self::MANY_MANY, 'User', 'tbl_project_user_assignment(project_id, user_id)'),

);

}

Issues: //mt issue c th c mt hoc nhiu trong 1 d n

Users: //mt user c th mt hoc nhiu trong mt hoc nhiu d nVi s thay th trn chng ta d dng truy cp tt c issue hoc user lin quan ti project mt cch d dng.$project = Project::model()->findByPk(1);

$allProjectIssues = $project->issues;

$allUsers = $project->users;

$ownerOfFirstIssue = $project->issues[0]->owner;

Thng thng chng ta c th vit lnh SQL trng thi ni truy cp ti d liu lin quan,s dng quan h trong AR Yii gip chng ta d dng v nhanh gn hn.Chng ta c th truy cp quan h d dng d c v d hiu.

III.1.19 Generating the data to populate the dropdownsTheo k hoch chng ta cn dropdown d liu ca status v type . Chng ta s thm hm getUserOptions() ti Project model class:M protected/models/Project.php v thm on sau vo di class:

/**

* @return array of valid users for this project, indexed by user IDs

*/

public function getUserOptions()

{

$usersArray = CHtml::listData($this->users, 'id', 'username');

return $usersArray;

}

y chng ta s dng Yiis CHtml class gip chng ta to mng id=>username t cc user lin quan ti project. Nh rng thuc tnh users (nh ngha trong method relations()) trong project class khi s dng AR model. CHtml::listData() l phng thc c th tin hnh trong danh sch v s dng mng hp l t CactiveForm::dropDownList();By gi chng ta c hm getUserOptions() tr v d liu chng ta cn, chng ta thc thi dropdown hin th d liu tr v,chng ta s s dng filter thit lp project id lin quan t request $_GET,v chng ta s dng gi tr thit lp project_id khi to mi issue lc bt u thc hin IssueController::actionCreate() method, by gi bn c cm thy AR thc s d dng v nhanh gn khng ?Chng ta hy thay i trong form issue:

M protected/views/issue/_form.php v tm hai trng text-input owner_id v requester_id v thay th n vi on sau:

Tr thnh

V thay th :

Thnh : Vo trnh duyt g : http://localhost/devyii/index.php?r=issue/create&pid=1Nu khng vo c v bo li vui lng vo Gii, click menu : Model generator sau ti trng table prefix : tbl_ , ti trng table name : tbl_user , ti trng model class : User sau preview->generated.

Nu vn cha vo c vui lng vo Gii, click menu : Model generator sau ti trng table prefix : tbl_ , ti trng table name : tbl_project_user_assignment , ti trng model class : ProjectUserAssignment sau preview->generated.

III.1.20 Lm ln thay i cui cngSau khi chng ta bt u to issue form ,hy lm nhanh mt ln thay i cui cng,Vic to time v user cng nh time update v user update field chng ta c trong mi bn ghi l c s history (lch s) v nh du ngi dng no cp nht bn ghi. Sau chng ta s iu chnh ng dng logic mt cch t ng ph bin vi field x l insert hoc update. By gi , hy xa i field input trong form ca chng:Vo protected/views/issue/_form.php xa cc on sau:

Sau khi thc hin xong form ca chng ta ch cn nh sau:

III.1.21 X hi vi CRUDPhn ch ca chng ny l thc thi tt c CRUD operation cho Issue. Chng ta c kt thc vic to ra cc hm, nhng chng ta vn cn hon thnh phn chi tit (read), cp nht (update), v xa (delete) cho Issue, Tht may mn hu ht tiu chun ny thc thi trong Gii CRUD khi generated cc hm. Tuy nhin sau chng ta mun qun l tt c Issue vi khng ch vn cnh ca project, chng ta cn lm mt s iu chnh sao cho chng ta c th truy cp vo cc hm chc nng.

III.1.22 Danh sch vi IssueMc d chng ta tng ngh v actionIndex() method trong IssueController class n hin th danh sch tt c issue trong CSDL, chng ta khng mun iu ny trong hm chc nng.Dng nh khng tht s tt khi m tt c danh sch cc issue trong CSDL c hin th ra,V th nn chng ta s iu chnh ng dng hin th danh sch ca mt phn issue lin quan ti project trong chi tit trang. Lc chng ta tin hnh thay i quan h AR model trong Yii, n s lm biu thay i.

III.1.23 iu chnh project controller

Trc tin chng ta s iu chnh actionView() method trong ProjectController class. Sau chng ta mun hin th danh sch cc issue lin quan vi cc d n c bit m chng ta chn, chng ta c th lm iu ny vi cng mt trang chi tit project. Method actionView() l method c hin th trong chi tit project.

Chnh li method sau: protected/controller/ProjectController.phppublic function actionView($id)

{

$issueDataProvider=new CActiveDataProvider('Issue',

array('criteria'=>array(

'condition'=>'project_id=:projectId',

'params'=>array(':projectId'=>$this->loadModel($id)->id),

),

'pagination'=>array('pageSize'=>1,),

));

$this->render('view',array('model'=>$this->loadModel($id),

'issueDataProvider'=>$issueDataProvider,

));

}

Ti y chng ta s dng CactiveDataProvider (Kch hot nh cung cp d liu do Yii to ra) framework class cung cp d liu s dng i tng ca Cactive Record (kch hot bn ghi), n s s dng cc quan h AR model lin quan trch lc d liu t CSDL trong v chng ta s s dng n mt cch d dng. Bng vic xy dng thnh phn danh sch gi l ClistView.

Chng ta s dng thnh phn ny hin th danh sch ca issue trong view file. Chng ta s dng thuc tnh tiu chun quyt nh iu kin s ch lc danh sch issue lin quan ti project ang c hin th, chng ta cng s dng thuc tnh phn trang (pagination) gii hn bn ghi trong danh sch issue c lc ra.

Th cui cng chng ta lm thm d liu c cung cp ny vo mng nh ngha c gi l render(), lm n hp l khi chuyn sang view file vi bin $issueDataProvide.

III.1.23 Chnh li file View ca projectNh chng ti ngh ,chng ta s s dng thnh phn trong framework gi ti ClistView hin th ngoi danh sch cc issue trong project chi tit trang. M protected/views/project/view.php v thm on sau di cng file:

Project Issues

Vy l chng ta thit lp thuc tnh dataProvider trong ClistView t issue dataprovider m chng ta to trong controller.V sau chng ta cu hnh n s dng t protected/views/issue/_view.php file nh mt templates cho render mi item trong data provider. File ny c to cho chng ta bi Gii tool khi chng ta generated CRUD cho Issue.Chng ta s dng n ti y hin th issue trong project chi tit trang.Chng ta cng cn lm s thay i protected/views/issue/_view.php file chng ta iu chnh c bit nh mt layout templates cho mi issue. Chnh li ni dung thc th ca file nh sau:

:


:


:


:

Ok, bn vo trnh duyt g : http://localhost/devyii/index.php?r=project/view&id=2 xem kt qu:

III.1.24 Tin hnh status v type text hin th

Trc chng ta va thm public method Issue AR class, trch lc status v type option ti dropdown issue form chng ta cn thm mt s method trong AR class tr v text cho status v type c bit hoc type id.Vo protected/models/Issue.php :

public function getStatusText()

{

$statusOptions=$this->statusOptions;

return isset($statusOptions[$this->status_id]) ?

$statusOptions[$this->status_id] : "unknown status ({$this->status_

id})";

}

/**

* @return string the type text display for the current issue

*/

public function getTypeText()

{

$typeOptions=$this->typeOptions;

return isset($typeOptions[$this->type_id]) ? $typeOptions[$this->type_id] : "unknown type ({$this->type_id})";

}

Ti y s tr v cc trng thi value (Chua san sang,San sang,ket thuc) v thuc tnh text (bug,feature,task) ci t cho issue.Bn vo protected/model/issue.php thm on khai bo sau:

const STATUS_NOTYET=0;

const STATUS_YET=1;

const STATUS_FINAL=2;public function getStatusOptions()

{

return array(

self::STATUS_NOTYET=>'Chua San Sang',

self::STATUS_YET=>'Sang Sang',

self::STATUS_FINAL=>'Hoan Thanh',

);

}public static function getAllowedStatusRange()

{

return array(

self::STATUS_NOTYET,

self::STATUS_YET,

self::STATUS_FINAL,

);

}Thm on sau vo array trong function Issue::rules()

array('status_id','in','range'=>self::getAllowedStatusRange()),Trong Issue::relations() bn thm on sau:

'users'=>array(self::MANY_MANY,'User','tbl_project_user_assignment(project_id,user_id)'),public function getUserOptions()

{

$usersArray=CHtml::listData($this->users,'id','username');

return $usersArray;

}Vo protected/views/issue/_form.php chnh li nh sau:

III.1.25 Thm on hin th text ti formVo protected/views/issue/_view.phpThay th this thnh:

V thnh

(ch mi to xong status v type th bn phi vo link menu manage v click vo hnh edit trong view list ri chn cc trng to ra cc id cho 2 trng ny, nu khng kt qu hin ra s l unknow hoc s b bo li khng nhn din c kt qu tr v v khng i tng c khi to )V y l thnh qu:

III.1.26 Thay i chi tit khung nhn IssueChng ta hy vo http://localhost/devyii/index.php?r=issue/view&id=1 v thy cc trng thi vn cn nm dng s 0 , 1, iu c ngha chng ta vn cha thay i v y l cng vic chng ta phi lm

Ti v chng ta s dng view file mc nh nn cha cu hnh ht, iu chnh chng ta cn vo protected/views/issue/view.php

Chng ta s s dng Zii c k tha t widget CdetailView, ci m chng ta nhn thy trc file view project m chng ta thm ClistView,

V chng ta c th nhn thy on sau trong protected/views/issue/views.php

Ti y chng ta thit lp d liu cho model Cdetail View widget t Issue Model class c khi to ( l khi to c bit khi chng ta mun hin th chi tit) v sau khi thit lp danh sch ca phn t khi model c khi to hin th trong render chi tit views, mt phn t c th c trng ging nh chui nh dng : tn : thuc tnh: nhn, vi c hai i tng type v label hoc array, trong trng hp ny chng ta ch s dng tn ca phn t.

Nu chng ta thy mng phn t ny, chng ta c th custom vic hin th tt hn t vic nh ngha li cc yu t. Chng ta s tin hnh k hoch trong thc n c bit ca model class method Issue::getTypeText() v Issue::getStatusText() c s dng hin th gi tr text cho type v status field.

Hy thay i trong CdetailView nh sau:

Sau khi thc hin xong vo http://localhost/devyii/index.php?r=issue/view&id=1 xem kt qu:

III.1.27 Hin th tn owner v requester

T nh trn bn cng c th nhn thy, bn ch mi nhn thy id ca user to ln hoc user yu cu n, cng vic ca bn by gi l thay th n bng tn ca user trong bng user.

S dng Quan h AR

Sau khi Issues v users c trnh din li ging nh bng d liu v mi quan h bi kha ngoi (foreign key) chng ta c th truy cp c vo owner v requester username t $model trong view file nh cng c mnh ca Yii AR , by gi cng vic ca chng ta l nh ngha li mi quan h trong Issue::relations()

'owner' => array(self::BELONGS_TO, 'User', 'owner_id'),// on ny s dng lin kt thuc v,bn thn mt user nm trong bng user'requester' => array(self::BELONGS_TO, 'User', 'requester_id'),// on ny s dng lin kt thuc v,ngi yu cu nm trong bng useron ny c khi to ri v bn khng cn phi vo iu chnh li,Thay vo bn cn quay li file protected/views/issues/view.php lm nt s thay i

V y l kt qu: http://localhost/devyii/index.php?r=issue/view&id=1

III.1.28 S thay i cui cng vi navigationM protected/views/issue/view.php v thay i menu config nh sau:$this->menu=array(

array('label'=>'List Issues', 'url'=>

array('index', 'pid'=>$model->project->id)),

array('label'=>'Create Issue', 'url'=>

array('create', 'pid'=>$model->project->id)),

array('label'=>'Update Issue', 'url'=>

array('update', 'id'=>$model->id)),

array('label'=>'Delete Issue', 'url'=>'#', 'linkOptions'=>

array('submit'=>array('delete','id'=>$model->id),

'confirm'=>'Are you sure you want to delete this item?')),

array('label'=>'Manage Issues', 'url'=>

array('admin', 'pid'=>$model->project->id)),

);

Tip theo chng ta cn thay i IssueController::filters()public function filters()

{

return array(

'accessControl', // perform access control for CRUD operations

'projectContext + create index admin', //perform a check to

//ensure valid project context

);

}

Tip theo ta chnh li IssueControlller:actionIndex():public function actionIndex()

{

$dataProvider=new CActiveDataProvider('Issue', array(

'criteria'=>array(

'condition'=>'project_id=:projectId',

'params'=>array(':projectId'=>$this->_project->id),

),

));

$this->render('index',array('dataProvider'=>$dataProvider,));

}

Tip theo bn cn vo protected/views/issue/admin.phpS dng kt qu ca model class Issues::search() method c cung cp danh sch issues.Bn vo IssueController::actionAdmin():

public function actionAdmin()

{

$model=new Issue('search');

if(isset($_GET['Issue']))

$model->attributes=$_GET['Issue'];

$model->project_id = $this->_project->id;

$this->render('admin',array('model'=>$model));

}

Tip theo bn thay i trong Issues::search()public function search()

{

// Warning: Please modify the following code to remove attributes that

// should not be searched.

$criteria=new CDbCriteria;

$criteria->compare('id',$this->id);

$criteria->compare('name',$this->name,true);

$criteria->compare('description',$this->description,true);

$criteria->compare('type_id',$this->type_id);

$criteria->compare('status_id',$this->status_id);

$criteria->compare('owner_id',$this->owner_id);

$criteria->compare('requester_id',$this->requester_id);

$criteria->compare('create_time',$this->create_time,true);

$criteria->compare('create_user_id',$this->create_user_id);

$criteria->compare('update_time',$this->update_time,true);

$criteria->compare('update_user_id',$this->update_user_id);

$criteria->condition='project_id=:projectID';

$criteria->params=array(':projectID'=>$this->project_id);

return new CActiveDataProvider(get_class($this), array(

'criteria'=>$criteria,

));

} y chng ta va xa $criteria->compare() s dng project_id vi $criteria->condition() so snh vi project_id trong project context.vi nhng thay i ny danh sch issues thc s b chi phi bi projectChng 4: Qun l ngi dng v qu trnh xc thc(User Management and Authentication)

K hoch xa hnKhi chng ta s dng dng lnh yii to ra ng dng ny, n cho php chng ta ng nhp bi 2 account l demo demo v admin-admin ,chng ta c th thc hin li qu trnh xc thc t CRUD v ta c k hoch sau:

To controller class cho php:

1. To mi user

2. Lc danh sch user tn ti trong csdl

3. Cp nht/chnh sa bn ghi

4. Xa user tn ti

To view file v thc hin trnh by :

1. Hin th form cho php ngi dng to mi

2. Hin th danh sch user tn ti

3. Hin th form cho php chnh sa user

4. Thm hoc xa user

Chnh li qu trnh xc thc s dng database kim tra qu trnh loginIV.1 User CRUDTrc tin bn vo Gii : http://localhost/devyii/index.php?r=gii/default/indexChn Model Generated v in ging nh hnh sau:

Click Preview - > Generated.

Sau khi hon thnh bn vo protected/models/ kim tra file mi to bn s thy User.php

Tip theo bn vo Gii chn CRUD Generator , ti Model class : in vo : User , ti Controller ID in vo : User, sau chn preview -> generated.

Tip theo bn vo http://localhost/devyii/index.php?r=user kim tra bn thy 2 user c to sn ban u

Chng ta cng c th to mi user ngay by gi t link menu create user: http://localhost/devyii/index.php?r=user/createNu hin ti bn khng ng nhp bn s c router login s dng vi 2 ti khon l demo/demo v admin/admin.

IV.2 Thnh phn Behavior

Behavior trong Yii class c thc thi giao din ca Ibehavior, v phng thc ca n c th k tha t hm thnh phn bi vic kch hot component. L do chng ta s dng component ny bi v User, Project, Issue cng c cng cu trc, ta thay th hm behavior c sn v kch hot n t model class,n cho php chng ta thit lp cc trng d liu trong AR class .

Thc t trong th vin Zii, gi nh trong Yii framework tn ti behavior cho vic cp nht thi gian create_time v update_time. Behavior ny c tn CtimestampBehavior.

Bn vo protected/models/User.php thm hm sau:public function behaviors()

{

return array('CTimestampBehavior' => array(

'class' => 'zii.behaviors.CTimestampBehavior',

'createAttribute' => 'create_time',

'updateAttribute' => 'update_time',

'setUpdateOnCreate' => true,

),

);

}

y chng ta va kch hot th vin Zii CtimestampBehavior ti class User model. Chng ta c th nhn thy s khc bit ca 2 phn t create_time v update_time c cu hnh trong behavior thit lp thi gian cho mi bn ghi c to hoc cp nht.

Sau ny khi bn ng nhp vo user mi th bn s thy 2 phn t s c t cp nht: iu ny tht tuyt chng ta cn lp li n trong model class, tuy nhin chng ta c th thc hin k hoch khc tt hn na , l tin hnh s dng Active record (kch hot bn ghi) bi s kin beforeSave (trc khi lu), v thit lp nhng g cn thit cho trng d liu. v chng ta c th thc hin cc lnh kt ni vi AR model class.Bn s la chn k hoch ny tt hn cho ng dng Yii c a bn.

lm vic chng ta cn to mi AR model class, trc tin xa b hm behaviors() chng ta va to trong User.php model.Tip theo bn vo protected/models/ bn to file DevYiiActiveRecord.php vi ni dung sau:

V t form user: protected/views/user/_form.php ta xa thm phn t last_login_time

Tip theo vo model ca 3 class Issue, Project, Users trn xa cc phn t trn trong hm rules v hm attributeslabel v hm search.Tip theo ta vo model User.php :: rules() v thay i nh sau:public function rules()

{

return array(

array('email', 'required'),

array('email, username, password', 'length', 'max'=>255,

array('email, username', 'unique'),

array('email', 'email'),

// The following rule is used by search().

// Please remove those attributes that should not be searched.

array('id, email, username, password', 'safe','on'=>'search'),

);

}IV.3 Thm trng G li password

Chng ta khai bo trn u class User.php model trong protected/models/User.php:public $password_repeat;

Thm User::rules() dng sau vo mng array:array('password', 'compare', 'compareAttribute'=>'password_repeat'),array('password_repeat', 'safe'),

V thay i

array('email, username, password, password_repeat', 'required'),

Thm on sau vo protected/views/user/_form.php sau password field:

V y l kt qu:http://localhost/devyii/index.php?r=user/create

IV.4 Hash (Bm) mt khuLn thay i cui cng chng ta c th lm trc khi di chuyn ti vic to mi user l to hm bm cho mt khu ca ngi dng, khi chng ta nht n vo database.

Chng ta s thm logic vo User.php nh vic iu khin CactiveRecord cho php chng ta custom mc nh kch hot bn ghi , iu ny c ti vi phng thc afterValidate() sau khi xc thc cc trng d liu u vo hp l,

Vo model User.php protected/models/User.php thm on sau di class:

protected function afterValidate()

{

parent::afterValidate();

if(!$this->hasErrors())

$this->password = $this->hashPassword($this->password);

}

/**

* Generates the password hash.

* @param string password

* @return string hash

*/

public function hashPassword($password)

{

return md5($password);

}

Bn hy to mi ti khon tn admin, password admin v s thy kt qu sau: ( Bc ny m khng to th on sau khi phi vo h thng lun ^_^)http://localhost/devyii/index.php?r=user/view&id=3

IV.5 Xc thc User kt ni ti DatabaseNh chng ta bit, form ng nhp c bn ngi dng xc thc truy cp c to n gin bi lnh Yii khi to mi ng dng, Chng ta truy nhp vo website nh hai ti khon l demo/demo v admin/admin, cng vic ca chng ta by gi l chuyn ton b ti khon xc thc trong CSDL m bn va to vo qu trnh xc thc h thng Yii.Gii thiu Yii authentication model (Xc thc m hnh CSDL)Trung tm ti xc thc user ca Yii l mt thnh phn ng dng gi l user, n l mt i tng c thc thi t giao din IwebUser, class c bit ny c s dng bi vic thc thi CwebUser, thnh phn user ny l thng tin tt c nh danh user hin ti c trong ng dng. Thnh phn ny c cu hnh cho chng ta nh mt phn t ng trong h thng khi ng dng c to bi yii tool, cu hnh n bn vo protected/config/main.php v nhn on ny:'user'=>array(

// enable cookie-based authentication

'allowAutoLogin'=>true,

),Lc ny n c cu hnh nh mt thnh phn ng dng,vi tn user, chng ta c th truy cp bt k ni no trong ng dng bi vic s dng:

Yii::app()->user.

Yii t ng nh ngha thc th thc hin vic xc thc c bn, n c gi l identity class v n c th hin bi Iuseridentity interface, vai tr chnh ca class ny l xc thc v phn quyn user.

Bn m protected/components/UserIdentity.php y chnh l n v bn c th nhn s qua n :

You last logged in on .

Vo http://localhost/devyii/index.php?r=site/login ng nhp vi ti khon mi to admin/admin, on trc ai cha to th khi phi hc tip, i ng lun i.y l kt qu:

CHNG 5 : iu khin truy cp ngi dng

(UAC User Access Control)V.1 Cu hnh qun l truy cpVo protected/config/main.php v thm on sau vo mng component:

'components'=>array(

'authManager'=>array(

'class'=>'CDbAuthManager',

'connectionID'=>'db',

),

V.2 To bng csdl RBAC

Vo phpmyadmin v to ra cc bng sau vi cc query :

To bng auth_itemcreate table tbl_auth_item(name varchar(255) not null,type int(11) not null,description text,bizrule text,data text,primary key(`name`))Engine=InnoDB;To bng auth_item_child

create table tbl_auth_item_child(parent varchar(255) not null,child varchar(255) not null,PRIMARY KEY (`parent`,`child`))ENGINE=InnoDB;To kha ngoi tham chiu vi field name

alter table tbl_auth_item_child add constraint fk_auth_item_child_parent foreign key(parent) references tbl_auth_item(name) on update cascade on delete cascadealter table tbl_auth_item_child add constraint fk_auth_item_child_child foreign key(child) references tbl_auth_item(name) on update cascade on delete cascadeTo bng auth assignment

create table tbl_auth_assignment(itemname varchar(255) not null,userid int(11) not null,bizrule text,data text,primary key(itemname,userid)) engine=innodb;To kha ngoi lin kt bng vi field itemname

alter table tbl_auth_assignment add foreign key(itemname) references tbl_auth_item(name) on update cascade on delete cascade;To kha ngoi lin kt vi userid

alter table tbl_auth_assignment add constraint fk_auth_assignment_userid foreign key(userid) references tbl_user(id) on update cascade on delete cascade;Tip theo vo protected/config/main.php v sa li ni dung trong component array:'components'=>array(

'authManager'=>array(

'class'=>'CDbAuthManager',

'connectionID'=>'db',

'itemTable' =>'tbl_auth_item',

'itemChildTable' =>'tbl_auth_item_child',

'assignmentTable' =>'tbl_auth_assignment',

),

V.3 To biu nh danh RBACSau khi to cc bng csdl ri chng ta cn thm cc vai tr (roles) v phn quyn (permission).Chng ta s s dng API c cung cp bi authmanager component. By gi chng ta hy nhn xem qua nh ngha cc bng vi s sau:

y ta c th nhn thy cp cao nht chnh l bn thn chng ta (admin) vi vic to user, cp nht user, xa user, to project, cp nht project v xa project, n c phn quyn nh hng t c hai member (thnh vin) v reader(Ngi c)

.Thnh vin ch c php cp nht sa xa d liu ca bn thn v cc quyn li ca ngi c l xem thnh vin, c project, c issue.

Ngi c (anonymous) l ngi khch vng lai truy cp vo web h c php c thng tin user, c thng tin c a project v issue

V.4 Thc thi project AR method miTrc tin vo phpmyadmin thm ct mi cho tbl_project_user_assignment

alter table tbl_project_user_assignment add column role varchar(255) not nullVo protected/models/Project.php v thm vo hm sau:

public function assignUser($userId, $role)

{

$command = Yii::app()->db->createCommand();

$command->insert('tbl_project_user_assignment', array(

'role'=>$role,

'user_id'=>$userId,

'project_id'=>$this->id,

));

}

Thm hm xa User:public function removeUser($userId)

{

$command = Yii::app()->db->createCommand();

$command->delete(

'tbl_project_user_assignment',

'user_id=:userId AND project_id=:projectId',

array(':userId'=>$userId,':projectId'=>$this->id)

);

}V.5 Thm User ti Project1. Thm hm tnh (static) getUserRoleOptions() t Project AR tr v danh sch hp l vi role option s dng getRoles() method trong manager. Chng ta s cho user la chn dropdown

2. Thm hm mi gi l isUserInProject($user) t Project AR quyt nh user c lin quan ti project

Chng ta s dng rules validation thm user ti project

3. Thm form mi tn l ProjectUserForm k tha t CformModel to input form model. Thm vo form ny 3 phn t l $role,$project,$user.

4. Thm file mi trong protected/views/project gi l adduser.php hin th form mi to t user ti project.

5. Thm controller action method mi tn actionAdduser() t ProjectController.php v iu chnh c accessRules() phng thc truy cp nh danh t user.

By gi chng ta bt tay vo cng vic

V.5.1 Chnh li Project model class

T Project Model chng ta to thm 2 hm mi:/** Returns an array of available roles in which a user can be placed

*when being added to a project

*/

public static function getUserRoleOptions()

{

return CHtml::listData(Yii::app()->authManager->getRoles(), 'name',

'name');

}

/*

* Determines whether or not a user is already part of a project

*/

public function isUserInProject($user)

{

$sql = "SELECT user_id FROM tbl_project_user_assignment WHERE project_id=:projectId AND user_id=:userId";

$command = Yii::app()->db->createCommand($sql);

$command->bindValue(":projectId", $this->id, PDO::PARAM_INT);

$command->bindValue(":userId", $user->id, PDO::PARAM_INT);

return $command->execute()==1;

}

V.5.2 Thm model Form classVo protected/modes to mi file tn ProjectUserForm.php vi ni dung sau:array(

'urlFormat'=>'path',

),

Mc nh th n nm trong array component v b dng comment /* -- */ b kch hot n.

Cng vic ca bn l b 2 dng comment kch hot urlManager.

'urlManager'=>array(

'urlFormat'=>'path',

'rules'=>array(

'/'=>'/view',

'//'=>'/',

'/'=>'/',

),

),

By gi th bn c th vo c url : http://localhost/devyii/index.php/comment/feed mt cch d dng, v t nay khi vo cc cng c bn vui lng b on r= i khi vo Gii v d:http://localhost/devyii/index.php/gii/default/indexHoc vo project : http://localhost/devyii/index.php/project . b nt c index.php bn cn phi nh ngha li Url v thit lp controller/action tr n url nh danh , iu ny c vit trong Yii development Cookbook ebook ti dch ri, bn vui lng vo xem li nh

VII.3.2 Cu hnh li Routing rules (Quy tc routes)Router l g : L mt gi url tr v m trnh duyt yu cu h thng x l, n cha c phn s v phn ch, v d nh cc bin $_GET, $_POST, hoc n gin l cc tiu ni dung ca mt bi no m trnh duyt yu cu h thng tr li vi gi , thc hin cng vic ny Yii s dng Url manager nh ngha cc khai bo truy nhp router quyt nh xem controller no v action no c thc hin .

Vi nhng quy tc URL, thit lp CurlManager file s tr v cc thuc tnh quy tc theo mng array vi nh dng pattern=>route.

V y l v d qua v mt quy tc: Thm on sau vo urlManager://khai bo ng dn issue tr v controller/action (issue/index)//khai bo ng dn chi tit issue theo dng issues/id (dng s) tr v (issue/view).

'urlManager'=>array(

'urlFormat'=>'path',

'rules'=>array(

'issuehello'=>'issue/index',

'issue//*'=>'issue/view',

),

)Vi khai bo issuehello bn c th vo trnh duyt xem kt qu:http://localhost/devyii/index.php/issuehello n nhn ng khng ^_^. ng thi vi cch ny bn c th vo c http://localhost/devyii/index.php/issue/4 m khng cn phi g http://localhost/devyii/index.php/issue/view/4 mt ng dn rt xu.

Tip theo nu chng ta mun c ng dn nh sau: http://localhost/devyii/index.php/commentFeed.xml

Tht n gin ta vo url Manager khai bo nh sau:'urlManager'=>array(

'urlFormat'=>'path',

'rules'=>array( 'commentfeed'=>array('comment/feed',

'urlSuffix'=>'.xml', 'caseSensitive'=>false),

),

),

Trong commentfeed l url alias v urlsuffix l hu t sau url alias , caseSensitive chnh l trng hp u tin chn router y l mc nh (k u tin) v bn vo trnh duyt thng thc thnh qu.

http://localhost/devyii/index.php/commentfeed.xml

VII.3.3 Loi b kch bn index.php t URLBy gi chng ta s xa thnh phn index.php trc url, iu ny cn lm theo 2 bc:

1. Chnh li webserver cu hnh router tt c cc request s khng x l file tn ti hoc ng dn lin quan ti index.php

2. Thit lp url manager component v chn thuc tnh: showScriptName l false.

Khi chng ta s dng Apache HTTP server chng ta c th thc hin giai on u tin vi file .htaccess trong th mc gc ca ng dng v chng ta to file .htaccess nh sau:

# Turning on the rewrite engine is necessary for the following rules

#and features.

# FollowSymLinks must be enabled for this to work.

Options +FollowSymlinks

RewriteEngine On

# Unless an explicit file or directory exists, redirect all request to

#sssYii entry script

RewriteCond %{REQUEST_FILENAME} !-f

RewriteCond %{REQUEST_FILENAME} !-d

RewriteRule . index.php

By gi chng ta vo http://localhost/devyii/commentfeed.xml ^_^!

http://localhost/devyii/project ^_^ c p ln hn khng ?

Bc th 2 n gin ri chnh li urlManager vi dng sau:

'urlManager'=>array(

'urlFormat'=>'path',

'rules'=>array(

'commentfeed'=>array('comment/feed', 'urlSuffix'=>'.xml',

'caseSensitive'=>false),

),//tt hn index.php'showScriptName'=>false,

),

qu, th l li c framework na xi ri hehei vi nhng url iu khin vi ch s ID nh Project ID, chng ta c th lm theo cch sau:'urlManager'=>array(

'urlFormat'=>'path',

'rules'=>array(

'/commentfeed'=>array('comment/feed',

'urlSuffix'=>'.xml', 'caseSensitive'=>false),

'commentfeed'=>array('comment/feed', 'urlSuffix'=>'.xml',

'caseSensitive'=>false),

),

'showScriptName'=>false,

),

Vo trnh duyt : http://localhost/devyii/2/commentfeed.xml xem kt qu:

VII.3.4 Thm Feed LinksBy gi chng ta s to url feed cu trc thn thin hn cho ngi dng,chng ta cn thm subscribe feed,vo projectController::actionIndex()Chnh li nh sau:

public function actionIndex()

{

$dataProvider=new CActiveDataProvider('Project');

Yii::app()->clientScript->registerLinkTag(

'alternate',

'application/rss+xml',

$this->createUrl('comment/feed'));

$this->render('index',array(

'dataProvider'=>$dataProvider,

));

}

Bn s thy on sau u th head:

VII.3.5 Gi mail ti user vi Zend_Mail()Chng ta s lm v d thc hin vic gi email ti user bng cch s dng Zend_mail ti CommentController.php ::actionMail()

Bn vo protected/controller/CommentController thm on sau vo u class:

require_once('Zend/Mail.php');

require_once('Zend/Mail/Transport/Smtp.php');

require_once('Zend/Mail/Protocol/Smtp/Auth/Login.php');Ti function accessRules()

{

array('allow', // allow all users to perform 'index' and 'view' actions

'actions'=>array('index','view','feed','mail'),

'users'=>array('*'),

),

}

Xy dng hm mail:

public function actionMail()

{

$content='i love you';

$addto='[email protected]';

$subject='Dear love!';

$emailfrom='[email protected]';

$tr = new Zend_Mail_Transport_Smtp ('smtp.gmail.com', array('auth' => 'login', 'username' => '[email protected]', 'password' => 'password user', 'ssl' => 'ssl', 'port' => 465 ));

Zend_Mail::setDefaultTransport($tr);

$mail = new Zend_Mail('UTF-8');

$mail->setBodyHtml(($content));

$mail->addTo($addto);

$mail->setSubject($subject);

$mail->setFrom ($emailfrom);

$mail->send ();

}Vo trnh duyt xem thnh qu : http://localhost/devyii/comment/mailDo khng c host nn nu bn g vo s bo li khng th m gi trn v user name v password khng chnh xc, v bn phi c host thc trn mng mi c th gi socket.

Tuy nhin n giai on ny l bn hon ton c th gi mail online c khi bn chy trn website thc.

VII.3.6 To File PDF Vi Zend_PDFBn vo th mc gc devyii to mt folder c tn pdf ngang hng vi protected cha file to pdf

Bn vo protected/controller/CommentController.php thm on sau vo u class:

require_once('Zend/Pdf.php');

require_once('Zend/Pdf/Page.php');

require_once('Zend/Pdf/Font.php');Sa li function accessRules() thm vo actionPdf:

public function accessRules()

{

return array(

array('allow', // allow all users to perform 'index' and 'view' actions

'actions'=>array('index','view','feed','mail','pdf'),

'users'=>array('*'),

),To CommentController:: actionPdf():

public function actionPdf()

{

$pdf = new Zend_Pdf();

$page = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);

// define font resource

$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_COURIER);

// thiet lap font , kich co font

// viet noi dung pdf

$page->setFont($font, 24) ->drawText('I miss you,', 72, 720)

->drawText('Because I love You', 72, 620);

$pdf->pages[] = $page;

// luu file vao folder pdf

$pdf->save('pdf/miss.pdf');

}Vo trnh duyt g : http://localhost/devyii/comment/pdfVo folder pdf mi to s thy mt file tn miss.pdf v m ra s c hnh sau:

Vi cch ny bn c th to ra mt file pdf v to ng link ti file user c th download c mt s trang theo kiu ha n thanh ton.CHNG 8 : LM NG DNG P HNK HOCH To theme mi cho ng dng bng vic to layout mi,CSS v folder v cc ti sn khc cn c cung cp trong ng dng vi thit k frontend mi.

S dng tiu chun ngn ng vng m