• Tidak ada hasil yang ditemukan

zend framework 1 10 x en

N/A
N/A
Protected

Academic year: 2017

Membagikan "zend framework 1 10 x en"

Copied!
1742
0
0

Teks penuh

(1)

Programmer's

Reference

Guide

(2)

Publication date 01/27/2010 by mikaelkael (SVN 20684)

(3)

I. Introduction to Zend Framework ... 1

Overview ... 3

Installation ... 4

II. Learning Zend Framework ... 5

Zend Framework Quick Start ... 8

1. Zend Framework & MVC Introduction ... 8

1.1. Zend Framework ... 8

1.2. Model-View-Controller ... 8

2. Create Your Project ... 10

2.1. Install Zend Framework ... 10

2.2. Create Your Project ... 10

2.3. The Bootstrap ... 11

2.4. Configuration ... 12

2.5. Action Controllers ... 12

2.6. Views ... 13

2.7. Checkpoint ... 15

3. Create A Layout ... 15

4. Create a Model and Database Table ... 18

5. Create A Form ... 28

6. Congratulations! ... 31

Autoloading in Zend Framework ... 33

1. Introduction ... 33

2. Goals and Design ... 33

2.1. Class Naming Conventions ... 33

2.2. Autoloader Conventions and Design ... 33

3. Basic Autoloader Usage ... 34

4. Resource Autoloading ... 36

5. Conclusion ... 37

Plugins in Zend Framework ... 38

1. Introduction ... 38

2. Using Plugins ... 38

3. Conclusion ... 40

Getting Started with Zend_Layout ... 42

1. Introduction ... 42

2. Using Zend_Layout ... 42

2.1. Layout Configuration ... 42

2.2. Create a Layout Script ... 43

2.3. Accessing the Layout Object ... 43

2.4. Other Operations ... 44

3. Zend_Layout: Conclusions ... 45

Getting Started Zend_View Placeholders ... 46

1. Introduction ... 46

2. Basic Placeholder Usage ... 46

3. Standard Placeholders ... 49

3.1. Setting the DocType ... 49

3.2. Specifying the Page Title ... 50

3.3. Specifying Stylesheets with HeadLink ... 51

3.4. Aggregating Scripts Using HeadScript ... 52

4. View Placeholders: Conclusion ... 54

Understanding and Using Zend Form Decorators ... 55

(4)

2. Decorator Basics ... 55

2.1. Overview of the Decorator Pattern ... 55

2.2. Creating Your First Decorator ... 57

3. Layering Decorators ... 58

4. Rendering Individual Decorators ... 62

5. Creating and Rendering Composite Elements ... 66

5.1. The Element ... 66

5.2. The Decorator ... 68

5.3. Conclusion ... 70

6. Conclusion ... 70

Getting Started with Zend_Session, Zend_Auth, and Zend_Acl ... 72

1. Building Multi-User Applications With Zend Framework ... 72

1.1. Zend Framework ... 72

2. Managing User Sessions In ZF ... 72

2.1. Introduction to Sessions ... 72

2.2. Basic Usage of Zend_Session ... 73

2.3. Advanced Usage of Zend_Session ... 74

3. Authenticating Users in Zend Framework ... 74

3.1. Introduction to Authentication ... 74

3.2. Basic Usage of Zend_Auth ... 74

4. Building an Authorization System in Zend Framework ... 76

4.1. Introduction to Authorization ... 76

4.2. Basic Usage of Zend_Acl ... 77

Getting Started with Zend_Search_Lucene ... 80

1. Zend_Search_Lucene Introduction ... 80

2. Lucene Index Structure ... 81

3. Index Opening and Creation ... 82

4. Indexing ... 82

4.1. Indexing Policy ... 82

5. Searching ... 83

6. Supported queries ... 84

7. Search result pagination ... 86

Getting Started with Zend_Paginator ... 88

1. Introduction ... 88

2. Simple Examples ... 88

3. Pagination Control and ScrollingStyles ... 90

4. Putting it all Together ... 91

III. Zend Framework Reference ... 93

Zend_Acl ... 124

1. Introduction ... 124

1.1. Resources ... 124

1.2. Roles ... 124

1.3. Creating the Access Control List ... 125

1.4. Registering Roles ... 126

1.5. Defining Access Controls ... 127

1.6. Querying an ACL ... 127

2. Refining Access Controls ... 128

2.1. Precise Access Controls ... 128

2.2. Removing Access Controls ... 130

3. Advanced Usage ... 130

3.1. Storing ACL Data for Persistence ... 130

3.2. Writing Conditional ACL Rules with Assertions ... 131

Zend_Amf ... 132

(5)

2. Zend_Amf_Server ... 132

2.1. Connecting to the Server from Flex ... 134

2.2. Error Handling ... 136

2.3. AMF Responses ... 136

2.4. Typed Objects ... 136

2.5. Resources ... 138

2.6. Connecting to the Server from Flash ... 138

2.7. Authentication ... 140

Zend_Application ... 142

1. Introduction ... 142

2. Zend_Application Quick Start ... 142

2.1. Using Zend_Tool ... 142

2.2. Adding Zend_Application to your application ... 144

2.3. Adding and creating resources ... 145

2.4. Next steps with Zend_Application ... 147

3. Theory of Operation ... 147

3.1. Bootstrapping ... 148

3.2. Resource Plugins ... 152

4. Examples ... 153

6. Available Resource Plugins ... 168

6.1. Zend_Application_Resource_Cachemanager ... 168

1.3. Identity Persistence ... 180

1.4. Usage ... 183

2. Database Table Authentication ... 184

2.1. Introduction ... 184

2.2. Advanced Usage: Persisting a DbTable Result Object ... 186

2.3. Advanced Usage By Example ... 186

3. Digest Authentication ... 188

3.1. Introduction ... 188

(6)

3.3. Identity ... 188

4. HTTP Authentication Adapter ... 189

4.1. Introduction ... 189

4.2. Design Overview ... 189

4.3. Configuration Options ... 189

4.4. Resolvers ... 190

4.5. Basic Usage ... 191

5. LDAP Authentication ... 192

5.1. Introduction ... 192

5.2. Usage ... 192

5.3. The API ... 193

5.4. Server Options ... 195

5.5. Collecting Debugging Messages ... 198

5.6. Common Options for Specific Servers ... 199

6. Open ID Authentication ... 200

6.1. Introduction ... 200

6.2. Specifics ... 201

Zend_Barcode ... 203

1. Introduction ... 203

2. Barcode creation using Zend_Barcode class ... 203

2.1. Using Zend_Barcode::factory ... 203

2.2. Drawing a barcode ... 204

2.3. Renderering a barcode ... 204

3. Zend_Barcode Objects ... 205

3.1. Common Options ... 206

3.2. Common Additional Getters ... 208

3.3. Description of shipped barcodes ... 208

4. Zend_Barcode Renderers ... 215

4.1. Common Options ... 215

4.2. Zend_Barcode_Renderer_Image ... 216

4.3. Zend_Barcode_Renderer_Pdf ... 217

Zend_Cache ... 218

1. Introduction ... 218

2. The Theory of Caching ... 220

2.1. The Zend_Cache Factory Method ... 221

2.2. Tagging Records ... 221

2.3. Cleaning the Cache ... 222

3. Zend_Cache Frontends ... 222

(7)

5. The Cache Manager ... 239

Zend_Captcha ... 243

1. Introduction ... 243

2. Captcha Operation ... 243

3. CAPTCHA Adapters ... 244

3.1. Zend_Captcha_Word ... 244

3.2. Zend_Captcha_Dumb ... 245

3.3. Zend_Captcha_Figlet ... 245

3.4. Zend_Captcha_Image ... 245

3.5. Zend_Captcha_ReCaptcha ... 246

Zend_CodeGenerator ... 247

1. Introduction ... 247

1.1. Theory of Operation ... 247

2. Zend_CodeGenerator Examples ... 249

3. Zend_CodeGenerator Reference ... 253

3.1. Abstract Classes and Interfaces ... 253

3.2. Concrete CodeGenerator Classes ... 255

Zend_Config ... 261

1. Introduction ... 261

2. Theory of Operation ... 262

3. Zend_Config_Ini ... 263

4. Zend_Config_Xml ... 265

Zend_Config_Writer ... 270

1. Zend_Config_Writer ... 270

Zend_Console_Getopt ... 273

1. Introduction ... 273

2. Declaring Getopt Rules ... 274

2.1. Declaring Options with the Short Syntax ... 274

2.2. Declaring Options with the Long Syntax ... 274

3. Fetching Options and Arguments ... 275

3.1. Handling Getopt Exceptions ... 275

3.2. Fetching Options by Name ... 276

3.3. Reporting Options ... 276

3.4. Fetching Non-option Arguments ... 277

4. Configuring Zend_Console_Getopt ... 277

4.1. Adding Option Rules ... 277

4.2. Adding Help Messages ... 277

4.3. Adding Option Aliases ... 278

4.4. Adding Argument Lists ... 278

4.5. Adding Configuration ... 279

Zend_Controller ... 281

1. Zend_Controller Quick Start ... 281

1.1. Introduction ... 281

1.2. Quick Start ... 281

2. Zend_Controller Basics ... 284

3. The Front Controller ... 287

3.1. Overview ... 287

3.2. Primary Methods ... 288

3.3. Environmental Accessor Methods ... 289

3.4. Front Controller Parameters ... 291

3.5. Extending the Front Controller ... 291

4. The Request Object ... 292

4.1. Introduction ... 292

(8)

4.3. Subclassing the Request Object ... 295

5. The Standard Router ... 297

5.1. Introduction ... 297

5.2. Using a Router ... 298

5.3. Basic Rewrite Router Operation ... 298

5.4. Default Routes ... 300

5.5. Base URL and Subdirectories ... 301

5.6. Global Parameters ... 301

5.7. Route Types ... 301

5.8. Using Zend_Config with the RewriteRouter ... 314

5.9. Subclassing the Router ... 315

6. The Dispatcher ... 315

6.1. Overview ... 315

6.2. Subclassing the Dispatcher ... 317

7. Action Controllers ... 320

7.1. Introduction ... 320

7.2. Object Initialization ... 321

7.3. Pre- and Post-Dispatch Hooks ... 321

7.4. Accessors ... 322

7.5. View Integration ... 323

7.6. Utility Methods ... 324

7.7. Subclassing the Action Controller ... 325

8. Action Helpers ... 327

8.1. Introduction ... 327

8.2. Helper Initialization ... 327

8.3. The Helper Broker ... 328

8.4. Built-in Action Helpers ... 329

8.5. Writing Your Own Helpers ... 357

9. The Response Object ... 357

9.1. Usage ... 357

9.2. Manipulating Headers ... 359

9.3. Named Segments ... 360

9.4. Testing for Exceptions in the Response Object ... 361

9.5. Subclassing the Response Object ... 362

10. Plugins ... 362

10.1. Introduction ... 362

10.2. Writing Plugins ... 362

10.3. Using Plugins ... 363

10.4. Retrieving and Manipulating Plugins ... 364

10.5. Plugins Included in the Standard Distribution ... 364

11. Using a Conventional Modular Directory Structure ... 369

11.1. Introduction ... 369

11.2. Specifying Module Controller Directories ... 370

11.3. Routing to Modules ... 371

11.4. Module or Global Default Controller ... 371

12. MVC Exceptions ... 371

12.1. Introduction ... 371

12.2. Handling Exceptions ... 372

12.3. MVC Exceptions You May Encounter ... 373

Zend_Currency ... 376

1. Introduction to Zend_Currency ... 376

1.1. Why should you use Zend_Currency? ... 376

2. Using Zend_Currency ... 376

(9)

2.2. Currency creation based on a locale ... 377

3. Options for currencies ... 377

4. What makes a currency? ... 378

5. Where is the currency? ... 380

6. How does the currency look like? ... 381

7. How much is my currency? ... 382

7.1. Working with currency values ... 383

7.2. Using precision on currencies ... 383

8. Calculating with currencies ... 384

9. Exchanging currencies ... 385

10. Additional informations on Zend_Currency ... 386

10.1. Currency informations ... 386

10.2. Currency Performance Optimization ... 387

Zend_Date ... 388

1. Introduction ... 388

1.1. Always Set a Default Timezone ... 388

1.2. Why Use Zend_Date? ... 388

2. Theory of Operation ... 389

2.1. Internals ... 389

3. Basic Methods ... 390

3.1. Current Date ... 390

3.2. Zend_Date by Example ... 390

4. Zend_Date API Overview ... 392

4.1. Zend_Date Options ... 392

4.2. Working with Date Values ... 393

4.3. Basic Zend_Date Operations Common to Many Date Parts ... 394

4.4. Comparing Dates ... 397

4.5. Getting Dates and Date Parts ... 399

4.6. Working with Fractions of Seconds ... 400

4.7. Sunrise / Sunset ... 400

5. Creation of Dates ... 401

5.1. Create the Actual Date ... 401

5.2. Create a Date from Database ... 401

5.3. Create Dates from an Array ... 402

6. Constants for General Date Functions ... 402

6.1. Using Constants ... 402

6.2. List of All Constants ... 403

6.3. Self-Defined OUTPUT Formats with ISO ... 407

6.4. Self-Defined OUTPUT Formats Using PHP's date() Format Specifiers ... 410

7. Working Examples ... 413

7.1. Checking Dates ... 413

7.2. Sunrise and Sunset ... 414

7.3. Time Zones ... 416

Zend_Db ... 419

1. Zend_Db_Adapter ... 419

1.1. Connecting to a Database Using an Adapter ... 419

1.2. Example Database ... 424

1.3. Reading Query Results ... 425

1.4. Writing Changes to the Database ... 428

1.5. Quoting Values and Identifiers ... 432

1.6. Controlling Database Transactions ... 434

1.7. Listing and Describing Tables ... 435

(10)

1.9. Running Other Database Statements ... 437

1.10. Retrieving Server Version ... 438

1.11. Notes on Specific Adapters ... 438

2. Zend_Db_Statement ... 441

2.1. Creating a Statement ... 441

2.2. Executing a Statement ... 442

2.3. Fetching Results from a SELECT Statement ... 442

3. Zend_Db_Profiler ... 444

3.1. Introduction ... 444

3.2. Using the Profiler ... 446

3.3. Advanced Profiler Usage ... 447

3.4. Specialized Profilers ... 448

4. Zend_Db_Select ... 449

4.1. Introduction ... 449

4.2. Creating a Select Object ... 450

4.3. Building Select queries ... 450

4.4. Executing Select Queries ... 463

4.5. Other methods ... 464

5. Zend_Db_Table ... 466

5.1. Introduction ... 466

5.2. Using Zend_Db_Table as a concrete class ... 466

5.3. Defining a Table Class ... 466

5.4. Creating an Instance of a Table ... 469

5.5. Inserting Rows to a Table ... 471

5.6. Updating Rows in a Table ... 473

5.7. Deleting Rows from a Table ... 473

5.8. Finding Rows by Primary Key ... 474

5.9. Querying for a Set of Rows ... 475

5.10. Querying for a Single Row ... 479

5.11. Retrieving Table Metadata Information ... 479

5.12. Caching Table Metadata ... 480

5.13. Customizing and Extending a Table Class ... 482

6. Zend_Db_Table_Row ... 485

6.1. Introduction ... 485

6.2. Fetching a Row ... 485

6.3. Writing rows to the database ... 487

6.4. Serializing and unserializing rows ... 489

6.5. Extending the Row class ... 490

7. Zend_Db_Table_Rowset ... 493

7.1. Introduction ... 493

7.2. Fetching a Rowset ... 493

7.3. Retrieving Rows from a Rowset ... 493

7.4. Retrieving a Rowset as an Array ... 495

7.5. Serializing and Unserializing a Rowset ... 496

7.6. Extending the Rowset class ... 497

8. Zend_Db_Table Relationships ... 498

8.1. Introduction ... 498

8.2. Defining Relationships ... 498

8.3. Fetching a Dependent Rowset ... 500

8.4. Fetching a Parent Row ... 502

8.5. Fetching a Rowset via a Many-to-many Relationship ... 503

8.6. Cascading Write Operations ... 505

9. Zend_Db_Table_Definition ... 507

(11)

9.2. Basic Usage ... 507

9.3. Advanced Usage ... 509

Zend_Debug ... 511

1. Dumping Variables ... 511

Zend_Dojo ... 512

1. Introduction ... 512

2. Zend_Dojo_Data: dojo.data Envelopes ... 512

2.1. Zend_Dojo_Data Usage ... 512

2.2. Adding metadata to your containers ... 514

2.3. Advanced Use Cases ... 514

3. Dojo View Helpers ... 516

3.1. dojo() View Helper ... 516

3.2. Dijit-Specific View Helpers ... 521

4. Dojo Form Elements and Decorators ... 534

4.1. Dijit-Specific Form Decorators ... 535

4.2. Dijit-Specific Form Elements ... 537

4.3. Dojo Form Examples ... 554

5. Zend_Dojo build layer support ... 555

5.1. Introduction ... 555

5.2. Generating Custom Module Layers with Zend_Dojo_BuildLayer ... 556

5.3. Generating Build Profiles with Zend_Dojo_BuildLayer ... 558

Zend_Dom ... 561

1. Introduction ... 561

2. Zend_Dom_Query ... 561

2.1. Theory of Operation ... 561

2.2. Methods Available ... 562

Zend_Exception ... 564

1. Using Exceptions ... 564

2. Basic usage ... 564

3. Previous Exceptions ... 564

Zend_Feed ... 566

1. Introduction ... 566

2. Importing Feeds ... 567

2.1. Custom feeds ... 567

3. Retrieving Feeds from Web Pages ... 571

4. Consuming an RSS Feed ... 572

5. Consuming an Atom Feed ... 573

6. Consuming a Single Atom Entry ... 574

7. Modifying Feed and Entry structures ... 575

8. Custom Feed and Entry Classes ... 575

9. Zend_Feed_Reader ... 577

9.1. Introduction ... 577

9.2. Importing Feeds ... 577

9.3. Retrieving Underlying Feed and Entry Sources ... 578

9.4. Cache Support and Intelligent Requests ... 579

9.5. Locating Feed URIs from Websites ... 580

9.6. Attribute Collections ... 581

9.7. Retrieving Feed Information ... 582

9.8. Retrieving Entry/Item Information ... 585

9.9. Extending Feed and Entry APIs ... 588

10. Zend_Feed_Writer ... 592

10.1. Introduction ... 592

10.2. Architecture ... 592

(12)

10.4. Setting Feed Data Points ... 594

10.5. Setting Entry Data Points ... 596

11. Zend_Feed_Pubsubhubbub ... 598

11.1. What is Pubsubhubbub? ... 598

11.2. Architecture ... 599

11.3. Zend_Feed_Pubsubhubbub_Publisher ... 599

11.4. Zend_Feed_Pubsubhubbub_Subscriber ... 600

Zend_File ... 608

1. Zend_File_Transfer ... 608

1.1. Supported Adapters for Zend_File_Transfer ... 609

1.2. Options for Zend_File_Transfer ... 609

1.3. Checking Files ... 610

1.4. Additional File Informations ... 610

1.5. Progress for file uploads ... 612

2. Validators for Zend_File_Transfer ... 614

2.1. Using Validators with Zend_File_Transfer ... 615

2.2. Count Validator ... 617

2.3. Crc32 Validator ... 618

2.4. ExcludeExtension Validator ... 618

2.5. ExcludeMimeType Validator ... 619

2.6. Exists Validator ... 620

2.7. Extension Validator ... 620

2.8. FilesSize Validator ... 621

2.9. ImageSize Validator ... 622

2.10. IsCompressed Validator ... 623

2.11. IsImage Validator ... 623

2.12. Hash Validator ... 624

2.13. Md5 Validator ... 624

2.14. MimeType Validator ... 625

2.15. NotExists Validator ... 626

2.16. Sha1 Validator ... 627

2.17. Size Validator ... 627

2.18. WordCount Validator ... 628

3. Filters for Zend_File_Transfer ... 628

3.1. Using filters with Zend_File_Transfer ... 629

3.2. Decrypt filter ... 630

3.3. Encrypt filter ... 630

3.4. LowerCase filter ... 631

3.5. Rename filter ... 631

3.6. UpperCase filter ... 632

Zend_Filter ... 634

1. Introduction ... 634

1.1. What is a filter? ... 634

1.2. Basic usage of filters ... 634

1.3. Using the static staticFilter() method ... 634

2. Standard Filter Classes ... 635

2.1. Alnum ... 635

2.2. Alpha ... 636

2.3. BaseName ... 636

2.4. Boolean ... 636

2.5. Callback ... 638

2.6. Compress and Decompress ... 639

2.7. Decrypt ... 645

(13)

2.9. Dir ... 647

3.1. Changing filter chain order ... 657

4. Writing Filters ... 657

5. Zend_Filter_Input ... 658

5.1. Declaring Filter and Validator Rules ... 658

5.2. Creating the Filter and Validator Processor ... 660

5.3. Retrieving Validated Fields and other Reports ... 660

5.4. Using Metacommands to Control Filter or Validator Rules ... 663

5.5. Adding Filter Class Namespaces ... 668

6. Zend_Filter_Inflector ... 669

6.1. Operation ... 669

6.2. Setting Paths To Alternate Filters ... 670

6.3. Setting the Inflector Target ... 670

6.4. Inflection Rules ... 671

6.5. Utility Methods ... 673

6.6. Using Zend_Config with Zend_Filter_Inflector ... 673

Zend_Form ... 675

1. Zend_Form ... 675

2. Zend_Form Quick Start ... 675

2.1. Create a form object ... 675

2.2. Add elements to the form ... 675

2.3. Render a form ... 677

2.4. Check if a form is valid ... 678

2.5. Get error status ... 679

2.6. Putting it together ... 679

2.7. Using a Zend_Config Object ... 681

2.8. Conclusion ... 682

3. Creating Form Elements Using Zend_Form_Element ... 682

3.1. Plugin Loaders ... 682

3.2. Filters ... 684

3.3. Validators ... 685

3.4. Decorators ... 690

3.5. Metadata and Attributes ... 692

3.6. Standard Elements ... 693

3.7. Zend_Form_Element Methods ... 693

3.8. Configuration ... 695

3.9. Custom Elements ... 696

4. Creating Forms Using Zend_Form ... 697

4.1. Plugin Loaders ... 698

(14)

4.3. Display Groups ... 703

4.4. Sub Forms ... 707

4.5. Metadata and Attributes ... 708

4.6. Decorators ... 709

4.7. Validation ... 711

4.8. Methods ... 713

4.9. Configuration ... 716

4.10. Custom forms ... 717

5. Creating Custom Form Markup Using Zend_Form_Decorator ... 719

5.1. Operation ... 719

5.2. Standard Decorators ... 720

5.3. Custom Decorators ... 720

5.4. Rendering Individual Decorators ... 723

6. Standard Form Elements Shipped With Zend Framework ... 723

6.1. Zend_Form_Element_Button ... 723

7. Standard Form Decorators Shipped With Zend Framework ... 732

7.1. Zend_Form_Decorator_Callback ... 732

8. Internationalization of Zend_Form ... 737

8.1. Initializing I18n in Forms ... 737

8.2. Standard I18n Targets ... 738

9. Advanced Zend_Form Usage ... 739

9.1. Array Notation ... 739

9.2. Multi-Page Forms ... 741

(15)

1. Introduction ... 743

1.1. Structure of Zend_Gdata ... 743

1.2. Interacting with Google Services ... 744

1.3. Obtaining instances of Zend_Gdata classes ... 744

1.4. Google Data Client Authentication ... 745

1.5. Dependencies ... 745

1.6. Creating a new Gdata client ... 745

1.7. Common Query Parameters ... 746

1.8. Fetching a Feed ... 747

1.9. Working with Multi-page Feeds ... 747

1.10. Working with Data in Feeds and Entries ... 748

1.11. Updating Entries ... 748

1.12. Posting Entries to Google Servers ... 749

1.13. Deleting Entries on Google Servers ... 749

2. Authenticating with AuthSub ... 750

2.1. Creating an AuthSub authenticated Http Client ... 750

2.2. Revoking AuthSub authentication ... 751

3. Using the Book Search Data API ... 751

3.1. Authenticating to the Book Search service ... 752

3.2. Searching for books ... 752

3.3. Using community features ... 753

3.4. Book collections and My Library ... 755

4. Authenticating with ClientLogin ... 757

4.1. Creating a ClientLogin authenticated Http Client ... 757

4.2. Terminating a ClientLogin authenticated Http Client ... 758

5. Using Google Calendar ... 758

5.1. Connecting To The Calendar Service ... 758

5.2. Retrieving A Calendar List ... 761

5.3. Retrieving Events ... 761

5.4. Creating Events ... 763

5.5. Modifying Events ... 766

5.6. Deleting Events ... 767

5.7. Accessing Event Comments ... 767

6. Using Google Documents List Data API ... 768

6.1. Get a List of Documents ... 768

6.2. Upload a Document ... 768

6.3. Searching the documents feed ... 769

7. Using Google Health ... 770

7.1. Connect To The Health Service ... 770

7.2. Profile Feed ... 773

7.3. Profile List Feed ... 774

7.4. Sending Notices to the Register Feed ... 775

8. Using Google Spreadsheets ... 776

8.1. Create a Spreadsheet ... 776

8.2. Get a List of Spreadsheets ... 776

8.3. Get a List of Worksheets ... 776

8.4. Interacting With List-based Feeds ... 776

8.5. Interacting With Cell-based Feeds ... 779

9. Using Google Apps Provisioning ... 780

9.1. Setting the current domain ... 780

9.2. Interacting with users ... 781

9.3. Interacting with nicknames ... 784

9.4. Interacting with email lists ... 786

(16)

9.6. Handling errors ... 788

10. Using Google Base ... 788

10.1. Connect To The Base Service ... 789

10.2. Retrieve Items ... 791

10.3. Insert, Update, and Delete Customer Items ... 793

11. Using Picasa Web Albums ... 794

11.1. Connecting To The Service ... 795

11.2. Understanding and Constructing Queries ... 797

11.3. Retrieving Feeds And Entries ... 798

11.4. Creating Entries ... 802

11.5. Deleting Entries ... 803

12. Using the YouTube Data API ... 805

12.1. Authentication ... 805

12.2. Developer Keys and Client ID ... 805

12.3. Retrieving public video feeds ... 805

12.4. Retrieving video comments ... 807

12.5. Retrieving playlist feeds ... 808

12.6. Retrieving a list of a user's subscriptions ... 808

12.7. Retrieving a user's profile ... 809

12.8. Uploading Videos to YouTube ... 809

12.9. Browser-based upload ... 811

12.10. Checking upload status ... 811

12.11. Other Functions ... 812

13. Catching Gdata Exceptions ... 812

Zend_Http ... 814

1. Introduction ... 814

1.1. Using Zend_Http_Client ... 814

1.2. Configuration Parameters ... 814

1.3. Performing Basic HTTP Requests ... 815

1.4. Adding GET and POST parameters ... 816

1.5. Accessing Last Request and Response ... 817

2. Zend_Http_Client - Advanced Usage ... 817

2.1. HTTP Redirections ... 817

2.2. Adding Cookies and Using Cookie Persistence ... 817

2.3. Setting Custom Request Headers ... 818

2.4. File Uploads ... 819

2.5. Sending Raw POST Data ... 820

2.6. HTTP Authentication ... 820

2.7. Sending Multiple Requests With the Same Client ... 821

2.8. Data Streaming ... 822

3. Zend_Http_Client - Connection Adapters ... 823

3.1. Overview ... 823

3.2. The Socket Adapter ... 823

3.3. The Proxy Adapter ... 826

3.4. The cURL Adapter ... 827

3.5. The Test Adapter ... 828

3.6. Creating your own connection adapters ... 831

4. Zend_Http_Cookie and Zend_Http_CookieJar ... 833

4.1. Introduction ... 833

4.2. Instantiating Zend_Http_Cookie Objects ... 833

4.3. Zend_Http_Cookie getter methods ... 834

4.4. Zend_Http_Cookie: Matching against a scenario ... 835

4.5. The Zend_Http_CookieJar Class: Instantiation ... 836

(17)

4.7. Retrieving Cookies From a Zend_Http_CookieJar object ... 837

5. Zend_Http_Response ... 838

5.1. Introduction ... 838

5.2. Boolean Tester Methods ... 839

5.3. Accessor Methods ... 839

5.4. Static HTTP Response Parsers ... 840

Zend_InfoCard ... 842

1. Introduction ... 842

1.1. Basic Theory of Usage ... 842

1.2. Using as part of Zend_Auth ... 842

1.3. Using the Zend_InfoCard component standalone ... 844

1.4. Working with a Claims object ... 844

1.5. Attaching Information Cards to existing accounts ... 845

1.6. Creating Zend_InfoCard Adapters ... 846

Zend_Json ... 848

1. Introduction ... 848

2. Basic Usage ... 848

2.1. Pretty-printing JSON ... 848

3. Advanced Usage of Zend_Json ... 848

3.1. JSON Objects ... 848

3.2. Encoding PHP objects ... 849

3.3. Internal Encoder/Decoder ... 849

3.4. JSON Expressions ... 849

4. XML to JSON conversion ... 850

5. Zend_Json_Server - JSON-RPC server ... 851

5.1. Advanced Details ... 854

Zend_Layout ... 860

1. Introduction ... 860

2. Zend_Layout Quick Start ... 860

2.1. Layout scripts ... 860

2.2. Using Zend_Layout with the Zend Framework MVC ... 861

2.3. Using Zend_Layout as a Standalone Component ... 862

2.4. Sample Layout ... 863

3. Zend_Layout Configuration Options ... 865

3.1. Examples ... 865

4. Zend_Layout Advanced Usage ... 867

4.1. Custom View Objects ... 867

4.2. Custom Front Controller Plugins ... 867

4.3. Custom Action Helpers ... 868

4.4. Custom Layout Script Path Resolution: Using the Inflector ... 868

Zend_Ldap ... 870

1. Introduction ... 870

1.1. Theory of operation ... 870

2. API overview ... 873

2.1. Configuration / options ... 873

2.2. API Reference ... 875

3. Usage Scenarios ... 900

3.1. Authentication scenarios ... 900

3.2. Basic CRUD operations ... 901

3.3. Extended operations ... 902

4. Tools ... 903

4.1. Creation and modification of DN strings ... 903

4.2. Using the filter API to create search filters ... 903

(18)

5. Object oriented access to the LDAP tree using Zend_Ldap_Node ... 903

5.1. Basic CRUD operations ... 903

5.2. Extended operations ... 904

5.3. Tree traversal ... 904

6. Getting information from the LDAP server ... 904

6.1. RootDSE ... 904

6.2. Schema Browsing ... 904

7. Serializing LDAP data to and from LDIF ... 905

7.1. Serialize a LDAP entry to LDIF ... 905

7.2. Deserialize a LDIF string into a LDAP entry ... 906

Zend_Loader ... 908

1. Loading Files and Classes Dynamically ... 908

1.1. Loading Files ... 908

1.2. Loading Classes ... 908

1.3. Testing if a File is Readable ... 909

1.4. Using the Autoloader ... 910

2. The Autoloader ... 910

2.1. Using the Autoloader ... 911

2.2. Selecting a Zend Framework version ... 912

2.3. The Autoloader Interface ... 914

2.4. Autoloader Reference ... 914

3. Resource Autoloaders ... 917

3.1. Resource autoloader usage ... 917

3.2. The Module Resource Autoloader ... 919

3.3. Using Resource Autoloaders as Object Factories ... 919

3.4. Resource Autoloader Reference ... 919

4. Loading Plugins ... 919

4.1. Basic Use Case ... 920

4.2. Manipulating Plugin Paths ... 921

4.3. Testing for Plugins and Retrieving Class Names ... 921

4.4. Getting Better Performance for Plugins ... 922

Zend_Locale ... 923

1. Introduction ... 923

1.1. What is Localization ... 923

1.2. What is a Locale? ... 924

1.3. How are Locales Represented? ... 924

1.4. Selecting the Right Locale ... 925

1.5. Usage of automatic Locales ... 925

1.6. Using a default Locale ... 926

1.7. ZF Locale-Aware Classes ... 927

1.8. Application wide locale ... 927

1.9. Zend_Locale_Format::setOptions(array $options) ... 928

1.10. Speed up Zend_Locale and its subclasses ... 928

2. Using Zend_Locale ... 929

2.1. Copying, Cloning, and Serializing Locale Objects ... 929

2.2. Equality ... 929

2.3. Default locales ... 930

2.4. Set a new locale ... 930

2.5. Getting the language and region ... 930

2.6. Obtaining localized strings ... 931

2.7. Obtaining translations for "yes" and "no" ... 945

2.8. Get a list of all known locales ... 946

2.9. Detecting locales ... 946

(19)

3.1. Number normalization: getNumber($input, Array $options) ... 948

3.2. Number localization ... 949

3.3. Number testing ... 951

3.4. Float value normalization ... 951

3.5. Floating point value localization ... 951

3.6. Floating point value testing ... 951

3.7. Integer value normalization ... 952

3.8. Integer point value localization ... 952

3.9. Integer value testing ... 952

3.10. Numeral System Conversion ... 952

4. Working with Dates and Times ... 954

4.1. Normalizing Dates and Times ... 954

4.2. Testing Dates ... 957

4.3. Normalizing a Time ... 958

4.4. Testing Times ... 958

5. Supported locales ... 958

Zend_Log ... 970

1. Overview ... 970

1.1. Creating a Log ... 970

1.2. Logging Messages ... 970

1.3. Destroying a Log ... 971

1.4. Using Built-in Priorities ... 971

1.5. Adding User-defined Priorities ... 971

1.6. Understanding Log Events ... 972

2. Writers ... 972

2.1. Writing to Streams ... 972

2.2. Writing to Databases ... 973

2.3. Writing to Firebug ... 973

2.4. Writing to Email ... 975

2.5. Writing to the System Log ... 977

2.6. Writing to the Zend Server Monitor ... 978

2.7. Stubbing Out the Writer ... 982

2.8. Testing with the Mock ... 982

2.9. Compositing Writers ... 982

3. Formatters ... 983

3.1. Simple Formatting ... 983

3.2. Formatting to XML ... 983

4. Filters ... 984

4.1. Filtering for All Writers ... 984

4.2. Filtering for a Writer Instance ... 985

5. Using the Factory to Create a Log ... 985

5.1. Writer Options ... 986

5.2. Filter Options ... 987

5.3. Creating Configurable Writers and Filters ... 987

Zend_Mail ... 989

1. Introduction ... 989

1.1. Getting started ... 989

1.2. Configuring the default sendmail transport ... 989

2. Sending via SMTP ... 990

3. Sending Multiple Mails per SMTP Connection ... 990

4. Using Different Transports ... 992

5. HTML E-Mail ... 992

6. Attachments ... 993

(20)

8. Controlling the MIME Boundary ... 994

9. Additional Headers ... 994

10. Character Sets ... 995

11. Encoding ... 995

12. SMTP Authentication ... 996

13. Securing SMTP Transport ... 996

14. Reading Mail Messages ... 997

14.1. Simple example using Pop3 ... 997

14.2. Opening a local storage ... 997

14.3. Opening a remote storage ... 998

14.4. Fetching messages and simple methods ... 998

14.5. Working with messages ... 999

14.6. Checking for flags ... 1001

14.7. Using folders ... 1002

14.8. Advanced Use ... 1004

Zend_Markup ... 1008

1. Introduction ... 1008

2. Getting Started With Zend_Markup ... 1008

3. Zend_Markup Parsers ... 1009

3.1. Theory of Parsing ... 1009

3.2. The BBCode parser ... 1009

3.3. The Textile parser ... 1010

4. Zend_Markup Renderers ... 1010

4.1. Adding your own tags ... 1011

4.2. List of tags ... 1012

Zend_Measure ... 1013

1. Introduction ... 1013

2. Creation of Measurements ... 1013

2.1. Creating measurements from integers and floats ... 1013

2.2. Creating measurements from strings ... 1014

2.3. Measurements from localized strings ... 1014

3. Outputting measurements ... 1015

3.1. Automatic output ... 1015

3.2. Outputting values ... 1015

3.3. Output with unit of measurement ... 1016

3.4. Output as localized string ... 1016

4. Manipulating Measurements ... 1016

4.1. Convert ... 1016

4.2. Add and subtract ... 1017

4.3. Compare ... 1017

4.4. Compare ... 1018

4.5. Manually change values ... 1018

4.6. Manually change types ... 1019

5. Types of measurements ... 1019

5.1. Hints for Zend_Measure_Binary ... 1022

5.2. Hints for Zend_Measure_Number ... 1022

5.3. Roman numbers ... 1022

Zend_Memory ... 1023

1. Overview ... 1023

1.1. Introduction ... 1023

1.2. Theory of Operation ... 1023

2. Memory Manager ... 1024

2.1. Creating a Memory Manager ... 1024

(21)

2.3. Memory Manager Settings ... 1026

3. Memory Objects ... 1026

3.1. Movable ... 1026

3.2. Locked ... 1027

3.3. Memory container 'value' property ... 1027

3.4. Memory container interface ... 1027

Zend_Mime ... 1030

1. Zend_Mime ... 1030

1.1. Introduction ... 1030

1.2. Static Methods and Constants ... 1030

1.3. Instantiating Zend_Mime ... 1031

2. Zend_Mime_Message ... 1031

2.1. Introduction ... 1031

2.2. Instantiation ... 1031

2.3. Adding MIME Parts ... 1031

2.4. Boundary handling ... 1031

2.5. parsing a string to create a Zend_Mime_Message object (experimental) ... 1032

3. Zend_Mime_Part ... 1032

3.1. Introduction ... 1032

3.2. Instantiation ... 1032

3.3. Methods for rendering the message part to a string ... 1032

Zend_Navigation ... 1034

1. Introduction ... 1034

1.1. Pages and Containers ... 1034

1.2. Separation of data (model) and rendering (view) ... 1034

2. Pages ... 1034

2.1. Common page features ... 1035

2.2. Zend_Navigation_Page_Mvc ... 1037

2.3. Zend_Navigation_Page_Uri ... 1041

2.4. Creating custom page types ... 1042

2.5. Creating pages using the page factory ... 1043

3. Containers ... 1045

3.1. Creating containers ... 1045

3.2. Adding pages ... 1048

3.3. Removing pages ... 1048

3.4. Finding pages ... 1049

3.5. Iterating containers ... 1051

3.6. Other operations ... 1051

Zend_Oauth ... 1054

1. Introduction to OAuth ... 1054

1.1. Protocol Workflow ... 1054

1.2. Security Architecture ... 1055

1.3. Getting Started ... 1056

Zend_OpenId ... 1060

1. Introduction ... 1060

1.1. What is OpenID? ... 1060

1.2. How Does it Work? ... 1060

1.3. Zend_OpenId Structure ... 1061

1.4. Supported OpenID Standards ... 1061

2. Zend_OpenId_Consumer Basics ... 1061

2.1. OpenID Authentication ... 1061

2.2. Combining all Steps in One Page ... 1063

(22)
(23)
(24)
(25)
(26)
(27)
(28)
(29)
(30)
(31)
(32)
(33)
(34)
(35)
(36)
(37)
(38)
(39)

Zend Framework is an open source framework for developing web applications and services with PHP 5. Zend Framework is implemented using 100% object-oriented code. The component structure of Zend Framework is somewhat unique; each component is designed with few dependencies on other components. This loosely coupled architecture allows developers to use components individually. We often call this a "use-at-will" design.

While they can be used separately, Zend Framework components in the standard library form a powerful and extensible web application framework when combined. Zend Framework offers a robust, high performance MVC implementation, a database abstraction that is simple to use, and a forms component that implements HTML form rendering, validation, and filtering so that developers can consolidate all of these operations using one easy-to-use, object oriented interface. Other components, such as Zend_Auth and Zend_Acl, provide user authentication and authorization against all common credential stores. Still others implement client libraries to simply access to the most popular web services available. Whatever your application needs are, you're likely to find a Zend Framework component that can be used to dramatically reduce development time with a thoroughly tested foundation.

(40)

See the requirements appendix for a detailed list of requirements for Zend Framework.

Installing Zend Framework is extremely simple. Once you have downloaded and extracted the framework, you should add the /library folder in the distribution to the beginning of your include path. You may also want to move the library folder to another – possibly shared – location on your file system.

• Download the latest stable release. This version, available in both .zip and .tar.gz formats, is a good choice for those who are new to Zend Framework.

• Download the latest nightly snapshot. For those who would brave the cutting edge, the nightly snapshots represent the latest progress of Zend Framework development. Snapshots are bundled with documentation either in English only or in all available languages. If you anticipate working with the latest Zend Framework developments, consider using a Subversion (SVN) client.

• Using a Subversion (SVN) client. Zend Framework is open source software, and the Subversion repository used for its development is publicly available. Consider using SVN to get Zend Framework if you already use SVN for your application development, want to contribute back to the framework, or need to upgrade your framework version more often than releases occur.

Exporting is useful if you want to get a particular framework revision without the .svn directories as created in a working copy.

Check out a working copy if you want contribute to Zend Framework, a working copy can be updated any time with svn update and changes can be commited to our SVN repository with the svn commit command.

An externals definition is quite convenient for developers already using SVN to manage their application's working copies.

The URL for the trunk of Zend Framework's SVN repository is: http://framework.zend.com/ svn/framework/standard/trunk

Once you have a copy of Zend Framework available, your application needs to be able to access the framework classes. Though there are several ways to achieve this, your PHP include_path needs to contain the path to Zend Framework's library.

Zend provides a QuickStart to get you up and running as quickly as possible. This is an excellent way to begin learning about the framework with an emphasis on real world examples that you can build upon.

(41)
(42)
(43)
(44)

1. Zend Framework & MVC Introduction

1.1. Zend Framework

Zend Framework is an open source, object oriented web application framework for PHP 5. Zend Framework is often called a 'component library', because it has many loosely coupled components that you can use more or less independently. But Zend Framework also provides an advanced Model-View-Controller (MVC) implementation that can be used to establish a basic structure for your Zend Framework applications. A full list of Zend Framework components along with short descriptions may be found in the components overview. This QuickStart will introduce you to some of Zend Framework's most commonly used components, including Zend_Controller, Zend_Layout, Zend_Config, Zend_Db, Zend_Db_Table, Zend_Registry, along with a few view helpers.

Using these components, we will build a simple database-driven guest book application within minutes. The complete source code for this application is available in the following archives: • zip

• tar.gz

1.2. Model-View-Controller

So what exactly is this MVC pattern everyone keeps talking about, and why should you care? MVC is much more than just a three-letter acronym (TLA) that you can whip out anytime you want to sound smart; it has become something of a standard in the design of modern web applications. And for good reason. Most web application code falls under one of the following three categories: presentation, business logic, and data access. The MVC pattern models this separation of concerns well. The end result is that your presentation code can be consolidated in one part of your application with your business logic in another and your data access code in yet another. Many developers have found this well-defined separation indispensable for keeping their code organized, especially when more than one developer is working on the same application.

More Information

(45)

Model - This is the part of your application that defines its basic functionality behind a set of abstractions. Data access routines and some business logic can be defined in the model.

View - Views define exactly what is presented to the user. Usually controllers pass data to each view to render in some format. Views will often collect data from the user, as well. This is where you're likely to find HTML markup in your MVC applications.

(46)

Of course there is more to be said about this critical pattern, but this should give you enough background to understand the guestbook application we'll be building.

2. Create Your Project

In order to create your project, you must first download and extract Zend Framework.

2.1. Install Zend Framework

The easiest way to get Zend Framework along with a complete PHP stack is by installing Zend Server. Zend Server has native installers for Mac OSX, Windows, Fedora Core, and Ubuntu, as well as a universal installation package compatible with most Linux distributions.

After you have installed Zend Server, the Framework files may be found under /usr/local/ zend/share/ZendFramework on Mac OSX and Linux, and C:\Program Files\Zend \ZendServer\share\ZendFramework on Windows. The include_path will already be configured to include Zend Framework.

Alternately, you can Download the latest version of Zend Framework and extract the contents; make a note of where you have done so.

Optionally, you can add the path to the library/ subdirectory of the archive to your php.ini's include_path setting.

That's it! Zend Framework is now installed and ready to use.

2.2. Create Your Project

zf Command Line Tool

In your Zend Framework installation is a bin/ subdirectory, containing the scripts zf.sh and zf.bat for Unix-based and Windows-based users, respectively. Make a note of the absolute path to this script.

Wherever you see references to zf.sh or zf.bat, please substitute the absolute path to the script. On Unix-like systems, you may want to use your shell's alias functionality: alias zf.sh=path/to/ZendFramework/bin/zf.sh.

If you have problems setting up the zf command-line tool, please refer to the manual.

Open a terminal (in Windows, Start -> Run, and then use cmd). Navigate to a directory where you would like to start a project. Then, use the path to the appropriate script, and execute one of the following:

# Unix:

% zf.sh create project quickstart

# DOS/Windows:

C:> zf.bat create project quickstart

(47)

quickstart

|-- application

| |-- Bootstrap.php

| |-- configs

| | `-- application.ini | |-- controllers

| | |-- ErrorController.php | | `-- IndexController.php

| |-- models

| `-- views | |-- helpers | `-- scripts

| |-- error

| | `-- error.phtml | `-- index

| `-- index.phtml |-- library

|-- public

| `-- index.php

`-- tests

|-- application | `-- bootstrap.php |-- library

| `-- bootstrap.php `-- phpunit.xml

At this point, if you haven't added Zend Framework to your include_path, we recommend either copying or symlinking it into your library/ directory. In either case, you'll want to either recursively copy or symlink the library/Zend/ directory of your Zend Framework installation into the library/ directory of your project. On unix-like systems, that would look like one of the following:

# Symlink:

% cd library; ln -s path/to/ZendFramework/library/Zend .

# Copy:

% cd library; cp -r path/to/ZendFramework/library/Zend .

On Windows systems, it may be easiest to do this from the Explorer.

Now that the project is created, the main artifacts to begin understanding are the bootstrap, configuration, action controllers, and views.

2.3. The Bootstrap

Your Bootstrap class defines what resources and components to initialize. By default, Zend Framework's Front Controller is initialized, and it uses the application/controllers/ as the default directory in which to look for action controllers (more on that later). The class looks like the following:

// application/Bootstrap.php

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap

{ }

(48)

2.4. Configuration

While Zend Framework is itself configurationless, you often need to configure your application. The default configuration is placed in application/configs/application.ini, and contains some basic directives for setting your PHP environment (for instance, turning error reporting on and off), indicating the path to your bootstrap class (as well as its class name), and the path to your action controllers. It looks as follows:

; application/configs/application.ini

[production]

phpSettings.display_startup_errors = 0 phpSettings.display_errors = 0

includePaths.library = APPLICATION_PATH "/../library"

bootstrap.path = APPLICATION_PATH "/Bootstrap.php"

bootstrap.class = "Bootstrap"

resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"

[staging : production]

[testing : production]

phpSettings.display_startup_errors = 1 phpSettings.display_errors = 1

[development : production]

phpSettings.display_startup_errors = 1 phpSettings.display_errors = 1

Several things about this file should be noted. First, when using INI-style configuration, you can reference constants directly and expand them; APPLICATION_PATH is actually a constant. Additionally note that there are several sections defined: production, staging, testing, and development. The latter three inherit settings from the "production" environment. This is a useful way to organize configuration to ensure that appropriate settings are available in each stage of application development.

2.5. Action Controllers

Your application's action controllers contain your application workflow, and do the work of mapping your requests to the appropriate models and views.

An action controller should have one or more methods ending in "Action"; these methods may then be requested via the web. By default, Zend Framework URLs follow the schema /controller/action, where "controller" maps to the action controller name (minus the "Controller" suffix) and "action" maps to an action method (minus the "Action" suffix).

Typically, you always need an IndexController, which is a fallback controller and which also serves the home page of the site, and an ErrorController, which is used to indicate things such as HTTP 404 errors (controller or action not found) and HTTP 500 errors (application errors). The default IndexController is as follows:

// application/controllers/IndexController.php

class IndexController extends Zend_Controller_Action

{

(49)

{

/* Initialize action controller here */ }

public function indexAction() {

// action body }

}

And the default ErrorController is as follows: // application/controllers/ErrorController.php

class ErrorController extends Zend_Controller_Action

{

public function errorAction() {

$errors = $this->_getParam('error_handler'); switch ($errors->type) {

case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ROUTE: case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER: case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:

// 404 error -- controller or action not found $this->getResponse()->setHttpResponseCode(404); $this->view->message = 'Page not found';

break; default:

// application error

$this->getResponse()->setHttpResponseCode(500); $this->view->message = 'Application error'; break;

}

$this->view->exception = $errors->exception; $this->view->request = $errors->request; }

}

You'll note that (1) the IndexController contains no real code, and (2) the ErrorController makes reference to a "view" property. That leads nicely into our next subject.

2.6. Views

Views in Zend Framework are written in plain old PHP. View scripts are placed in application/ views/scripts/, where they are further categorized using the controller names. In our case, we have an IndexController and an ErrorController, and thus we have corresponding index/ and error/ subdirectories within our view scripts directory. Within these subdirectories, you will then find and create view scripts that correspond to each controller action exposed; in the default case, we thus have the view scripts index/index.phtml and error/error.phtml. View scripts may contain any markup you want, and use the <?php opening tag and ?> closing tag to insert PHP directives.

(50)

<!-- application/views/scripts/index/index.phtml -->

background-image: url(http://framework.zend.com/images/bkg_header.jpg); width: 600px;

div#more-information {

background-image: url(http://framework.zend.com/images/bkg_body-bottom.gif); height: 100%;

}

</style>

<div id="welcome">

<h1>Welcome to the <span id="zf-name">Zend Framework!</span><h1 /> <h3>This is your project's main page<h3 />

<div id="more-information"> <p>

<img src="http://framework.zend.com/images/PoweredBy_ZF_4LightBG.png" /> </p>

<p>

Helpful Links: <br />

<a href="http://framework.zend.com/">Zend Framework Website</a> | <a href="http://framework.zend.com/manual/en/">Zend Framework Manual</a> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"; "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd> <html xmlns="http://www.w3.org/1999/xhtml">

<head>

(51)

</head> <body>

<h1>An error occurred</h1>

<h2><?php echo $this->message ?></h2>

<?php if ('development' == $this->env): ?> <h3>Exception information:</h3>

<p>

<b>Message:</b> <?php echo $this->exception->getMessage() ?> </p>

<h3>Stack trace:</h3>

<pre><?php echo $this->exception->getTraceAsString() ?> </pre>

<h3>Request Parameters:</h3>

<pre><?php echo var_export($this->request->getParams(), 1) ?> </pre>

<?php endif ?> </body>

</html>

2.7. Checkpoint

At this point, you should be able to fire up your initial Zend Framework application. Create a virtual host in your web server, and point its document root to your application's public/ subdirectory. Make sure your host's name is in your DNS or hosts file, and then point your browser to it. You should be able to see a welcome page at this point.

3. Create A Layout

You may have noticed that the view scripts in the previous sections were HTML fragments- not complete pages. This is by design; we want our actions to return content only related to the action itself, not the application as a whole.

Now we must compose that generated content into a full HTML page. We'd also like to have a consistent look and feel for the application. We will use a global site layout to accomplish both of these tasks.

There are two design patterns that Zend Framework uses to implement layouts: Two Step View and Composite View. Two Step View is usually associated with the Transform View pattern; the basic idea is that your application view creates a representation that is then injected into the master view for final transformation. The Composite View pattern deals with a view made of one or more atomic, application views.

In Zend Framework, Zend_Layout combines the ideas behind these patterns. Instead of each action view script needing to include site-wide artifacts, they can simply focus on their own responsibilities.

Occasionally, however, you may need application-specific information in your site-wide view script. Fortunately, Zend Framework provides a variety of view placeholders to allow you to provide such information from your action view scripts.

(52)

; application/configs/application.ini

; Add to [production] section:

resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts"

The final INI file should look as follows:

; application/configs/application.ini

[production]

; PHP settings we want to initialize phpSettings.display_startup_errors = 0 phpSettings.display_errors = 0

includePaths.library = APPLICATION_PATH "/../library"

bootstrap.path = APPLICATION_PATH "/Bootstrap.php"

bootstrap.class = "Bootstrap"

resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"

resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts"

[staging : production]

[testing : production]

phpSettings.display_startup_errors = 1 phpSettings.display_errors = 1

[development : production]

phpSettings.display_startup_errors = 1 phpSettings.display_errors = 1

This directive tells your application to look for layout view scripts in application/layouts/ scripts. Create those directories now.

We also want to ensure we have an XHTML DocType declaration for our application. To enable this, we need to add a resource to our bootstrap.

The simplest way to add a bootstrap resource is to simply create a protected method beginning with the phrase _init. In this case, we want to initialize the doctype, so we'll create an _initDoctype() method within our bootstrap class:

// application/Bootstrap.php

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap

{

protected function _initDoctype() {

} }

Within that method, we need to hint to the view to use the appropriate doctype. But where will the view object come from? The easy solution is to initialize the View resource; once we have, we can pull the view object from the bootstrap and use it.

To initialize the view resource, add the following line to your application/configs/ application.ini file, in the section marked production:

(53)

; Add to [production] section:

resources.view[] =

This tells us to initialize the view with no options (the '[]' indicates that the "view" key is an array, and we pass nothing to it).

Now that we have a view, let's flesh out our _initDoctype() method. In it, we will first ensure the View resource has run, fetch the view object, and then configure it:

// application/Bootstrap.php

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap

{

protected function _initDoctype() {

$this->bootstrap('view');

$view = $this->getResource('view'); $view->doctype('XHTML1_STRICT'); }

}

Now that we've initialized Zend_Layout and set the Doctype, let's create our site-wide layout: // application/layouts/scripts/layout.phtml

echo $this->doctype() ?>

<html xmlns="http://www.w3.org/1999/xhtml"> <head>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Zend Framework Quickstart Application</title>

<?php echo $this->headLink()->appendStylesheet('/css/global.css') ?> </head>

<body>

<div id="header" style="background-color: #EEEEEE; height: 30px;"> <div id="header-logo" style="float: left">

<b>ZF Quickstart Application</b> </div>

<div id="header-navigation" style="float: right"> <a href="<?php echo $this->url(

array('controller'=>'guestbook'), 'default',

true) ?>">Guestbook</a> </div>

</div>

<?php echo $this->layout()->content ?> </body>

</html>

We grab our application content using the layout() view helper, and accessing the "content" key. You may render to other response segments if you wish to, but in most cases, this is all that's necessary.

(54)

Checkpoint

Now go to "http://localhost" and check out the source. You should see your XHTML header, head, title, and body sections.

4. Create a Model and Database Table

Before we get started, let's consider something: where will these classes live, and how will we find them? The default project we created instantiates an autoloader. We can attach other autoloaders to it so that it knows where to find different classes. Typically, we want our various MVC classes grouped under the same tree -- in this case, application/ -- and most often using a common prefix.

Zend_Controller_Front has a notion of "modules", which are individual mini-applications. Modules mimic the directory structure that the zf tool sets up under application/, and all classes inside them are assumed to begin with a common prefix, the module name. application/ is itself a module -- the "default" or "application" module. As such, we'll want to setup autoloading for resources within this directory.

Zend_Application_Module_Autoloader provides the functionality needed to map the various resources under a module to the appropriate directories, and provides a standard naming mechanism as well. An instance of the class is created by default during initialization of the bootstrap object; your application bootstrap will be default use the module prefix "Application". As such, our models, forms, and table classes will all begin with the class prefix "Application_". Now, let's consider what makes up a guestbook. Typically, they are simply a list of entries with a comment, timestamp, and, often, email address. Assuming we store them in a database, we may also want a unique identifier for each entry. We'll likely want to be able to save an entry, fetch individual entries, and retrieve all entries. As such, a simple guestbook model API might look something like this:

// application/models/Guestbook.php

class Application_Model_Guestbook

{

protected $_comment; protected $_created; protected $_email; protected $_id;

public function __set($name, $value); public function __get($name);

public function setComment($text); public function getComment();

public function setEmail($email); public function getEmail();

public function setCreated($ts); public function getCreated();

public function setId($id); public function getId();

(55)

public function fetchAll(); }

__get() and __set() will provide a convenience mechanism for us to access the individual entry properties, and proxy to the other getters and setters. They also will help ensure that only properties we whitelist will be available in the object.

find() and fetchAll() provide the ability to fetch a single entry or all entries. Now from here, we can start thinking about setting up our database.

First we need to initialize our Db resource. As with the Layout and View resource, we can provide configuration for the Db resource. In your application/configs/ application.ini file, add the following lines in the appropriate sections.

; application/configs/application.ini

; Add these lines to the appropriate sections: [production]

resources.db.adapter = "PDO_SQLITE"

resources.db.params.dbname = APPLICATION_PATH "/../data/db/guestbook.db"

[testing : production]

resources.db.params.dbname = APPLICATION_PATH "/../data/db/guestbook-testing.db"

[development : production]

resources.db.params.dbname = APPLICATION_PATH "/../data/db/guestbook-dev.db"

Your final configuration file should look like the following:

; application/configs/application.ini

[production]

phpSettings.display_startup_errors = 0 phpSettings.display_errors = 0

bootstrap.path = APPLICATION_PATH "/Bootstrap.php"

bootstrap.class = "Bootstrap"

resources.frontController.controllerDirectory = APPLICATION_PATH "/controllers"

resources.layout.layoutPath = APPLICATION_PATH "/layouts/scripts"

resources.view[] =

resources.db.adapter = "PDO_SQLITE"

resources.db.params.dbname = APPLICATION_PATH "/../data/db/guestbook.db"

[staging : production]

[testing : production]

phpSettings.display_startup_errors = 1 phpSettings.display_errors = 1

resources.db.params.dbname = APPLICATION_PATH "/../data/db/guestbook-testing.db"

[development : production]

phpSettings.display_startup_errors = 1 phpSettings.display_errors = 1

resources.db.params.dbname = APPLICATION_PATH "/../data/db/guestbook-dev.db"

Note that the database(s) will be stored in data/db/. Create those directories, and make them world-writeable. On unix-like systems, you can do that as follows:

(56)

On Windows, you will need to create the directories in Explorer and set the permissions to allow anyone to write to the directory.

At this point we have a connection to a database; in our case, its a connection to a Sqlite database located inside our application/data/ directory. So, let's design a simple table that will hold our guestbook entries.

-- scripts/schema.sqlite.sql

---- You will need load your database schema with this SQL.

CREATE TABLE guestbook (

id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT,

email VARCHAR(32) NOT NULL DEFAULT '[email protected]', comment TEXT NULL,

created DATETIME NOT NULL

);

CREATE INDEX "id" ON "guestbook" ("id");

And, so that we can have some working data out of the box, lets create a few rows of information to make our application interesting.

-- scripts/data.sqlite.sql

---- You can begin populating the database with the following SQL statements.

INSERT INTO guestbook (email, comment, created) VALUES ('[email protected]',

'Hello! Hope you enjoy this sample zf application!', DATETIME('NOW'));

INSERT INTO guestbook (email, comment, created) VALUES ('[email protected]',

'Baz baz baz, baz baz Baz baz baz - baz baz baz.', DATETIME('NOW'));

Now that we have both the schema and some data defined. Lets get a script together that we can now execute to build this database. Naturally, this is not needed in production, but this script will help developers build out the database requirements locally so they can have the fully working application. Create the script as scripts/load.sqlite.php with the following contents: // scripts/load.sqlite.php

/**

* Script for creating and loading database */

// Initialize the application path and autoloading defined('APPLICATION_PATH')

|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));

set_include_path(implode(PATH_SEPARATOR, array( APPLICATION_PATH . '/../library',

get_include_path(), )));

require_once 'Zend/Loader/Autoloader.php';

Zend_Loader_Autoloader::getInstance();

Gambar

Table 4. Zend_Application_Bootstrap_Bootstrapper Interface
Table 6. Zend_Application_Bootstrap_BootstrapAbstract Methods
Table 7. Zend_Application_Resource_Resource Interface
Table 10. Server Options
+7

Referensi

Dokumen terkait