yii framework - design pattern and database and form

Upload: toan-nguyen-minh

Post on 17-Oct-2015

289 views

Category:

Documents


0 download

TRANSCRIPT

  • Yii Framework

    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

    Best MVC Practices .......................................................................................................... 6

    Model ..................................................................................................................................................... 6

    View ....................................................................................................................................................... 6

    Controller ............................................................................................................................................... 7

    CakePHP vs Yii ................................................................................................................. 8

    Yii Basic Workflow ........................................................................................................... 9

    Yii Components ............................................................................................................... 11

    1. Application ....................................................................................................................................... 11

    2. Controller ......................................................................................................................................... 12

    Action ............................................................................................................................................... 12

    Filter ................................................................................................................................................. 15

    3. Component ....................................................................................................................................... 17

    Event ................................................................................................................................................ 17

    4. Model ............................................................................................................................................... 17

    Working with model......................................................................................................................... 18

    5. View ................................................................................................................................................. 19

    6. Widget .............................................................................................................................................. 20

    Working with Database ................................................................................................... 21

    1. Data Access Objects (DAO) ............................................................................................................ 21

    Establishing Database Connection (Thit lp kt ni CSDL) .......................................................... 21

    Executing SQL Statements (Thc thi cu lnh truy vn SQL) ........................................................ 22

    Fetching Query Results (Ly kt qu truy vn) ............................................................................... 22

    Using Transactions (S dng transaction) ....................................................................................... 23

    Binding Parameters .......................................................................................................................... 23

  • JustLook

    Yii Framework Trang 3/34

    2. Query Builder ................................................................................................................................... 24

    Building Data Retrieval Queries ...................................................................................................... 24

    Building Data Manipulation Queries ............................................................................................... 25

    Building Schema Manipulation Queries .......................................................................................... 26

    3. Active Record ................................................................................................................................... 26

    Establishing DB Connection ............................................................................................................ 27

    Defining AR Class ........................................................................................................................... 27

    Creating Record................................................................................................................................ 28

    Reading Record ................................................................................................................................ 28

    Using Transaction with AR .............................................................................................................. 28

    Relational Active Record ................................................................................................................. 29

    Extensions Library ........................................................................................................... 31

    Classified extension ............................................................................................................................. 31

    Using extension .................................................................................................................................... 31

    Creating extension ................................................................................................................................ 32

  • JustLook

    Yii Framework Trang 4/34

    Overview MVC

    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.

    Controller

    View 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

    Best MVC Practices

    Mt m hnh MVC tt th cn phi thc hin ng cc nguyn tc sau:

    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

    o Truy cp trc tip n $_GET, $_POST, hoc cc bin tng t khc i

    din cho request ca ngi dng

    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

    CakePHP Framework Yii Framework

    CakePHP c nh gi l framework c m hnh MVC chun nht, c bn nht. Cc

    thnh phn ca CakePHP hon ton tng ng vi m hnh MVC.

    Yii cng s dng m hnh MVC trong thit k. Ngoi cc thnh phn c bn, Yii b

    sung thm mt s thnh phn (Application, App Components, Widget, ). Cc thnh

    phn ny s c team gii thiu chi tit trong cc phn sau.

    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.

    Model View

    Controller

    Widget

    Application

    Index.php App component

  • JustLook

    Yii Framework Trang 9/34

    Yii Basic Workflow

    V c bn, cch lm vic ca Yii c thc hin qua cc bc sau:

    1. Yu cu (request) ca ngi dng c trnh duyt gi cho Web server. Web

    server chuyn tip request cho index.php x l. Index.php c chc nng to mt

    thc th Application v thc thi n

    2. Application to ra cc App Component (App Component l cc thnh phn ca

    ng dng, vd: UrlManager, HttpRequest)

    3. App Component gi cc thnh phn ca mnh cho Application qun l

    4. Application xc nh cc controller v action t request v gi chng cho

    UrlManager qun l. Tip n Application tin hnh thc thi controller

    5. Controller c th to ra cc model x l d liu

    6. Model gi d liu cho Controller

    7. Controller gi cc bin, cc th hin ca model cho View

    8. View to ra cc Widget

    9. View thc hin trnh by trang web

    Model View

    Controller

    Widget

    Application Index.php App component2

    3 1 4

    5

    6 7

    9

    8

  • 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

    Controller

    Widget

    Application Index.php App components

  • JustLook

    Yii Framework Trang 11/34

    Yii Components

    Cc thnh phn chnh ca Yii bao gm:

    1. Application

    2. Controller

    3. Component

    4. Model

    5. View

    6. 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

    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

    Mt s phng thc tng ng gia CakePHP v Yii

    class ContactAction extends CAction { public function run() { // place the action logic here } }

    class SiteController extends CController

    { // ... public function actions() { return array(

    'contact'=>'application.controllers.site.ContactAction',

    ); } // ... }

  • JustLook

    Yii Framework Trang 14/34

    CakePHP Framework Yii Framework

    CakePHP Framework Yii Framework

    class SiteController extends CController

    { public function beforeAction() { // ... } // ... public function afterAction() { // ... }

    class SiteController extends AppController

    { public function beforeFilter() { // ... } // ... public function afterFilter() { // ... }

    class SiteController extends CController

    { public function beforeRender() { // ... } // ... public function afterRender() { // ... } }

    class SiteController extends AppController

    { public function beforeRender() { // ... } // ... public function afterRender() { // ... } }

  • 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:

    class PostController extends CController { public function filters() { return array ( accessControl , ); } public function filterAccessControl($filterChain) { //...pre-filtering code... $filterChain->run(); //...post-filtering code... }

    }

  • 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:

    class PostController extends CController { public function filters() { return array ( checkAdmin + update, delete , checkLogin - view , ); } public function filterCheckAdmin($filterChain) { if (is Admin) { $filterChain->run(); } else { echo Access denied; } }

    }

  • JustLook

    Yii Framework Trang 17/34

    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.

    // file: protected/controllers/PostContrller.php

    class PostController extends CController { // public function filters() { return array ( application.filters.PerformanceFilter, ); } // }

    // file: protected/filters/PerformanceFilter.php

    class PerformanceFilter extends CFilter { protected function preFilter($filterChain) { // logic being applied before the action is executed return true; // false if the action should not be executed } protected function postFilter($filterChain) { // logic being applied after the action is executed }

    }

  • 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:

    class LoginForm extends CFormModel { public $username; public $password; public function rules() { return array( array('username, password', 'required'), array('password', 'authenticate'), ); } public function authenticate($attribute,$params) { }

  • 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

    o renderDynamic(): Renders dynamic content returned by the specified

    callback

    o renderDynamicInternal(): This method is internally used

    o renderFile() or renderInternal(): Renders a view file

    o renderPartial(): Renders a view

    o renderText(): Renders a static text string

    Protected methods

    o beforeRender() / afterRender()

    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

    Working with Database

    1. Data Access Objects (DAO)

    2. Query Builder

    3. Active Record

    1. Data Access Objects (DAO)

    DAO cung cp mt API chung truy cp d liu c lu tr trong h thng qun l

    CSDL khc nhau.

    Yii DAO ch yu bao gm 4 lp (class) sau:

    CDbConnection: i din cho mt kt ni n CSDL

    CDbCommand: i din cho mt cu lnh truy vn SQL thc hin trn CSDL

    CDbDataReader: i din cho mt tp hp cc hng (row) t kt qu cu truy

    vn

    CdbTransaction: i din cho mt giao dch (transaction) vi DB

    Establishing Database Connection (Thit lp kt ni CSDL)

    thit lp kt ni vi CSDL ta to i tng CdbConnection vi cu trc nh sau:

    $connection=new CDbConnection($dsn,$username,$password);

    // establish connection. You may try...catch possible exceptions

    $connection->active=true;

    ......

    $connection->active=false; // close connection

    $dsn ty thuc vo trnh iu khin CSDL PDO s dng. Di y l danh sch cc

    DSN thng c s dng:

    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

    $username v $password l cc thng tin kt ni n CSDL.

  • JustLook

    Yii Framework Trang 22/34

    Ta c th thit lp kt ni CSDL trong file config (protected/config/main.php) nh sau:

    array(

    ......

    'components'=>array(

    ......

    'db'=>array(

    'class'=>'CDbConnection',

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

    'username'=>'root',

    'password'=>'password',

    'emulatePrepare'=>true, // needed by some MySQL installations

    ),

    ),

    )

    Vi cch cu hnh nh trn, truy cp n DB connection ta s dng Yii::app()->db.

    Executing SQL Statements (Thc thi cu lnh truy vn SQL)

    Khi mt kt ni CSDL c thit lp, cc cu lnh truy SQL c th c thc hin

    bng cch s dng CDbCommand. to ra CDbCommand ta s dng phng thc

    CDbConnection::createCommand(). Xem v d:

    $rowCount=$command->execute(); // execute the non-query SQL

    $dataReader=$command->query(); // execute a query SQL

    $rows=$command->queryAll(); // query and return all rows of result

    $row=$command->queryRow(); // query and return the first row of result

    $column=$command->queryColumn(); // query and return the first column of result

    $value=$command->queryScalar(); // query and return the first field in the first

    row

    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();

    Using Transactions (S dng transaction)

    s dng transaction (giao dch) ta s dng cu trc nh sau:

    $transaction=$connection->beginTransaction();

    try

    {

    $connection->createCommand($sql1)->execute();

    $connection->createCommand($sql2)->execute();

    //.... other SQL executions

    $transaction->commit();

    }

    catch(Exception $e) // an exception is raised if a query fails

    {

    $transaction->rollBack();

    }

    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();

    Vic s dng Query Builder c cc li ch sau:

    Cho php xy dng cc cu lnh truy vn phc tp (nhng d vit hn)

    T ng bc (quote) cc tn table bng cch thm cc k t (`) vo tn table

    nhm trnh xung t vi cc t kha ca SQL v cc k t c bit

    T ng bc cc gi tr tham s v s dng cc tham s rng buc (parameter

    binding) khi c th, gim nguy c b tn cng bng SQL Injection

    n gin ha vic chuyn i sang cc nn tng DB khc nhau

    Trc khi s dng Query Builder, ta kt ni n CSDL bng cch s dng

    CDbCommand nh DAO.

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

    Building Data Retrieval Queries

    Cc phng thc lin quan n vic truy vn CSDL:

    select(): specifies the SELECT part of the query

    selectDistinct(): specifies the SELECT part of the query and turns on the

    DISTINCT flag

    from(): specifies the FROM part of the query

  • JustLook

    Yii Framework Trang 25/34

    where(): specifies the WHERE part of the query

    join(): appends an inner join query fragment

    group(): specifies the GROUP BY part of the query

    having(): specifies the HAVING part of the query

    order(): specifies the ORDER BY part of the query

    limit(): specifies the LIMIT part of the query

    offset(): specifies the OFFSET part of the query

    union(): appends a UNION query fragment

    $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();

    Building Data Manipulation Queries

    s dng cc thao tc thm, sa, xa d liu Yii Query Builder cung cp cc phng

    thc sau:

    insert(): thm mt hng (row) vo 1 bng (table)

    update(): trong mt bng

    delete(): xa d liu t mt bng

    Xem cc v d sau:

    // build and execute the following SQL:

    // INSERT INTO `tbl_user` (`name`, `email`) VALUES (:name, :email)

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

    'name'=>'Tester',

    'email'=>'[email protected]',

    ));

    // build and execute the following SQL:

    // UPDATE `tbl_user` SET `name`=:name WHERE id=:id

    $command->update('tbl_user', array(

  • JustLook

    Yii Framework Trang 26/34

    'name'=>'Tester',

    ), 'id=:id', array(':id'=>1));

    // build and execute the following SQL:

    // DELETE FROM `tbl_user` WHERE id=:id

    $command->delete('tbl_user', 'id=:id', array(':id'=>1));

    Building Schema Manipulation Queries

    thao tc trn lt CSDL ta s dng cc phng thc sau:

    createTable(): to mt bng (table)

    renameTable(): i tn bng

    dropTable(): xa bng

    truncateTable(): truncates bng

    addColumn(): thm ct (column) cho bng

    renameColumn(): i tn ct

    alterColumn(): s ct

    dropColumn(): xa ct

    createIndex(): to index

    dropIndex(): xa index

    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 n CSDL, ta thit lp cu hnh trong file

    protected/config/main.php

    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';

    }

    }

    Theo mc nh, tn ca lp AR ging tn ca bng (table). S dng ghi (override)

    phng thc tableName() thay i tn bng nu cn.

    Nu bng c kha chnh ta s dng phng thc primaryKey() khai bo n

    public function primaryKey()

    {

    return 'id';

    // For composite primary key, return an array like the following

    // return array('pk1', 'pk2');

  • 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);

    Using Transaction with AR

    $model=Post::model();

    $transaction=$model->dbConnection->beginTransaction();

    try

    {

    // find and save are two steps which may be intervened by another request

    // we therefore use a transaction to ensure consistency and integrity

    $post=$model->findByPk(10);

    $post->title='new post title';

    $post->save();

    $transaction->commit();

    }

    catch(Exception $e)

    {

  • JustLook

    Yii Framework Trang 29/34

    $transaction->rollBack();

    }

    Relational Active Record

    C 4 loi relationships:

    BELONGS_TO: nu quan h gia bng A v B l one-to-many

    HAS_MANY: nu quan h gia bng A v B l one-to-many

    HAS_ONE: nu quan h gia bng A v B l many-to-one

    MANY_MANY: nu quan h gia bng A v B l many-to-many

    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)'),

    );

  • 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

    Vi v d trn, ta c 1 extension ContactAction (extension contact) c cha trong th

    class ContactAction extends CAction { public function run() { // place the action logic here } }

    class SiteController extends CController { // ... public function actions() { return array( 'contact'=>ext.action.ContactAction', ); } // ... }

  • JustLook

    Yii Framework Trang 32/34

    mc protected/extensions/action. Ti controller Site ta s dng action Contact bng

    cch khai bo n trong phng thc actions().

    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);

    }

    }

    Vi v d trn, ta to mt extension validator c tn l MyValidator. Mt extenstion

    validator th cn phi c mt phng thc l validateAttribute.

    class ContactAction extends CAction

    {

    protected function run()

    {

    // ...place the action logic here...

    }

    }

  • JustLook

    Yii Framework Trang 33/34

    V d trn cho thy mt extension action th cn phi c mt phng thc l run.

    bit cu trc class mi loi extension, bn c th truy cp vo trang ch ca Yii

    (http://www.yiiframework.com/doc/guide/1.1/en/extension.create).