Zend-Framwork
Download
Report
Transcript Zend-Framwork
1.
2.
3.
4.
1
2
I.
Giới Thiệu
What, Why, How?
II.
Cấu trúc MVC trong Zend Framework(ZF)
III.
Zend Components
Giới thiệu và demo các thư viện hỗ trợ trong
ZF
3
Framework: Là một cấu trúc mới của ngôn ngữ, giúp
phát triển các ứng dụng phần mềm.
Bên trong framework có các thành phần cơ bản :
1. Code library
2. Scripting language
3. API
Ngoài ra còn được tích hợp các phần mềm hoặc ngôn
ngữ khác
4
Đây là một Open Source, giúp ta xây
dựng Web với PHP theo kiến trúc MVC.
ZF là một framework.
Nổi tiếng nhất cho PHP
Nó hỗ trợ rất nhiều cho developer.
Hướng đối tượng.
Các thành phần ít lệ thuộc với nhau.
5
2005 : Dự án được hình thành
Những nhà sáng lập : Zend (of course), IBM,
OmniTI.
Bất đầu với các component nhưng nó đã có
sự kết hợp với nhau.
Hỗ trợ PHP5, hướng đối tượng.
7-2007 : version 1.0 ra đời.
28-04-2010 : version 1.10.4
6
Mạnh mẽ, chất lượng và hỗ trợ hướng đối tượng
cho PHP 5.
Zend Framework có hỗ trợ làm việc với Tempalate engine
kết hợp cùng tầng View
MVC + PHP ZF
Thư viện hàm : cung cấp 4/5 những gì chúng ta cần.
Hỗ trợ Web 2.0.
Coding standard
http://framework.zend.com/manual/en/codingstandard.html
7
Dễ học và tài liệu về ZF rất phong phú và
sẵn có
http://www.zftutorials.com/
http://framework.zend.com/
Document của ZF
Đây là framework mã nguồn mở nhầm phát
triển ngôn ngữ PHP
+ ZF =
8
Mang đến sự đơn giản nhất có thể:
Đơn giản để sử sử dụng
Đơn gian để vững vàng và ít lổi nhất
Đơn giản để dễ dàng năng cấp
Đưa ra những xu hướng
Web services
Ajax
Search
9
Những đối tác kỹ thuật :
Adobe, Google, IBM, Microsoft, nirvanix,
StrikeIron
Khi gập khó khăn có thể tìm kiếm sự giúp đỡ
tại : zfforum.com,zend.vn/forum, zftalk IRC
35% Website trên thới giới sử dụng PHP
30.000 công ty trên toàn thới giới đã triển
khai
10
Download gói phù hợp với bạn tại
http://framework.zend.com/download/latest
Xem hướng dẫn tại thư mục documentation
Và xem những demo trong thư mục demo
Ta cần config lại 1 số path như trong hướng dẫn tại
http://framework.zend.com/manual/en/learning.quicks
tart.intro.html
IDE hỗ trợ sẵn ZF là Zend Studio
http://www.zend.com/en/products/studio/downloads
11
Model
View
Chứa những class với mục đích giao tiếp
CSDL
Nơi thể hiện thông tin cho người dùng
Controller
Kết nối giữa Model và View
Xử lý các sự kiện khi người dùng tương tác.
12
13
Front Controller
14
Front Controller nằm ở phần đầu tiên của MVC.
Tất cả các PHP request đều đi qua index.php (bootstrap file).
Front Controller giúp cho bạn:
Khởi tạo request/response cho các đối tượng.
Có thể cài đặt các chức năng và xử lý thông thường.
“Include” paths.
Các cấu hình.
Location cho các thành phần MVC(nếu cần thiết).
Đăng nhập, Database,chứng thực/phân quyền.
Convert URL thành 1 “request” với từng phần riêng biệt.
Router các request đến action controller phù hợp.
15
Front Controller
16
Ví dụ:
Request bình thường:
http://example.com/index.php?controller=news&
action=list &id=1
Request trong ZF :
http://example.com/news/list /1
17
Quy ước:
http://example.com/controller/action/param1/value1...
Controller maps
chỉ đến tên lớp
Action maps chỉ
đến tên phương
thức
Param/value
chuyển đến action
Controller1
action1()
action2()
http
request
Bootstrap:
index.php
Front
Controller
Controller2
action1()
action2()
18
Nằm trong thư mục gốc
(public folder):
1.
.htaccess
chuyển hướng
request đến
index.php
2.
index.php
khởi tạo
Front Controller
19
20
Controller chứa các lớp xử lý những request URL
http://example.com/controller/action
Mặc định: IndexController
Tổ chức và nhóm các chức năng
Mỗi class (extending Zend_Controller_Action) đại diện cho 1
controller
Action trong những Controller
http://example.com/controller/action
Mặc định: indexAction()
Đặt tên hàm actionAction()
Ex: nếu hành động là “edit” thì tên ham là editAction()
21
Các hàm giúp tổ chức và điều khiển luồn
init() – gọi bởi constructor
preDispatch() – gọi trước khi thực hiện hàm
postDispatch() – gọi sau khi thực hiện hàm.
Các hàm thường dùng:
forward(), redirect(), getParam(),
getRequest(), getResponse(),render()
22
23
24
Scripts (templates)
o
PHP sử dụng script templates để thể hiện data
o
Chỉ thể hiện chứ không xử lý ở đây.
o
Tên mặc định: “myaction.phtml”
Helpers
o
Là những lớp và phương thức được cung cấp để tái
sử dụng các hàm phục vụ View.
Ví dụ: <p>He gave me <?php echo $this>formatCurrency(10);?>.</p>
He gave me £10.00.
Assigning data to the view
25
Assigning data to the view
Zend_View có hàm assign() để gán dữ liệu.
Assign biến đơn giản:
VD: $view->assign('title', 'Hello World!');
Assign mảng:
music = array('title'=>'Abbey Road', 'artist'=>'The
Beatles');
music = array('title'=>'The Wall', 'artist'=>'Pink Floyd');
view->assign($music);
26
27
Models chứa các business logic, làm nhiệm
vụ giao tiếp với CSDL.
Nó có thể extended từ:
Zend_Db_Table – For database abstraction
Zend_Feed_Element – For RSS abstraction
Zend_Service - for accessing both public and
private
28
<?php
// model: Busyflag.php
class Busyflag
{
// The table name
protected $name = ‘SYSFLAGS'; // old-fashioned “System
36” table
// isSiteUp: return true if up, false if down
public function isSiteUp() {
// one record, with key "B"
$sql = "select BZYFLG from {$this->name} where RECID
= 'B'";
$row = SBSDbhelp::getOneRow($sql);
// true if Y, false otherwise.
return $row['BZYFLG'] == 'Y';
} //(public function isSiteUp())
} //(class Busyflag)
// usage (from a preDispatch front controller plugin)
$busyFlag = new Busyflag();
if (!$busyFlag->isSiteUp()) {
// Take user to "site down" page.
$request->setControllerName("Down");
$request->setActionName("index");
} //(if (!$busyFlag->isSiteUp()))
29
Zend Studio cho Eclipse sẽ giúp bạn xây dựng Web theo
MVC.
Bản free trial: http://www.zend.com/en/products/studio/
30
31
Ghi chú:
Zend/Db.php = Zend_Db
Zend/Db/Table.php =
Zend_Db_Table
32
MVC
Web Services
Formatting
Enterprise
Ajax
Identity,
Authentication,
and Authorization
Debugging,
Logging, and
Testing
I18n and L10n
Forms
Mail
Datastore
Infrastructure
33
Zend_Controller
Zend_Layout
Zend_View
34
35
Zend_Text
Zend_Paginator
36
Là một thành phần cho phép tạo ra chuỗi
Figlet.
Chuỗi Figlet là chuỗi nghệ thuật được trình
bày theo dạng:
37
Các phương thức hỗ trợ:
setConfig($config): Thiết lập các cấu hình
cho chuỗi Figlet
setFont($font): Thiết lập font cho chuỗi Figlet
setOutputWidth($outputWidth): Thiết lập độ
rộng của chuỗi
setHandleParagraphs($handleParagraphs):
Trả về giá trị Boolean cho biết có xuống dòng
hay không
38
Các phương thức hỗ trợ:
setRightToLeft($rightToLeft): Định nghĩa cách
trình bày chuỗi:
DIRECTION_LEFT_TO_RIGHT
DIRECTION_RIGHT_TO_LEFT
setJustification($justification): Canh lề:
0: Canh trái
1: Canh giữa
2: Canh phải
39
Ví dụ xuất ra chuỗi “PHP” đơn giản
40
41
Zend_Text_Table là một thành phần để tạo
ra table
Zend_Text_Table mặc định sử dụng bộ mã
UTF-8 cho cả input và output
Đối tượng Zend_Text_Table chứa những
dòng và cột, được biểu diện thông qua:
Zend_Text_Table_Row
Zend_Text_Table_Column.
42
Các phương thức hỗ trợ:
setDefaultColumnAlign($columnNum, $align):
Thiết lập cách canh lề cho cột mặc định
setInputCharset($charset): Thiết lập mã input
getInputCharset(): Lấy mã input
setOutputCharset($charset): Thiết lập mã
output
getOutputCharset(): Lấy mã output
appendRow($row): Thêm một dòng
43
Các phương thức hỗ trợ:
setConfig(Zend_Config $config): Thiết lập
cấu hình ban đầu
setColumnWidths(array $columnWidths):
Thiết lập độ rộng cột
44
Ví dụ tạo ta table đơn giản:
45
46
Zend_Search_Lucene
Zend_Pdf
47
Một text search engine được viết trên PHP 5. Nó
chứa các index trên file và không yêu cầu một
database server, nên có thể search trên bất kì PHPdriven website nào.
Zend_Search_Lucene hỗ trợ những tính năng sau:
Ranked searching - hiển thị kết quả phù hợp nhất lên
trên
Hỗ trợ nhiều kiểu truy vấn: phrase query, boolean
query, wildcard query, proximity query, range query,
...
Search theo field cụ thể (ví dụ. title, author, contents)
48
Zend_Pdf là một công cụ giúp làm việc với file pdf.Nó
có thể load, create, modify và save file pdf.Zend_Pdf
hỗ trợ:
Tạo mới hoặc load 1 file đã có.
Thao tác các trang trong một file. Thay đổi thứ tự trang,
thêm trang mới, loại bỏ các trang từ một file.
Giúp vẽ hình đơn giản(các đường thẳng, hình chữ nhật,
hình đa giác, hình tròn, bầu dục và các lĩnh vực).
Hỗ trợ nhiều font size.
Xoay.
Vẽ ảnh.
49
Creating :
$pdf = new Zend_Pdf();
Loading :
$file = '/path/to/example.pdf';
$pdf = Zend_Pdf::load($file);
50
Tạo biến $page :
$page = new
Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
$page = new Zend_Pdf_Page($width,
$height);
Tạo page trong pdf:
$pdf->pages[] = $page;
51
$pdf->properties['Title'] = 'Zend_Pdf makes great
PDFs';
52
$file = '/path/to/image.jpg';
$image =
Zend_Pdf_Image::imageWithPath($file);
$page->drawImage($image, $x1, $y1, $x2,
$y2);
53
Saving:
$file = '/path/to/shiny/new/example.pdf';
$pdf->save($file);
54
Zend_Captcha
Zend_Form
Zend_Validate
Zend_Filter
55
Được implement từ Zend_Captcha_Adapter có interface sau :
56
Có những loại Captcha sau :
Dumb
Figlet
Image
ReCaptcha
Dumb, Figlet,Image extends từ
Captcha_Word
57
Các method Word hỗ trợ :
setWordLen ($length) , getWordLen() : chỉ ra số ký
tự của chuỗi kết quả, trả về độ dài.
setTimeOut( $time) : thiết lập timeout cho session
token
getTimeOut() : trả về giá trị timeout
getWord () :nhận lại word được phát sinh với
Capcha, nó sẽ phát sinh lại nếu chưa phát sinh.
58
Methods support :
setExpiration( $expiration ), getExpiration() :
setGcFreq($gcFreq) , getGcFreg() :
setFont($font) , getFont() :
setFontSize($fsize) , getFontSize() :
setHeight($height) , getHeight() :
setWidth($width) , getWidth() :
setImgDir($imgDir) , getImgDir() :
setImgUrl($imgUrl) , getImgUrl() :
setSuffix($suffix) , getSuffix() :
59
Dùng Zend_Service_ReCaptcha để generate &
validate Captcha
setPrivKey($key) ,getPrivKey() : chỉ rõ public ket
được dùng với dịch vụ Recaptcha.
setPubKey($key) , getPubKey() : chỉ rõ public ket
được dùng với dịch vụ Recaptcha,
setService (Zend_Service_ReCaptcha $service)
, getService() : get hoặc set đối tượng service
60
$view = new Zend_View() ; // tạo View
$captcha = new Zend_Captcha_Figlet(
array( 'name' => 'foo', 'wordLen' => 6, 'timeout' => 300,)
);
$id = $captcha->generate();
echo "<form method=\"post\" action=\"\">";
echo $captcha->render($view);
echo "</form>";
61
Alnum
Hex
Alpha
Hostname
Barcode
Ip
Between
InArray
Ccnum
StringLength
CreditCard
Regex
Date
LessThan
Digit
Float
EmailAddress
NotEmpty......
GreaterThan
62
$validator = new Zend_Validate_EmailAddress();
$validator = new Zend_Validate_Alpha(false);
...........
if ($validator->isValid($email)) {
// email appears to be valid
} else {
// email is invalid; print the reasons
}
}
63
64
65
if (Zend_Validate::is($email, 'EmailAddress')) {
// Yes, email appears to be valid
}
if (Zend_Validate::is($value, 'Between',
array('min' => 1, 'max' => 12))) {
// Yes, $value is between 1 and 12
}
66
Chấp nhận các loại card sau :
American Express
JCB
China UnionPay
Laser
Diners Club Card
Blanche
Maestro
MasterCard
Solo
Visa
Visa Electron
Diners Club
International
Diners Club US &
Canada
Discover Card
67
o
$valid = new Zend_Validate_CreditCard(array(
Zend_Validate_CreditCard::AMERICAN_EXPRESS,
Zend_Validate_CreditCard::VISA
));
o
$valid-> isValid($value) : để kiểm tra card
68
69
Include : Zend_Config, Zend_Validate,
Zend_Filter, Zend_Loader_PluginLoader,
and optionally Zend_View.
Elements : button, image, checkbox, hidden,
password, radio, reset, select, submit, text,
textarea.
70
createElement($element,
$name , $options)
addElement($element,
$name, $options)
addElements(array
$elements)
setElements(array
$elements)
getElement($name)
getElements()
removeElement($name)
clearElements()
getValue($name)
getValues()
setElementFilters(array
$filters)
setElementDecorators(arr
ay $decorators)
71
populate(array $values)
isValid(array $data)
isValidPartial(array $data)
processAjax(array $data)
persistData()
getErrors($name = null)
getMessages($name = null)
72
setAttrib($key, $value)
clearAttribs()
addAttribs(array
$attribs)
setAction($action)
getAction()
setMethod($method)
setAttribs(array
$attribs)
getAttrib($key)
getMethod()
getAttribs()
setName($name)
removeAttrib($key)
getName()
73
Tạo form Login extends Zend_Form :
74
Tạo view script Login.phtml để
render form
<?php echo $this->form ; ?>
Tạo LoginController để xử lý
event submit
75
Chuyển
trang
Show Error
76
77
$username->getValidator('alnum')
->setMessage('* Username include letter and number
only.');
$password->getValidator('stringLength')
->setMessage('Your password is too short');
78
$username->setDecorate($decorate)
$password->setDecorate($decorate)
79
Ngoài ra : $object->setAttrib(‘id’, value);
80
81
Zend_Db
Zend_Db_Table
Zend_Db_Profiler
82
Là một thư viện trong bộ thư viện của Zend
Framework.
Cung cấp các class dùng để thao tác trên
nhiều hệ quản trị CSDL.
Dễ dàng hơn trong cách sử dụng.
83
84
Khai báo kết nối: Zend_Db::facroty()
85
Adapter parameters
username
password
dbname
Port
Charset
options
classes
driver_options
86
Những class bên trong Zend_Db
Zend_Db_Adapter
Zend_Db_Statement
Zend_Db_Profiler
Zend_Db_Select
Zend_Db_Table
Zend_Db_Table_Row
Zend_Db_Table_Rowset
Zend_Db_Table Relationships
Zend_Db_Table_Definition
87
Những class bên trong Zend_Db
Zend _Db_Adapter
Zend_Db_Statement
Zend_Db_Profiler
Zend_Db_Select
Zend_Db_Table
Zend_Db_Table_Row
Zend_Db_Table_Rowset
Zend_Db_Table Relationships
Zend_Db_Table_Definition
88
Chọn bảng trong csdl
89
Những thao tác đơn giản
update
insert
90
fetchRow()
Find()
91
Delete()
fetchAll()
92
DEMO
93
Zend_Debug
Zend_Log
Zend_Test
Zend_Wildfire
94
Zend_Currency
Zend_Calendar
Zend_Date
Zend_Locale
Zend_Measure
Zend_TimeSync
Zend_Translate
95
Zend_Mail
96
97
<?php
require_once 'Zend/Mail.php';
$mail = new Zend_Mail();
$mail->setFrom('[email protected]', 'Support');
$mail->addTo('[email protected]', 'Bert');
$mail->setSubject('An Invite to a great new site!');
$mail->setBodyText(
'Hi Bert, Here is an invitation to a great new web site.'
);
$mail->send();
98
Zend_Cache
Zend_Config
Zend_Console
Zend_File
Zend_Loader
Zend_Memory
Zend_Registry
Zend_Version
99
Không sử dụng Cache
Có sử dụng Cache
100
101
102
Zend_Config giúp đơn giản hóa việc truy
cập, sử dụng, và cấu hình dữ liệu trong ứng
dụng.
Có 2 loại : Zend_Config_Ini và
Zend_Config_Xml.
103
104
105
Zend_File_Transfer : giúp upload và
download file.
Upload:
106
Count
FilesSize
Hash
Md5
Size
Upload
…..
107
addValidator($validator,
$breakChainOnFailure, $options = null, $files
= null)
addValidators(array $validators, $files = null)
setValidators(array $validators, $files = null)
hasValidator($name)
getValidator($name)
removeValidator($name)
108
109
Zend_Cache
Zend_Config
Zend_Console
Zend_File
Zend_Loader
Zend_Memory
Zend_Registry
Zend_Version
110
Zend_Acl
Zend_Auth
Zend_Infocard
Zend_OpenId
Zend_Session
111
Zend_Feed
Zend_Gdata
Zend_Http
Zend_Rest
Zend_Soap
Zend_Uri
Zend_XmlRpc
112
Akismet
SlideShare
Amazon
StrikeIron
Audioscrobbler
Technorati
Delicious
Twitter
Flickr
Yahoo
Nirvanix
Simpy
ReCaptcha