1. Giới thiệu về YII
Framework 1
Nguyễn Như Tuấn – Web developer
Contact: tuanquynh0508@gmail.com – +84 0903258221
2. Nội dung
1. Cài đặt Yii
2. Sử dụng Gii tạo Model, CRUD, Controller, Action, View
3. Routter
4. Active Record, Query Database, Validate, Form
5. Tạo và sử dụng Layout
6. Custom Login
7. Tạo và sử dụng Module, Partial, Custom Widget, Custom Validate
8. Khai báo Custom Component
9. Internationalization – i18n
10. Override base core
11. Sử dụng Script Packet
12. Tài liệu tham khảo
3. 1. Cài đặt Yii
Vào web site:
http://www.yiiframework.com/download/
Download yii-1.1.15.022a51.tar.gz hoặc bản zip file
Giải nén và đổi tên vào thư mục webroot (ví dụ
D:wwwyii1)
Tạo thư mục D:wwwyii1 để chứa các app
4. 1. Cài đặt Yii…tiếp
Tạo dự án:
Vào thư mục D:wwwyii1framework
Giữ shift + Right Mouse Click, chọn Open command
window here
Gõ: yiic webapp D:wwwyii1appspro1
Chọn Yes
5. 1. Cài đặt Yii…tiếp
Cấu hình Apache
#Yii Training
<VirtualHost *:80>
ServerAdmin tuanquynh0508@gmail.com
DocumentRoot "D:wwwyii1appspro1"
ServerName pro1
</VirtualHost>
6. 2. Sử dụng Gii tạo Model, CRUD,
Controller, Action, View
Cấu hình Database
Vào config/main.php comment phần db sqlite lại, và mở
comment phần mysql ra. Sửa đổi lại thông tin.
Cấu hình Gii
Trong config/main.php, mở comment module gii ra
Đổi password thành 1
Trên đường link gõ http://localhost:8080?r=gii
Hướng dẫn Gii tạo Module và CRUD (thực hành)
7. 3. Active Record, Query
Database, Validate, Form
Một số hàm quan
trọng:
afterConstruct()
afterDelete()
afterFind()
afterSave()
afterValidate()
beforeDelete()
beforeFind()
beforeSave()
beforeValidate()
Giới thiệu về Active
Record:
9. Các thao tác với Active
Record
Các thao tác với Active Record:
Insert:
$model=new Example;
$model->title = "Example 1";
$model->create_time=new
CDbExpression('NOW()');
// $post->create_time='NOW()'; will not
work because // 'NOW()' will be treated
as a string
$model->save();
10. Update Active Record
Update:
$post=Post::model()->findByPk(10);
$post->title='new post title';
$post->save();
// save the change to database
//From POST
$post->attributes=$_POST['Post'];
$post->save();
11. Update Active Record
Ngoài ra Yii còn cung cấp thêm các hàm Update khác:
// update the rows matching the specified condition
Post::model()-
>updateAll($attributes,$condition,$params);
// update the rows matching the specified condition
and primary key(s)
Post::model()-
>updateByPk($pk,$attributes,$condition,$params);
// update counter columns in the rows satisfying the
specified conditions
Post::model()-
>updateCounters($counters,$condition,$params);
13. Delete Active Record
Ngoài ra Yii còn cung cấp thêm các hàm Delete khác:
// delete the rows matching the
specified condition
Post::model()-
>deleteAll($condition,$params);
// delete the rows matching the
specified condition and primary
key(s)
Post::model()-
>deleteByPk($pk,$condition,$params);
14. Query Database
Query Database, có hai loại Query là Query trả về một ActiveRecord và Query trả về Object
Record.
Query trả về Active Record:
// 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);
15. Query trả về Object Record
// find all rows satisfying the specified condition
$posts=Post::model()->findAll($condition,$params);
// find all rows with the specified primary keys
$posts=Post::model()-
>findAllByPk($postIDs,$condition,$params);
// find all rows with the specified attribute values
$posts=Post::model()-
>findAllByAttributes($attributes,$condition,$params);
// find all rows using the specified SQL statement
$posts=Post::model()->findAllBySql($sql,$params);
16. Query trả về Object Record
// find all rows satisfying the specified condition
$posts=Post::model()->findAll($condition,$params);
// find all rows with the specified primary keys
$posts=Post::model()-
>findAllByPk($postIDs,$condition,$params);
// find all rows with the specified attribute values
$posts=Post::model()-
>findAllByAttributes($attributes,$condition,$params);
// find all rows using the specified SQL statement
$posts=Post::model()->findAllBySql($sql,$params);
17. Đối tượng CDbCriteria
Truy vấn thường
$list1 =
Example::model()-
>findAll(array(
'condition' =>
'is_public=:is_publi
c', 'params' =>
array( ':is_public' =>
1, ),
));
Sử dụng CDbCriteria
$criteria = new
CDbCriteria();
$criteria->condition =
"is_public=:is_public";
$criteria->params =
array(': is_public' =>
1);
$list1 =
Example::model()-
>findAll($criteria);
18. Sử dụng truy vấn bằng
createCommand
Khởi tạo:
Sử dụng đối tượng kết nối mặc định
$command = Yii::app()->db;
Sử dụng đối tượng kết nối của ActiveRecord
$command = Example::model()-
>getDbConnection();
19. Sử dụng truy vấn bằng
createCommand
//Example 1
$list2 = Example::model()->getDbConnection()
->createCommand()
->setFetchMode(PDO::FETCH_OBJ)
->select('*')
->from('tbl_example')
->where('is_public = :is_public',
array(':is_public' => 1))
->queryRow();
20. Sử dụng truy vấn bằng
createCommand
//Example 2
$list2 = Example::model()->getDbConnection()
->createCommand()
->setFetchMode(PDO::FETCH_OBJ)
->select('*')
->from('tbl_example')
->where('is_public = :is_public',
array(':is_public' => 1))
->queryAll();
21. Sử dụng truy vấn bằng
createCommand
//Example 3
$lastId = Example::model()->getDbConnection()
->createCommand()
->select('IFNULL(MAX(id),0) as max')
->from('tbl_example')
->where('is_public = :is_public',
array(':is_public' => 1))
->queryScalar();
22. Sử dụng truy vấn bằng
createCommand
//Example 4
$sql = 'SELECT * FROM ur_tbl t WHERE t.email_id =
'. $id;
$email = Yii::app()->db->createCommand($sql)-
>queryAll();
//Example 5
$list= Yii::app()->db
->createCommand('select * from post where
category=:category')
->bindValue(':category',$category)
->queryAll();
23. Sử dụng truy vấn bằng
createCommand
//Example 6
$list= Yii::app()->db
->createCommand('select * from post where
category=:category and status=:status')
->bindValues(array(':category'=>$category,
':status'=>$status))
->queryAll();
27. 4. Routter
htaccess
Options -Indexes +FollowSymLinks -Multiviews
IndexIgnore */*
RewriteEngine On
RewriteBase /pro1/
# if a directory or a file exists, use it
directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# otherwise forward it to index.php
RewriteRule . index.php
28. 5. Custom Login
Yii framework cung cấp sẵn cơ chế Authentication thông
qua đối tượng CUserIdentity
Sử dụng ba hàm thường dung là:
Yii::app()->user->login($this-
>_identity,$duration);
Yii::app()->user->logout();
authenticate();
29. 5. Custom Login
Tạo ra Custom Form Login với các trường cơ bản là
username và password
Sử dụng Active Record Staff để truy vấn database về cơ
sơ dữ liệu người dung
Override lại hàm authenticate của CUserIdentity để truy
vấn theo dữ liệu người dùng từ database
Bổ xung thêm các thông tin cần lấy ra từ CUserIdentity
nếu thấy cần thiết
Xem code mẫu đi kèm
30. 6. Tạo và sử dụng Custom
Layout
Trong thư mục views/layouts tạo thêm một layout mới
là template_free.php
Đưa các HTML cần thiết vào
Để sử dụng layout cho một Action nào đó, thì chỉ cần gán
như sau:
$this->layout = "//layouts/template_free";
Còn khai báo layout sử dụng cho toàn bộ một controller
thì gán là:
public $layout = "//layouts/template_free";
31. 7. Tạo và sử dụng Module,
Partial, Custom Widget,
Custom Validate
32. Module
Module là một mô hình MVC thu nhỏ của Framework
Trong Module có đầy đủ các thư mục như là components,
controllers, views, models…
Module được tạo ra một cách dễ dàng thông qua công cụ
gii của yii
33. Partial
Partial là một view và là một thành phần HTML tĩnh,
được include vào trong page.
Được tạo ra để sử dụng nhiều lần ở nhiều page khác
nhau
Partial cũng có thể truyền tham số và gọi lại trong html
của nó
Ví dụ một partial điển hình
35. Widget
Widget là một thành phần gần giống với controller
Widget có đầy đủ phần xử lý logic và view
Cũng giống như partial, widget được tạo ra và sử dụng
nhiều lần trên view thông qua việc gọi và truyền tham số
Widget có thể sử dụng các đối tượng Activerecord để lấy
thông tin từ database rồi trả về cho view của nó
Sau đây là một ví dụ về Widget
37. Custom validate
Yii framework cung cấp đầy đủ các validate cơ bản nhất
(tham khảo tại
http://www.yiiframework.com/wiki/56/reference-
model-rules-validation/)
Nhưng đôi khi chúng ta cũng muốn tự tạo ra một
validate riêng của mình cho những nghiệp vụ đòi hỏi
cách kiểm tra dữ liệu riêng.
Có hai cách để thực hiện việc này: Sử dụng validate
trong nội tại class Activerecord hoặc class CFormModel
Cách thư 2 là tạo ra một Custom validate riêng, để có
thể tái sử dụng ở nhiều Form khác nhau.
38. Custom validate
Khai báo custome validate trong class AC hoặc CF
<?php
class HelloForm extends CFormModel
{
public $fullname;
public $message;
public $age;
public $sex;
public function rules()
{
return array(
array('fullname, message', 'required'),
array('fullname', 'length', 'max'=>25),
array('age', 'numerical', 'integerOnly'=>true),
array('age', 'checkAge18Plus', 'min'=>18, 'message' => 'Chưa đủ tuổi'),
array('sex', 'application.components.validators.checkSex', 'allowEmpty'=>false),
);
}
39. Custom validate
protectedcomponentsvalidatorscheckSex.php
<?php
class checkSex extends CValidator
{
public $message = '';
public $allowEmpty = true;
protected function validateAttribute($object,$attribute)
{
$value = intval($object->$attribute);
//Bỏ qua nếu chấp nhận rỗng
if($this->allowEmpty && empty($value))
return;
$message=!empty($this->message)?$this->message:"Không chơi với GAY hoặc
40. Custom validate
Sử dụng trong form
array('sex', 'application.components.validators.checkSex',
'allowEmpty'=>false),
41. 8. Khai báo Custom
Component
Custom component là một class xử lý một tác vụ nào đó,
được sử dụng và gọi ở nhiều nơi.
Ta cũng có thể tạo ra các class, song khi sử dụng cần
new ra đối tượng rồi mới dùng được
Hoặc có thể tạo ra class và các function static để gọi
Có cách khác đơn giản hơn, là đăng ký class đó với Yii,
và gọi ra trực tiếp các functions của class đó.
42. 8. Khai báo Custom
Component
protectedcomponentsUtility.php
class Utility extends CComponent {
public $name = 'xxxx';
public function init() {}
48. 11. Sử dụng Script Packet
Việc tổ chức client javascript và css có thể add thẳng
vào view, các page khác nhau cùng sử dụng một thư viện
sẽ gọi lại các js và css này.
Mô hình chung tạo ra rất nhiều đoạn include js và css vào
các page, khi có thay đổi rất khó khăn.
Có thể sử dụng Partial và Widget, song Yii cung cấp thêm
một cách định nghĩa ra các gói Packet Script và gọi
chúng trong View tốt hơn.
49. 11. Sử dụng Script Packet
Quản lý việc này chính là đối tượng clientScript, đối tượng
clientScript hoạt động theo cơ chế:
Các widget hoặc component đăng ký với Yii các gói thư viện
Js và Css. Khi App chạy, các gói thư viện này sẽ được copy
vào thư mục assets với tên thư mục là tên mã của các gói
do Yii tự sinh name.
Wiget và Component sẽ lấy lại đường link thông qua việc gọi
lại các gói này.
Các gói thư viện này cũng được khai báo và sử dụng lại
trong view một cách chuyên nghiệp và hiệu quả.
Nó cũng làm giảm việc gọi trồng chéo các gói thư viện, tức
là nếu đã khai báo rồi, và bị khai báo lại thì khi chạy gói thư
viện cũng chỉ chạy 1 lần mà thôi.
Sau đây là ví dụ về sử dụng clientScript:
50. 11. Sử dụng Script Packet
Trong config/main.php ta khai báo ra hai gói thư viện là jquery và base cho template mới mà ta vừa đưa vào:
// Client packet script defined
'clientScript'=>array(
'packages'=>array(
// Override jquery core packet
'jquery'=>array(
'baseUrl'=> 'js/',
'js'=>array('jquery-2.1.1.min.js','jquery-migrate-1.2.1.min.js'),
),
// Example resource for site
'site_resource'=>array(
'baseUrl'=> '',
'css' => array('css/reset.css','css/template-free.css'),
'js'=>array('js/main.js'),
'depends' => array('jquery'),
),
),
),
51. 11. Sử dụng Script Packet
Sử dụng trong views
<?php
$baseUrl = Yii::app()->request->baseUrl;
$clientRes = Yii::app()->getClientScript();
//$clientRes->registerCoreScript('jquery');
$clientRes->registerCoreScript('site_resource');
//$clientRes->registerScriptFile($baseUrl.'/js/main.js');
//$clientRes->registerCssFile($baseUrl.'/css/reset.css');
//$clientRes->registerCssFile($baseUrl.'/css/template-free.css');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title><?php echo CHtml::encode($this->pageTitle); ?></title>
<meta charset="utf-8">
<meta name="author" content="pixelhint.com">
<meta name="description" content=""/>
</head>
52. 13. Tài liệu tham khảo
http://www.yiiframework.com/
Code mẫu kèm theo tài liệu:
https://github.com/tuanquynh0508/yii/tree/master/ex
ample/pro1