Tải bản đầy đủ (.pdf) (486 trang)

Tài liệu The Professional''''s Guide to Programming Joomla ppt

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (11.65 MB, 486 trang )


Mastering Joomla! 1.5
Extension and Framework
Development
The Professional's Guide to Programming
Joomla!
James Kennard
BIRMINGHAM - MUMBAI
Mastering Joomla! 1.5 Extension and Framework
Development
The Professional's Guide to Programming Joomla!
Copyright © 2007 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval
system, or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embedded in
critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of
the information presented. However, the information contained in this book is sold
without warranty, either express or implied. Neither the author, Packt Publishing,
nor its dealers or distributors will be held liable for any damages caused or alleged to
be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all the
companies and products mentioned in this book by the appropriate use of capitals.
However, Packt Publishing cannot guarantee the accuracy of this information.
First published: November 2007
Production Reference: 1311007
Published by Packt Publishing Ltd.
32 Lincoln Road
Olton
Birmingham, B27 6PA, UK.
ISBN 978-1-84719-282-0


www.packtpub.com
Cover Image by Vinayak Chittar (

)
Credits
Author
James Kennard
Reviewers
Joseph L. LeBlanc
Riccardo Tacconi
Senior Acquisition Editor
Douglas Paterson
Development Editor
Rashmi Phadnis
Technical Editors
Adil Rizwan Ahmed
Ved Prakash Jha
Editorial Manager
Dipali Chittar
Project Manager
Abhijeet Deobhakta
Indexer
Hemangini Bari
Proofreader
Chris Smith
Production Coordinator
Manjiri Nadkarni
Cover Designer
Shantanu Zagade
About the Author

James Kennard
is a computer programmer with a particular interest in web-based
services. His interests in Joomla! started as a result of an internal assignment at work
when he was tasked with identifying suitable web systems to host a number of
intranet and Internet applications.
James currently maintains one open-source Joomla! component, which has been
translated into over fteen languages. Examples of his work can be found on his
personal website:
www.webamoeba.co.uk
.
About the Reviewers
Joseph L. LeBlanc
started with computers at a very young age. His independent
education gave him the exibility to experiment and learn computer science. Joseph
holds a bachelor's degree in Management Information Systems from the Oral
Roberts University.
Joseph is currently a freelance Joomla! extension developer. He released a popular
component tutorial in May 2004, then later authored the book Learning Joomla! 1.5
Extension Development: Creating Modules, Components, and Plugins with PHP. Work
samples and open-source extensions are available at
www.jlleblanc.com
. In
addition to freelancing, he is a board member of the DC PHP Conference. He has
also worked as a programmer for a web communications rm in Washington, DC.
Riccardo Tacconi
works for an Italian company as a system administrator and
web developer using PHP, MySQL, and Oracle. He is an MCP and studies IT
part-time at the British Open University. His main interests are web development,
Windows and Linux administration, Robotics, and Java software development (JMF,
motion detection, CV, and distributed systems).

He loves Linux and he is a proud member of the local Linux User Group: GROLUG.
He tries to innovate ways to substitute Windows-based technologies with Linux and
open-source alternatives.

Table of Contents
Preface 1
Chapter 1: Introduction to Joomla! 7
Overview 7
History 8
Requirements 9
Extension Types and Their Uses 9
Components 10
Modules 10
Plugins 10
Languages 11
Templates 11
Tools 11
Extension Manager 12
JED and JoomlaCode.org 12
Development Tools 13
J!Code 14
J!Dump 14
Summary 16
Chapter 2: Getting Started 17
The Application and Document 17
Request to Response 18
The Process 18
URI Structure 22
Directory Structure 24
Libraries 26

A Quick Lesson in Classes 27
Inheriting from JObject 28
Table of Contents
[
ii
]
Working with the Request 29
The Factory 30
The Session 31
Predefined Constants 32
Multilingual Support 34
UTF-8 String Handling 34
Coding Standards 36
phpDocumentor 37
Summary 39
Chapter 3: The Database 41
The Core Database 41
Extending the Database 42
Table Prefix 42
Schema Conventions 42
Common Fields 42
Schema Example 44
Dealing with Multilingual Requirements 45
Querying the Database 46
Writing Queries 46
Getting Results 47
loadResult( ) : string 48
loadResultArray( numinarray : int=0 ) : array 48
loadAssoc( ) : array 48
loadAssocList( key : string='' ) : array 49

loadObject( ) : stdClass 49
loadObjectList( key : string='' ) : array 50
loadRow( ) : array 50
loadRowList( key : int ) : array 51
Using ADOdb 51
JTable 52
CRUD 54
Manipulating Common Fields 58
Publishing 59
Hits 59
Checking Out 59
Ordering 60
Parameter Fields 61
Date Fields 62
Summary 63
Chapter 4: Component Design 65
Setting up a Sandbox 65
The Structure 67
Table of Contents
[
iii
]
The MVC 68
Building a Model 70
Building a View 75
Building a Controller 78
Building an MVC Component 82
Rendering Other Document Types 87
Feed 87
PDF 90

Raw 91
Dealing with Component Configuration 93
Elements and Parameters 95
Extending JElement 96
Using Custom JElement Classes 98
Help Files 99
Routing 100
Packaging 102
XML Manifest File 103
SQL Install and Uninstall Files and Queries 110
Install and Uninstall Files 111
Summary 113
Chapter 5: Module Design 115
Setting Up a Sandbox 115
First Steps 116
Standalone Modules 117
Modules and Components Working Together 118
Frontend and Backend Module Display Positions 119
Module Settings (Parameters) 120
Helpers 121
Layouts (Templates) 124
Media 126
Translating 126
Packaging 127
XML Manifest File 127
Summary 131
Chapter 6: Plugin Design 133
Setting Up a Sandbox 134
Events 136
Listeners 138

Registering Listeners 138
Handling Events 138
Table of Contents
[
iv
]
Plugin Groups 141
Authentication 142
Content 144
Editors 146
Editors-xtd 148
Search 151
System 152
User 152
XML-RPC 155
Loading Plugins 155
Using Plugins as Libraries (in Lieu of Library Extensions) 156
Translating Plugins 159
Dealing with Plugin Settings (Parameters) 160
Packaging 161
XML Manifest File 162
File Naming Conflicts 165
Summary 165
Chapter 7: Extension Design 167
Supporting Classes 167
Helpers 168
Using and Building getInstance() Methods 169
Using the Registry 174
Saving and Loading Registry Values 175
The User 177

User Parameters 178
The Session 184
The Browser 185
Assets 189
Summary 190
Chapter 8: Rendering Output 193
The joomla.html Library 193
Behavior 196
Email 200
Grid 200
Image 203
List 204
Menu 208
Select 209
Building Component HTML Layouts (Templates) 212
Iterative Templates 213
Table of Contents
[
v
]
Component Backend 214
Admin Form 215
Toolbar 216
Sub-Menu 222
Itemized Data 224
Pagination 224
Ordering 228
Filtering and Searching 231
Summary 241
Chapter 9: Customizing the Page 243

Application Message Queue 243
Redirects 245
Component XML Metadata Files and Menu Parameters 248
Using Menu Item Parameters 257
Modifying the Document 258
Page Title 259
Pathway/Breadcrumb 259
JavaScript 261
CSS 262
Metadata 263
Custom Header Tags 263
Translating 264
Translating Text 264
Defining Translations 265
Debugging Translations 267
Using JavaScript Effects 268
JPane 268
Tooltips 269
Fx.Slide 271
Summary 275
Chapter 10: APIs and Web Services 277
XML 277
Parsing 278
Editing 282
Saving 283
AJAX 284
Response 284
Request 286
LDAP 290
Email 294

Table of Contents
[
vi
]
File Transfer Protocol 297
Web Services 299
Building a Web Service (XML-RPC Plugin) 301
Summary 309
Chapter 11: Error Handling and Security 311
Errors, Warnings, and Notices 312
Return Values 313
Customizing Error Handling 314
Dealing with CGI Request Data 315
Preprocessing CGI Data 315
Escaping and Encoding Data 317
Escaping and Quoting Database Data 318
Encode XHTML Data 319
Regular Expressions 320
Patterns 320
Matching 322
Replacing 323
Access Control 323
Menu Item Access Control 325
Extension Access Control 325
Attacks 327
How to Avoid Common Attacks 328
Using the Session Token 328
Code Injection 329
XSS (Cross Site Scripting) 331
File System Snooping 332

Dealing with Attacks 332
Log Out and Block 333
Attack Logging 335
Notify the Site Administrator 336
Summary 337
Chapter 12: Utilities and Useful Classes 339
Dates 340
File System 345
Paths 345
Folders 347
Files 351
Archives 354
Arrays 355
Trees 359
Log Files 361
Summary 364
Table of Contents
[
vii
]
Appendix 365
Classes 365
JObject 366
Properties 366
Constructors 366
Methods 367
JUser 368
Properties 368
Constructors 369
Methods 369

JModel 372
Properties 372
Constructors 372
Methods 372
JView 374
Properties 375
Constructors 375
Methods 375
JController 378
Properties 379
Constructors 379
Methods 379
JTable 383
Properties 383
Constructors 383
Methods 384
JError 388
Methods 388
JDocument 393
Properties 393
Constructors 393
Methods 394
JApplication 398
Properties 398
Constructors 399
Methods 399
JURI 407
Properties 407
Constructors 407
Methods 407

JLanguage 411
Properties 411
Constructors 411
Methods 412
JLanguageHelper 416
Methods 416
Table of Contents
[
viii
]
JText 417
Methods 417
JElement 417
Properties 418
Constructors 418
Methods 418
JParameter 419
Properties 419
Constructors 419
Methods 420
JCache 422
Properties 422
Constructors 423
Methods 423
JMail 424
Constructors 425
Methods 425
JMailHelper 427
Methods 427
JFactory 428

Methods 428
JRegistry 431
Properties 431
Constructors 431
Methods 431
JSession 434
Properties 434
Constructors 434
Methods 435
JRoute 438
Methods 438
JMenu 438
Properties 438
Constructors 439
Methods 439
JPathway 441
Properties 441
Methods 441
JDatabase 442
Properties 442
Constructors 443
Methods 443
Parameters (Core JElements) 452
Configuration 455
Index 459
Preface
This book will guide you through the complexities of implementing components,
modules, and plugins in Joomla! 1.5. It provides useful reference material that
explains many of the advanced design features and classes available in Joomla! 1.5.
Joomla! is one of the world's top open-source content management systems. The

main sources of the PHP MySQL application's success are its comprehensive
extension libraries, which extend Joomla! far beyond content management, and its
very active forums where one can easily tap into the knowledge of other Joomla!
users, administrators, and developers.
The architecture of the latest version of Joomla! differs in many ways from previous
versions. Resultantly backward-compatibility with some extensions has been broken;
the race is on for developers to update their skills in order to rectify the problems
and start building new extensions. Perhaps the most important of the changes is the
reorganization and classication of les and classes. This change encourages but does
not force developers to use the Joomla! libraries consistently between extensions.
What This Book Covers
Chapter 1 deals with the history of Joomla! and gives an overview of the technology
in general.
Chapter 2 covers the process from request to response and also talks about directory
and URI structure along with a brief description of libraries. It also introduces a
number of common classes, variables, and constants that are used frequently when
creating Joomla! extensions.
Chapter 3 deals with the database. It talks about extending the database, conventions
for the database schema, and common elds. Then the focus moves on to storing
data common types of data in standard elds and dealing with multilingual
requirements. We then cover querying the database and getting results.
Preface
[
2
]
Next, the chapter explores how to manipulate common eld types. The chapter
concludes with a brief description of the JTable. The JTable is used to display and
edit regular two-dimensional tables of cells. The JTable has many facilities that make
it possible to customize its rendering and editing but provides defaults for these
features so that simple tables can be set up easily.

Chapter 4 is about designing components. It starts with the structure and a basic
design of a component using the MVC design pattern. Then we learn conguring
the component and its various elements and parameters. The chapter nishes by
discussing component packaging and the various install and uninstall les.
Chapter 5 covers designing modules. It explains standalone modules, module
settings, frontend and backend modules, and modules and components working
together. Then we talk about using templates and packaging the modules.
Chapter 6 deals with designing plugins. It initially deals with listeners/observers
and then the various plugin groups like authentication, content editors, search, and
others. Then comes loading, translating, and using plugins as libraries. Finally it
deals with, plugin settings and how to package plugins.
Chapter 7 is all about designing extensions. Here, we start with helper classes then
cover building and using
getInstance()
methods. Then we cover the registry along
with saving and loading registry values. Towards the end of the chapter, we explain
the User, Session, Browser and the assets.
Chapter 8 explains ways to render output and how to maintain consistency
throughout. It starts with the
joomla.html
library and then continues to describe
how to build component HTML layouts. Then it discusses how to output the backend
of a component. The chapter ends with the details of itemized data and pagination.
Chapter 9 deals with customizing the page. We cover things like modifying the
document and translating, along with a brief explanation of using JavaScript effects
from the mootools library, which is included in Joomla!.
Chapter 10 explores some of the Joomla! APIs, specically in relation to web services.
We also discuss some of the more common web services and take a more in-depth
look at the Yahoo! Search API. The chapter nishes by describing how we can create
our own web services using plugins.

Chapter 11 provides an introduction to handling and throwing errors, warnings, and
notices. Further, it talks about building secure Joomla! extensions. It also describes a
number of common mistakes made when coding with Joomla! and explains how to
avoid them.
Chapter 12 explains various utilities and useful classes like dates, arrays, tree
structures, and others.
Preface
[
3
]
The Appendix details the more common Joomla! classes. It also provides information
on how to handle the ever-useful JParameter object. The appendix ends with a
description of the Joomla! settings in relation to the registry/cong.
What You Need for This Book
To use this book effectively you need access to a Joomla! 1.5 installation. In order
to run Joomla! 1.5 you need the following software: PHP 4.3 or higher (4.4.3 or
greater is recommended), MySQL 3.23 or higher and Apache 1.3 or higher or an
equivalent webserver.
Conventions
In this book, you will nd a number of styles of text that distinguish between
different kinds of information. Here are some examples of these styles, and an
explanation of their meaning.
There are two styles for code. Code words in text are shown as follows: "When
we populate the
$oldValue
variable using the
getValue()
method we supply a
second parameter."
A block of code will be set as follows:

$user =& JFactory::getUser();
if ($user->guest)
{
// user is a guest (is not logged in)
}
New terms and important words are introduced in a bold-type font. Words that you
see on the screen, in menus or dialog boxes for example, appear in our text like this:
"In the System tab we must set Debug Language to Yes".
Warnings or important notes appear in a box like this.
Tips and tricks appear like this.
Preface
[
4
]
Reader Feedback
Feedback from our readers is always welcome. Let us know what you think about
this book, what you liked or may have disliked. Reader feedback is important for us
to develop titles that you really get the most out of.
To send us general feedback, simply drop an email to

,
making sure to mention the book title in the subject of your message.
If there is a book that you need and would like to see us publish, please send us a
note in the SUGGEST A TITLE form on
www.packtpub.com
or email
suggest@
packtpub.com
.
If there is a topic that you have expertise in and you are interested in either writing

or contributing to a book, see our author guide on
www.packtpub.com/authors
.
Customer Support
Now that you are the proud owner of a Packt book, we have a number of things to
help you to get the most from your purchase.
Downloading the Example Code for the Book
Visit
/>, and select this book from the list of titles
to download any example code or extra resources for this book. The les available
for download will then be displayed.
The downloadable les contain instructions on how to
use them.
Errata
Although we have taken every care to ensure the accuracy of our contents, mistakes
do happen. If you nd a mistake in one of our books—maybe a mistake in text or
code—we would be grateful if you would report this to us. By doing this you can
save other readers from frustration, and help to improve subsequent versions of
this book. If you nd any errata, report them by visiting
ktpub.
com/support
, selecting your book, clicking on the Submit Errata link, and entering
the details of your errata. Once your errata are veried, your submission will be
accepted and the errata added to the list of existing errata. The existing errata can be
viewed by selecting your title from
/>.
Preface
[
5
]

Questions
You can contact us at

if you are having a problem with
some aspect of the book, and we will do our best to address it.

Introduction to Joomla!
This book is intended for use as a reference book for existing Joomla! developers.
It focuses on the Joomla! framework and how to utilize it to enhance and
standardize extensions.
Overview
Joomla! is a modular and extensible PHP MySQL CMS (Content Management
System). Joomla! is an open-source project, which is released under version 2 of the
GPL license. Joomla! has fast become one of the most popular open-source CMS, as is
proved by its numerous awards and massive online community.
One of the things that has made Joomla! so popular is the large number of freely and
commercially available extensions, which enable users to do far more than simply
manage content. This list details some common functions that extensions perform:
Banner Ads & Afliates
Calendars
Communication (Chat Rooms, Forums, Guest Books, Mailing Lists,
Newsletters)
Content & News (Blogs, eCards, News)
Documentation (Downloads, FAQs, Wikis)
eCommerce (Auctions, Shopping Carts)
Forms
Gallery & Multimedia
Intranet & Groupware
Search & Indexing











Introduction to Joomla!
[
8
]
History
Rice Studios, formerly Miro, created a closed-source CMS called 'Mambo' in the
year 2000. One year later, Mambo was re-licensed under two separate licenses,
one of which was open source. The open-source version became known as 'Mambo
Site Server'.
In 2002 Mambo Site Server was re-branded 'Mambo Open Source' (Also referred to
as MamboOS or MOS) in an attempt to differentiate the commercial and open-source
avors of Mambo. All rights to Mambo Open Source were ofcially released into the
open-source community in 2003.
Mambo Open Source was extremely successful and won a large number of
prestigious open-source awards.
In 2005 the commercial version of Mambo was re-branded as 'Jango'. Rice Studios,
at that time still Miro, also chose to form the Mambo Foundation, a non-prot
organization. The intention was to create a body that would help protect the
principles of Mambo and provide a more structured working methodology.
The creation of the Mambo Foundation created a rift in the Mambo Open Source
community. The creation of the Mambo Foundation was seen by many as an attempt

by Rice Studios to gain control of the Mambo Open Source project.
Not long after the Mambo Foundation was created, a group, consisting mainly of
the Mambo Open Source core developers, publicly announced that they intended to
abandon Mambo Open Source. The group formed a non-prot organization called
'Open Source Matters'.
Open Source Matters created the Joomla! project, a guaranteed 100% open-source
GPL project. The rst release of Joomla! (Joomla! 1.0) was very similar to the then
current release of Mambo, the majority of extensions at the time being compatible
with both.
Restraints within Joomla! 1.0 led to a complete re-think of how Joomla! should be
constructed. After a long development period, and two beta releases, Joomla! 1.5 was
released in mid 2007.
Joomla! 1.5 is extensively different to Joomla! 1.0 and Mambo. Joomla! 1.5 introduces
many new classes and implements a comprehensive framework. These changes have
lead to reduced compatibility between Joomla! and Mambo.
The most notable change, for most third-party extension developers, is the
introduction of the MVC (Model View Controller) design pattern in components.
These changes now mean that all third-party developers tend to develop for Joomla!
or Mambo, but not both.
Chapter 1
[
9
]
Requirements
To use Joomla! and develop new extensions there are a number of basic
requirements. This list details the minimum requirements:
MySQL 3.23 available at

PHP 4.3 available at


A web server (if using Apache, minimum version is 1.13.19, which is
available at

)
Precise version requirements may differ depending upon the exact
version of Joomla! that is being used.
An easy way to quickly obtain and install all of these is to use XAMPP (X, Apache,
MySQL, PHP, and Perl). This project packages all of the necessary pieces of software
required to run Joomla! in one installation package. XAMPP is available for the
Linux, Mac, Solaris, and Windows operating systems. To learn more about XAMPP
please refer to
/>.
Another easy way to get started with Joomla! is to use JSAS (Joomla! Stand
Alone Server). JSAS enables us to quickly set up multiple Joomla! installations
on a Windows-based system. To learn more about JSAS please refer to

.
Joomla! itself is relatively easy to set up and, if necessary, an administration
and installation guide can be found on the ofcial Joomla! help site:

.
Whenever we are developing extensions for Joomla! it is always good
practice to test the extensions on multiple systems. Extensions should
preferably be tested on Windows and Linux systems and tested using
PHP 4 and PHP 5.
Extension Types and Their Uses
A Joomla! extension is anything that extends Joomla!'s functionality beyond the core.
There are three main types of extension: components, modules, and plugins.
There are also languages and templates, but these are solely designed to modify
page output, irrespective of the data being displayed. Although we will discuss the

use of translation les and templates, we will not explicitly cover these two extension
types in this book.



Introduction to Joomla!
[
10
]
Tools, sometimes referred to as extensions, are essentially any type of extension
that does not fall into the extension type categories just described. We will not be
discussing how to create tools in this book.
Extensions are distributed in archive les, which include an XML manifest le that
describes the extension. It is from the manifest le that Joomla! is able to determine
what type the extension is, what it is called, what les are included, and what
installation procedures are required.
Components
Components are undoubtedly the most fundamental Joomla! extensions. Whenever
Joomla! is invoked a component is always called upon. Unlike other extensions,
output created by a component is displayed in the main content area. Since
components are the most fundamental extension, they are also generally the
most complex.
One component of which all Joomla! administrators will be aware, is the content
component. This component is used to display articles, content categories, and
content sections.
In addition to outputting component data as part of an XHTML page, we can output
component data as Feeds, PDF, and RAW documents.
Many components tend to include, and sometimes require, additional extensions
in order for them to behave as expected. When we create our own components
it is generally good practice to add 'hooks' in our code, which will enable other

extensions to easily enhance our component beyond its base functionality.
Modules
Modules are used to display small pieces of content, usually to the left, right, top or
bottom of a rendered page. There are a number of core modules with which we will
be instantly familiar, for example the menu modules.
Plugins
There are various types of plugin, each of which can be used differently; however,
most plugins are event driven. Plugins can attach listener functions and classes to
specic events that Joomla! can throw using the global event dispatcher.

×