Vous êtes sur la page 1sur 52
Licensed to: Joseph Crawford User #63883 info@josephcrawford.com
Licensed to: Joseph Crawford User #63883
Licensed to:
Joseph Crawford
User #63883
Licensed to: Joseph Crawford User #63883 info@josephcrawford.com
Licensed to: Joseph Crawford User #63883 info@josephcrawford.com
Licensed to: Joseph Crawford User #63883 info@josephcrawford.com
Licensed to: Joseph Crawford User #63883 info@josephcrawford.com
Licensed to: Joseph Crawford User #63883 info@josephcrawford.com
Licensed to: Joseph Crawford User #63883 info@josephcrawford.com
Licensed to: Joseph Crawford User #63883 info@josephcrawford.com
Licensed to: Joseph Crawford User #63883 info@josephcrawford.com
Licensed to: Joseph Crawford User #63883 info@josephcrawford.com

info@josephcrawford.com

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)
Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)
Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)
Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) CONTENTS February 2009 FeaTureS 13 20 28 33 41
Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) CONTENTS February 2009 FeaTureS 13 20 28 33 41
Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) CONTENTS February 2009 FeaTureS 13 20 28 33 41
Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) CONTENTS February 2009 FeaTureS 13 20 28 33 41

CONTENTS

February 2009

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) CONTENTS February 2009 FeaTureS 13 20 28 33 41
Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) CONTENTS February 2009 FeaTureS 13 20 28 33 41
Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) CONTENTS February 2009 FeaTureS 13 20 28 33 41

FeaTureS

13 20 28
13
20
28
33 41
33
41
VCL for PHP

VCL for PHP

VCL, PHP and a Visual IDE for the win

José León Serna Richard Bates Ricky Robinett
José León Serna
Richard Bates
Ricky Robinett

Matthew Weier O'Phinney

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) CONTENTS February 2009 FeaTureS 13 20 28 33 41
Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) CONTENTS February 2009 FeaTureS 13 20 28 33 41
Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) CONTENTS February 2009 FeaTureS 13 20 28 33 41

Rich Internet Applications with Flex and PHP: Part 1

Enrich your PHP applications with Flex

Enrich your PHP applications with Flex

Taking the Desktop Back

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) CONTENTS February 2009 FeaTureS 13 20 28 33 41

Creating Desktop RIAs using PHP and Adobe AIR

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) CONTENTS February 2009 FeaTureS 13 20 28 33 41

Optimizing Dojo and Zend Framework Integration

Built-in support makes Ajax a breeze.

Grokking the REST Architectural Style

Ben Ramsey Elizabeth Tucker Long Helgi Þormar Þorbjörnsson Ivo Jansch Arne Blankerts Marco Tabini
Ben Ramsey
Elizabeth Tucker Long
Helgi Þormar Þorbjörnsson
Ivo Jansch
Arne Blankerts
Marco Tabini

Discover the crucial principles of the REST style.

COLuMNS

4
4

6

Editorial

8

New Kid on the Block

ElePHPants!

PEAR Corner

Version Naming

Enterprise PHP

  • 10 Technical Design

Security Roundup
48

Securing Software & File Uploads

exit(0);
50

My Way or the UNIX Way

Download this month’s code at: http://phparch.com/code

WRITE FOR US!

If you want to bring a PHP-related topic to the attention of the professional PHP community, whether it is personal research, company software, or anything else, why not write an article for php|architect? If you would like to contribute, contact us, and one of our editors will be happy to help you hone your idea and turn it into a beautiful article for our magazine. Visit www.phparch. com/writeforus.php or contact our editorial team at write@phparch.com and get started!

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)

EDITORIAL

Round Two

by Elizabeth Tucker Long

W elcome to the February edition of php|architect. I just want to say a quick thanks to everyone who sent us feedback on the new layout and

features in the January issue. If that wasn’t you, there’s still time to

send us your comments:

• E-mail me directly: beth@phparch.com • E-mail us in general: info@phparch.com • Post in our forums: http://c7y-bb.phparchitect.com

We appreciate all of the feedback that we get, so be sure to keep it coming.

Don’t forget, if you are involved in a PHP or Python user group, we want to add your group to our directory, so be sure to e-mail beth@phparch.com with “PHP User Group Info” in the subject line. This month, we are focusing on adding a little spice to your PHP develop- ment. Take a tour of RIA development with Flex and PHP with Richard Bates while Matthew Weier O’Phinney shows us how a partnership between Zend and Dojo is making RIA development even easier. José León Serna introduces us to VCL which brings php into the visual IDE world, and Chris Cornutt makes a strong case for using CodeIgniter as your framework of choice. If you’d like to branch out into desktop applications, Ricky Robinett walks us through display- ing database information in a desktop application using PHP and AIR. Helgi Þormar Þorbjörnsson discusses PEAR’s contribution to naming conventions, and Arne Blankerts provides some simple tips to protect our users from cross-site scripting attacks. Ben Ramsey sets the record straight on the requirements for RESTful applications, Ivo Jansch outlines how more time spent in the technical design phase of a project can save you a huge headache later on, and Marco finally tries out his iPhone.

I hope you enjoy this month’s issue!

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) EDITORIAL Round Two by Elizabeth Tucker Long W elcomeb e t h @ p h p a r c h . c o m • E-mail us in general: i n f o @ p h p a r c h . c o m • Post in our forums: http://c7y-bb.phparchitect.com We appreciate all of the feedback that we get, so be sure to keep it coming. Don’t forget, if you are involved in a PHP or Python user group, we want to add your group to our directory, so be sure to e-mail b e t h @ p h p a r c h . c o m with “PHP User Group Info” in the subject line. This month, we are focusing on adding a little spice to your PHP develop- ment. Take a tour of RIA development with Flex and PHP with Richard Bates while Matthew Weier O’Phinney shows us how a partnership between Zend and Dojo is making RIA development even easier. José León Serna introduces us to VCL which brings php into the visual IDE world, and Chris Cornutt makes a strong case for using CodeIgniter as your framework of choice. If you’d like to branch out into desktop applications, Ricky Robinett walks us through display- ing database information in a desktop application using PHP and AIR. Helgi Þormar Þorbjörnsson discusses PEAR’s contribution to naming conventions, and Arne Blankerts provides some simple tips to protect our users from cross-site scripting attacks. Ben Ramsey sets the record straight on the requirements for RESTful applications, Ivo Jansch outlines how more time spent in the technical design phase of a project can save you a huge headache later on, and Marco finally tries out his iPhone. I hope you enjoy this month’s issue! What's New at Python Magazine Learn more at: http://pythonmagazine.com February 2009 Topics: • Mock testing techniques and tools (Grig Gheorghiu) • Creating a collection manager with Elixir (Gaëtan de Menten) • Multiple Documents on PyObjC (JC Cruz) • Using Python for Pedigree Analysis (John B. Cole, PhD) • Co-designing with web.py: Urban Mediator (Roman Suzi, Joanna Saad-Sulonen, Andrea Botero) • Simple File Input and Output (Mark Mruss) • Universal Newlines Ate My File: A Cautionary Tale 4 | February 2009 www.phparch.com February 2009 Volume 8 - Issue 2 Publisher Arbi Arzoumani Editor-in-Chief Elizabeth Tucker Long Author Liaison Elizabeth Naramore Cathleen MacIsaac Technical Editors Steph Fox Simon Harris Matthew Turland Clark Everetts Graphics & Layout Arbi Arzoumani Managing Editor Arbi Arzoumani Authors Richard Bates, Arne Blankerts, Chris Cornutt, Ivo Jansch, Matthew Weier O'Phinney, Ben Ramsey, Ricky Robinett, José León Serna, Marco Tabini, Helgi Þormar Þorbjörnsson php|architect (ISSN 1709-7169) is published twelve times a year by Marco Tabini & Associates, Inc., 28 Bombay Ave., Toronto, ON M3H1B7, Canada. Although all possible care has been placed in assuring the accuracy of the contents of this magazine, including all associated source code, listings and figures, the publisher assumes no responsibilities with regards of use of the information contained herein or in all associated material. php|architect, php|a, the php|architect logo, Marco Tabini & Associates, Inc. and the MTA Logo are trademarks of Marco Tabini & Associates, Inc. Contact Information: General mailbox: info@phparch.com Editorial: editors@phparch.com Sales & advertising: sales@phparch.com Printed in Canada Copyright 2003-2009 Marco Tabini & Associates, Inc. All Rights Reserved " id="pdf-obj-3-78" src="pdf-obj-3-78.jpg">
What's New at Python Magazine Learn more at: http://pythonmagazine.com February 2009 Topics: • Mock testing techniques
What's New at Python Magazine
Learn more at: http://pythonmagazine.com
February 2009 Topics:
• Mock testing techniques and tools (Grig Gheorghiu)
• Creating a collection manager with Elixir (Gaëtan de Menten)
• Multiple Documents on PyObjC (JC Cruz)
• Using Python for Pedigree Analysis (John B. Cole, PhD)
• Co-designing with web.py: Urban Mediator (Roman Suzi, Joanna
Saad-Sulonen, Andrea Botero)
• Simple File Input and Output (Mark Mruss)
• Universal Newlines Ate My File: A Cautionary Tale

4 | February 2009 www.phparch.com

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) EDITORIAL Round Two by Elizabeth Tucker Long W elcomeb e t h @ p h p a r c h . c o m • E-mail us in general: i n f o @ p h p a r c h . c o m • Post in our forums: http://c7y-bb.phparchitect.com We appreciate all of the feedback that we get, so be sure to keep it coming. Don’t forget, if you are involved in a PHP or Python user group, we want to add your group to our directory, so be sure to e-mail b e t h @ p h p a r c h . c o m with “PHP User Group Info” in the subject line. This month, we are focusing on adding a little spice to your PHP develop- ment. Take a tour of RIA development with Flex and PHP with Richard Bates while Matthew Weier O’Phinney shows us how a partnership between Zend and Dojo is making RIA development even easier. José León Serna introduces us to VCL which brings php into the visual IDE world, and Chris Cornutt makes a strong case for using CodeIgniter as your framework of choice. If you’d like to branch out into desktop applications, Ricky Robinett walks us through display- ing database information in a desktop application using PHP and AIR. Helgi Þormar Þorbjörnsson discusses PEAR’s contribution to naming conventions, and Arne Blankerts provides some simple tips to protect our users from cross-site scripting attacks. Ben Ramsey sets the record straight on the requirements for RESTful applications, Ivo Jansch outlines how more time spent in the technical design phase of a project can save you a huge headache later on, and Marco finally tries out his iPhone. I hope you enjoy this month’s issue! What's New at Python Magazine Learn more at: http://pythonmagazine.com February 2009 Topics: • Mock testing techniques and tools (Grig Gheorghiu) • Creating a collection manager with Elixir (Gaëtan de Menten) • Multiple Documents on PyObjC (JC Cruz) • Using Python for Pedigree Analysis (John B. Cole, PhD) • Co-designing with web.py: Urban Mediator (Roman Suzi, Joanna Saad-Sulonen, Andrea Botero) • Simple File Input and Output (Mark Mruss) • Universal Newlines Ate My File: A Cautionary Tale 4 | February 2009 www.phparch.com February 2009 Volume 8 - Issue 2 Publisher Arbi Arzoumani Editor-in-Chief Elizabeth Tucker Long Author Liaison Elizabeth Naramore Cathleen MacIsaac Technical Editors Steph Fox Simon Harris Matthew Turland Clark Everetts Graphics & Layout Arbi Arzoumani Managing Editor Arbi Arzoumani Authors Richard Bates, Arne Blankerts, Chris Cornutt, Ivo Jansch, Matthew Weier O'Phinney, Ben Ramsey, Ricky Robinett, José León Serna, Marco Tabini, Helgi Þormar Þorbjörnsson php|architect (ISSN 1709-7169) is published twelve times a year by Marco Tabini & Associates, Inc., 28 Bombay Ave., Toronto, ON M3H1B7, Canada. Although all possible care has been placed in assuring the accuracy of the contents of this magazine, including all associated source code, listings and figures, the publisher assumes no responsibilities with regards of use of the information contained herein or in all associated material. php|architect, php|a, the php|architect logo, Marco Tabini & Associates, Inc. and the MTA Logo are trademarks of Marco Tabini & Associates, Inc. Contact Information: General mailbox: info@phparch.com Editorial: editors@phparch.com Sales & advertising: sales@phparch.com Printed in Canada Copyright 2003-2009 Marco Tabini & Associates, Inc. All Rights Reserved " id="pdf-obj-3-85" src="pdf-obj-3-85.jpg">
Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) EDITORIAL Round Two by Elizabeth Tucker Long W elcomeb e t h @ p h p a r c h . c o m • E-mail us in general: i n f o @ p h p a r c h . c o m • Post in our forums: http://c7y-bb.phparchitect.com We appreciate all of the feedback that we get, so be sure to keep it coming. Don’t forget, if you are involved in a PHP or Python user group, we want to add your group to our directory, so be sure to e-mail b e t h @ p h p a r c h . c o m with “PHP User Group Info” in the subject line. This month, we are focusing on adding a little spice to your PHP develop- ment. Take a tour of RIA development with Flex and PHP with Richard Bates while Matthew Weier O’Phinney shows us how a partnership between Zend and Dojo is making RIA development even easier. José León Serna introduces us to VCL which brings php into the visual IDE world, and Chris Cornutt makes a strong case for using CodeIgniter as your framework of choice. If you’d like to branch out into desktop applications, Ricky Robinett walks us through display- ing database information in a desktop application using PHP and AIR. Helgi Þormar Þorbjörnsson discusses PEAR’s contribution to naming conventions, and Arne Blankerts provides some simple tips to protect our users from cross-site scripting attacks. Ben Ramsey sets the record straight on the requirements for RESTful applications, Ivo Jansch outlines how more time spent in the technical design phase of a project can save you a huge headache later on, and Marco finally tries out his iPhone. I hope you enjoy this month’s issue! What's New at Python Magazine Learn more at: http://pythonmagazine.com February 2009 Topics: • Mock testing techniques and tools (Grig Gheorghiu) • Creating a collection manager with Elixir (Gaëtan de Menten) • Multiple Documents on PyObjC (JC Cruz) • Using Python for Pedigree Analysis (John B. Cole, PhD) • Co-designing with web.py: Urban Mediator (Roman Suzi, Joanna Saad-Sulonen, Andrea Botero) • Simple File Input and Output (Mark Mruss) • Universal Newlines Ate My File: A Cautionary Tale 4 | February 2009 www.phparch.com February 2009 Volume 8 - Issue 2 Publisher Arbi Arzoumani Editor-in-Chief Elizabeth Tucker Long Author Liaison Elizabeth Naramore Cathleen MacIsaac Technical Editors Steph Fox Simon Harris Matthew Turland Clark Everetts Graphics & Layout Arbi Arzoumani Managing Editor Arbi Arzoumani Authors Richard Bates, Arne Blankerts, Chris Cornutt, Ivo Jansch, Matthew Weier O'Phinney, Ben Ramsey, Ricky Robinett, José León Serna, Marco Tabini, Helgi Þormar Þorbjörnsson php|architect (ISSN 1709-7169) is published twelve times a year by Marco Tabini & Associates, Inc., 28 Bombay Ave., Toronto, ON M3H1B7, Canada. Although all possible care has been placed in assuring the accuracy of the contents of this magazine, including all associated source code, listings and figures, the publisher assumes no responsibilities with regards of use of the information contained herein or in all associated material. php|architect, php|a, the php|architect logo, Marco Tabini & Associates, Inc. and the MTA Logo are trademarks of Marco Tabini & Associates, Inc. Contact Information: General mailbox: info@phparch.com Editorial: editors@phparch.com Sales & advertising: sales@phparch.com Printed in Canada Copyright 2003-2009 Marco Tabini & Associates, Inc. All Rights Reserved " id="pdf-obj-3-87" src="pdf-obj-3-87.jpg">

February 2009

Volume 8 - Issue 2

Publisher

Arbi Arzoumani

Editor-in-Chief

Elizabeth Tucker Long

Author Liaison

Elizabeth Naramore

Cathleen MacIsaac

Technical Editors

Steph Fox

Simon Harris

Matthew Turland

Clark Everetts

Graphics & Layout

Arbi Arzoumani

Managing Editor

Arbi Arzoumani

Authors

Richard Bates, Arne Blankerts, Chris Cornutt, Ivo Jansch, Matthew Weier O'Phinney, Ben Ramsey, Ricky Robinett, José León Serna, Marco Tabini, Helgi Þormar Þorbjörnsson

php|architect (ISSN 1709-7169) is published twelve times a year by Marco Tabini & Associates, Inc., 28 Bombay Ave., Toronto, ON M3H1B7, Canada.

Although

all

possible care

has been

placed in

assuring the accuracy of the contents of this

magazine, including all associated source code,

listings

and

figures,

the

publisher assumes

no

responsibilities

with

regards

of

use

of

the

information contained herein or in all associated

material.

php|architect, php|a, the php|architect logo, Marco Tabini & Associates, Inc. and the MTA Logo are trademarks of Marco Tabini & Associates, Inc.

Contact Information:

General mailbox:

info@phparch.com

Editorial:

editors@phparch.com

Sales & advertising:

sales@phparch.com

Printed in Canada

Copyright © 2003-2009 Marco Tabini & Associates, Inc. All Rights Reserved

<a href=Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) " id="pdf-obj-4-4" src="pdf-obj-4-4.jpg">
<a href=Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) " id="pdf-obj-4-6" src="pdf-obj-4-6.jpg">
<a href=Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) " id="pdf-obj-4-8" src="pdf-obj-4-8.jpg">
<a href=Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) " id="pdf-obj-4-10" src="pdf-obj-4-10.jpg">
<a href=Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) " id="pdf-obj-4-12" src="pdf-obj-4-12.jpg">
<a href=Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) " id="pdf-obj-4-14" src="pdf-obj-4-14.jpg">
<a href=Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) " id="pdf-obj-4-16" src="pdf-obj-4-16.jpg">
<a href=Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) " id="pdf-obj-4-18" src="pdf-obj-4-18.jpg">
<a href=Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) " id="pdf-obj-4-20" src="pdf-obj-4-20.jpg">
<a href=Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) " id="pdf-obj-4-22" src="pdf-obj-4-22.jpg">
<a href=Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) " id="pdf-obj-4-24" src="pdf-obj-4-24.jpg">
<a href=Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) " id="pdf-obj-4-26" src="pdf-obj-4-26.jpg">
<a href=Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) " id="pdf-obj-4-28" src="pdf-obj-4-28.jpg">

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)

ElePHPants!

The elePHPants love to travel the world! Here are some photos that they have sent us from their travels.

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) ElePHPants! The elePHPants love to travel the world! Herehttp://www.elephpantworldtour.com 6 | February 2009 www.phparch.com " id="pdf-obj-5-9" src="pdf-obj-5-9.jpg">

Overlooking the Straits of Gibraltar. Photo courtesy of Alexandru Stanoi.

Who knew ElePHPants were so good at pool! Photo courtesy of Cal Evans.
Who knew
ElePHPants
were so good at pool!
Photo courtesy
of Cal Evans.
Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) ElePHPants! The elePHPants love to travel the world! Herehttp://www.elephpantworldtour.com 6 | February 2009 www.phparch.com " id="pdf-obj-5-16" src="pdf-obj-5-16.jpg">
Mountain climbing and enjoying Photo courtesy of Derick Rethans. the view. Almost of Ivo just waiting
Mountain
climbing
and enjoying
Photo courtesy
of Derick
Rethans. the view.
Almost
of Ivo just
waiting for a taxi. Photo
courtesy home,
Jansch.

Do you have photos of your ElePHPant? We would love to print them. Send us a high-resolution image (or if you have the high-resolution image posted online, just send us the link) of your ElePHPant. We'll choose several photos a month to publish. Just can't get enough of these elePHPants? Be sure to check out the ElePHPant World Tour -

6 | February 2009 www.phparch.com

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)
Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)
Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)
Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)
Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)

COLUMN

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com) Version Naming by Helgi Þormar Þorbjörnsson PEAR Corner Inhttp://pear.php.net/group/docs/20040226-vn.php , but I will attempt to simplify it a little bit. First, it’s important to understand that there is a difference between version numbers and version state and how they interact. Let’s look at how the basics of the version numbering system work. Consider x.y.z for a second, now let’s translate that into something human readable. 8 | February 2009 www.phparch.com " id="pdf-obj-7-6" src="pdf-obj-7-6.jpg">

Version

Naming

by Helgi Þormar Þorbjörnsson

PEAR Corner

In this column series, I’d like to write a openly about PEAR, specifically about its good and bad sides.

P EAR has been around for many, many years, and thus has accumulated a lot of knowledge on how to run a large scale project.

PEAR has run into countless hurdles along the way

that had to be solved in one way or another. As a result

of getting over these hurdles, we have produced good

things that affect the whole PHP community and also

things that well

let’s

face it, didn’t help PEAR or PHP

a whole lot.

But, how do we bring that experience from the knowledge bank of PEAR and give it back to the com-

munity, so other projects can learn from us and steer

clear of what we did wrong and embrace what PEAR did

right. One of the things that really makes PEAR what it is today are the standards we have been evolving for the

past couple of years. A lot of other projects and even

companies have embraced large chunks of those stan-

dards as their de facto standard for PHP userland code.

Just to name a few standards:

• Distribution system (channels, packages, package.xml) • Coding Standards • Version naming • Directory layout • Backwards Compatibility and what that entails • And many others

If you want to read about the distribution system, you

can grab the November and December issues of this magazine where I wrote about it in good detail (and thus will not spend any ink covering it here).

Version Naming

Let’s start by talking about the version naming stan-

dard and why it’s important.

Now don’t get me wrong, it’s not like PEAR invented the need for version naming, be it for PHP projects or the software world at large, but the fact is that PEAR

was one of the first, if not the first, large-scale PHP

project that had more than one concurrent release at a time. This fact required a proper standard in the end.

So, almost 5 years ago today, the PEAR group at the

time went ahead and formalized a standard to keep the version naming more consistent, yet still working with

the version_compare function. The document they produced can be accessed from http://pear.php.net/group/docs/20040226-vn.php, but I will attempt to simplify it a little bit. First, it’s important to understand that there is a difference between version numbers and version state

and how they interact. Let’s look at how the basics of the version numbering system work. Consider x.y.z for a second, now let’s translate that into something human

readable.

8 | February 2009 www.phparch.com

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)

PEAR Corner

COLUMN

• x = Major release number • y = Minor, used for feature additions • z = patch level number, used when it’s purely only a bug fix release

Now let’s have a quick look at the states, “dev”, “alpha”, “beta”, “RC” or “stable” (listed in the order of code maturity). So what you end up with is “x.y.zstate” except when you have a stable release. In PEAR, you might see version namings like so: 0.5.6alpha1, 0.12.0beta3, 1.0.0RC4, 1.2.0 and so on. With this

system in mind, we need to see what each state and number incrementation really means for you and your

project. Quite often, I see people do their initial release, and

for some unknown reason, they decide that 0.0.1 is the best version, swear by it even. In the version naming standard we have in PEAR, that is not allowed because when you are releasing the first release you are not fixing bugs, you are adding new features, so the first release should always be 0.1.0, at the very least. Something that happens fairly often as well is that people do their initial release as 1.0.0 with a stable state, even though their project doesn’t truly have a stable API, for example, or even a stable product in

general. Perhaps it’s because they believe they man- aged to get it very stable, but the fact is, no mat-

ter how stable you think your product is for the first

release, always release the first one lower than 1.0.0

stable.

Keep in mind, when you go stable, stay stable! Don’t

start messing up the API in a way that people will have to alter their applications, this tends to be called BC,

or backwards compatibility.

Backwards Compatibility

Now what is backwards compatibility? In short, it is

when I, as a application developer, pick lib X to use in

my application and pick release 1.2.0 to start utilizing the API of lib X. Even though I don’t follow the devel- opment of lib X, if they follow a proper, no-BC-breaking approach, then I should be able to upgrade the lib from

  • 1.2.0 to 1.6.0 without having to change a single line

in my code. If a BC break would have occurred between

  • 1.2.0 and 1.6.0, then there is a good chance that my

application would stop working with such an upgrade. So BC breaks should only happen below stable, prefer-

ably only in the alpha state, if possible.

Food for Thought

So, I perhaps didn’t cover all that much of the version naming standard, but I do believe I got my point across and those interested in learning more can go to the

link I supplied above to get a better idea of how this all works together beautifully. A prime example of why it’s good to have a set stan- dard on the version naming would be when Matthew Weier O’Phinney of Zend Framework fame contacted me in late 2008 to determine whether or not PEAR had this kind of a standard. The Zend Framework team was hav- ing internal discussions in regards to version naming,

especially for their preview releases, better known by

other folks as alpha releases, where new api changes

are introduced but still not considered stable or that an api could possibly break before the final release.

In the end, Matthew managed to convince them to use alpha/beta states on the package level while allow-

ing them to use pr for the website and announcements. This allows people to utilize version_compare on Zend Framework for future releases, potentially use a PEAR channel for distribution, and also, to have appropri- ate stability states for what the release is suppose to reflect.

I felt like this was a very good example showing how

using a well-established naming convention benefits

the whole community and makes things a lot clearer for

those familiar with said standards.

Hopefully this is as useful to you as it was to me

and the projects of which I have been a part. It has,

at least, been highly successful to PEAR and numerous

other projects.

During the day, Helgi Þormar Þorbjörnsson works for Ibuildings in London, UK. The rest of his
During the day, Helgi Þormar Þorbjörnsson works for
Ibuildings in London, UK. The rest of his time is taken up
by his passion for all things PEAR. Helgi is a long term
contributor with a wide range of PEAR packages behind him,
and also takes care of the PEAR website. He is currently an
elected member of the governing body, PEAR Group. Helgi
enjoys writing articles, speaking at conferences and working
on PEAR2 and Pyrus.

9 | February 2009 www.phparch.com

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)

PHP
PHP

Technical Design

by Ivo Jansch

In

this

issue

of

the

Enterprise PHP

column, Ivo takes a look at some aspects

of the technical design phase

of

PHP

applications. He covers some important design decisions that PHP developers should make, and what elements make up a technical design for a PHP application.

  • I haven’t enjoyed any Radiohead albums since they released “Ok Computer” years ago. After that, they became too creative and too alternative for my

taste. However, I do like their recent single ’House of

Cards’.

Now, before you think you’re reading the wrong mag- azine, Radiohead does not have anything to do with programming (except perhaps the remarkable fact that their House of Cards video clip is actually open sourced

at http://code.google.com/creative/radiohead/). But the ’House of Cards’ single is very fitting for this month’s article in the Enterprise PHP series. Today, we’re going to talk about the technical design of PHP applications. Last month, we discussed require-

ments gathering - the ’what’ - and today, we’re going to look at the how. If we do a technical design before

we start to write code, we make sure that we’re not

building a house of cards, but instead, a solid well-

structured application that won’t break down by just

looking at it.

High-Level Architecture

The technical design of an application has a lot of dif-

ferent aspects. One of the first decisions we have to

make is what high-level architecture we will implement. Depending on the requirements and the available infra- structure, we might go for a single monolithic set-up where all the code makes up a single application. This is what we would call a ’normal’ architecture for PHP

applications, and it is probably right for 95% of the ap-

plications.

This column benefits greatly from reader input. If you have an interesting project or if youe n t e r p r i s e p h p @ p h p a r c h . c o m . I might contact you for a short interview, or at least I will use your input when writing this column! Thank you! Ivo " id="pdf-obj-9-71" src="pdf-obj-9-71.jpg">

This column benefits greatly from reader input. If you have an interesting project or if you want to share how you employ PHP in your organization, drop me an email at enterprisephp@phparch.com. I might contact you for a short interview, or at least I will use your input when writing this column!

Thank you!

Ivo

10 | February 2009 www.phparch.com

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)

The MVC model

A ’best practice’ in recent years is to use the MVC model

for such applications. MVC stands for Model, View,

Controller, where the Model contains the business logic of the application, the View contains the presenta- tion logic (the templates) and the Controller glues the two together with application logic. It always helps to

have an example, and the clearest example of the MVC

model is a website for booking hotel rooms. The models

in this case would be the room and the reservation,

each containing the implementation of the business logic, like calculating prices, checking availability, etc.

The view would be the templates that show informa- tion about the reservation on screen, and the controller

would implement the pages in a website that lets the

user create a reservation by showing him the view tem- plates and enabling the user to manipulate the underly- ing model.

This way, the application has a clear structure, and

if you want to change the layout, you only have to change the view templates. It also promotes reuse. You can reuse the business logic of the application in mul- tiple different scenarios. This makes programming more

efficient and enhances quality.

When creating the technical design for an MVC appli-

cation, take the requirements and make a list of all the

models, the views and the controllers you need. Put all the stuff that deals with how things look in the views. Put all the things that comprise business logic (logic that you can envision being more generic than the application you are building, logic that relates more to your business than to the website) in models. The remaining parts (usually the descriptions of how a user acts with the application) go in the controllers.

Service Oriented Architectures

Aside from the MVC model, there are more high-level

architectures that can be applied in PHP applications. An interesting one to look at is the ’Service Oriented Architecture’ or SOA for short. This architecture is com-

monly associated with Java and ’overkill’, but in my

opinion, that’s not justified. In an SOA, the application

is divided into several different web services that talk

to each other. In the above example of a hotel ap- plication, there could be an availability service giving information about a room’s availability, a pricing ser- vice able to deal with pricing schemes, etc. There are several advantages to a service oriented architecture:

• Each service can be developed independently

from the others. This makes it easier to test

the individual components. Services that aren’t ready yet can be stubbed (simulated). • Each service can scale independently. If the availability service is used a lot more heav- ily than the pricing service, this service could scale out to a cluster, while the remaining services remain on a single box. • Services can each be tested independently. Unit testing on a service is relatively easy be- cause services have a well-defined API.

PHP is a very suitable language for SOA architectures,

because PHP contains native functionality in the form of a SoapClient and SoapServer class that can be used

to either consume or to create a web service.

A common component in SOA environments is the Enterprise Service Bus (ESB), which is more or less a

medium that services use to communicate. For most

PHP applications, an ESB is overkill, as the services

can talk with each other just fine without the need for

a bus. Still, there is an open source PHP ESB product that might be worth having a look at when imple- menting a large SOA architecture: Blackbird ESB at http://www.blackbirdesb.org. When creating a technical design based on an SOA

architecture, first divide your application requirements

into logical units that would be able to operate fairly independently. If you can define a clean API for how

a set of features can interact with its surroundings, it’s a logical step to place those features in a separate

service. Once you’ve done this for all features, you have

a ’service model’, and you can start to create the design

for each individual service.

A suggestion for further reading on SOA architec- tures is the book ’Understanding Enterprise SOA’ by Eric Pulier and Hugh Taylor (http://manning.com/pulier/). The book is not PHP specific; it explains the ins and outs of SOA design in a language agnostic way.

Database Design

After we’ve made a decision on what high-level archi- tecture to implement, we can have a look at the under- lying data model. It is up for debate whether or not the data model should be designed at an early stage in the design process, but it is my personal experience that

11 | February 2009 www.phparch.com

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)

it works really well to do it as early as possible. Eric Raymond, one of the early evangelists of open source software has a saying that goes like this: “Smart data

structures and dumb code works a lot better than the

other way around” (from his majestic ’The Cathedral and The Bazaar’ article). The way I interpret this saying is that if your data model is well-designed at an early stage, the code that makes use of the data model will

be a lot easier and a lot clearer. Whereas if you create

the database in an ad hoc fashion on the fly while you

are writing the code, the code might be more complex and less manageable, and the data model more difficult

to understand.

There are various techniques for modeling a data- base. I tend to stick to the classic ’ERD’ method for relational databases with Crow’s foot notation (see

http://en.wikipedia.org/wiki/Entity-relationship_model), but any modeling method will do, as long as you apply it consistently, and as long as your fellow team members

can interpret your models properly. More important than what notation you use, is the

actual design of the database. I’m not going to talk

about stuff like normalization and general modeling, I’m going to assume that this is already part of your development skills (and if not, there are excellent prim- ers online). Instead I’ll discuss a more specific design decision when it comes to databases. Earlier, I dis-

cussed monolithic applications versus service oriented

architectures, and there is a similar design decision to

be made when it comes to the database.

In 95% of the cases, you’ll develop an application

that has a single database and all is good. But there are situations where you might consider splitting the data into multiple databases. In the SOA example, it is a logical choice to give each service its own database (on the other hand, it’s also fine for services to feed on the same database), but multiple databases can be a good thing in other applications as well. First, it helps keep the data models simple (simple is good) and

focused around a certain task. Think of a database with

customer related data (CRM) and a separate database for keeping track of stocks. The second reason is scal- ability. If you have multiple small databases, it is easi-

er to scale up only those parts that need it. Instead of

having to scale a massive data model across a database cluster, it might suffice to scale the heavy transactional parts while the rest remains in a single database. Note, by the way, that a significant disadvantage

of such a partitioning of the database is that simple

joins across multiple databases aren’t possible in most

database servers. However, if the separation is strict enough, those joins across functional parts of the data- base might not be necessary.

Application Design

The final aspect of the technical design is the design of the code itself. After the high-level architecture and the data model, the application design is the third im- portant part of the technical design phase. Typically, this part of the design consists of class

diagrams, sequence diagrams or data flow diagrams. Data flow diagrams are useful when the focus of an ap-

plication is on the data, and you need to identify how this information flows from one component to the next

and what processing is done on the information. Class diagrams are always useful, and sequence diagrams are

very useful if there is a complex hierarchy of classes

and you want to visualize what classes and method calls are involved in a particular feature. All three mod- eling techniques help visualize the design of an appli-

cation. The structure of an application is clearer if you

have it in front of you. If you need to change things or add functionality, the models help in determining what

should be implemented where.

Conclusion

We’ve covered just a few scenarios of high-level archi- tecture, database design and application design. The import take-away, however, is that you pay attention to these design aspects. Tackling design issues during the technical design phase saves a lot of time during the implementation phase. In general, the earlier you

can tackle an issue, the lower the cost of the issue. In

the design phase, while there is no code to maintain, you are in a good position to tackle architectural issues

such as the scalability of an application.

   
   

ivo janscH is the CTO of Ibuildings, a PHP services company based in Europe. He is the author of php|architect’s Guide

to Enterprise PHP Development, and is an active blogger

and speaker in the PHP community. Ivo also initiated the ATK Business Framework.

12 | February 2009 www.phparch.com

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)

FEATURE

 
V
V
C
C

VCL for PHP

VCL for PHP L
L
L

by José León Serna

Interested in Visual RAD tools for PHP? This article provides a general overview of VCL, Visual Component Library, for PHP, what it’s useful for, and introduces you to integrating your own components into the Delphi for PHP IDE.

W hat is VCL for PHP?

In short, it is a component

library. You’ve probably used other compo- nent libraries, like Zend Framework, so what

makes VCL for PHP different? The V in its name, which

stands for Visual. This library was designed from the beginning to be integrated into a Visual IDE, allowing

developers to write web applications in PHP using RAD technologies. When Delphi for Windows 1.0 was released, the sta-

tus of desktop application development for Windows

was very similar to the status of PHP web application

development today. There are numerous frameworks

and class libraries trying to make PHP web application

development faster and easier, but until recently, there

wasn’t a complete solution that allowed you to do it with a component library in an IDE with visual capabili-

ties. That is why Delphi for PHP and VCL for PHP were created: to provide a common path in which all existing

and future code could coexist and to create a standard

for PHP components.

Goals of VCL for PHP

VCL for PHP was designed with a very specific purpose,

and the goal was not to write yet another PHP frame- work:

• Be used in a Visual IDE where components can be dragged from a palette and dropped into a design panel • Create a component model to unify the con-

cepts of properties, methods and events

• Replicate VCL for Windows library, so using

it would be familiar to existing Delphi for

Windows developers

• Reuse as much code as possible from other, non-VCL libraries • Provide a persistence mechanism
• Reuse as much code as possible from other,
non-VCL libraries
• Provide a persistence mechanism (using ses-
sions) to emulate desktop applications
REQUIREMENTS
PHP: 5.2+
Other Software: Zend Framework, PEAR and others
Useful/Related Links:
• http://www.qadram.com/vcl4php
• http://en.wikipedia.org/wiki/Property_(computer_
science)

13 | February 2009 www.phparch.com

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)

FEATURE

VCL for PHP

Several things must be taken into account to make a library work in a Visual design tool, as the IDE requires extra information about the components. This infor- mation must be provided by the component developer. We will see more on this below.

VCL for PHP proposes a component model with all the features required to integrate components into a Visual IDE, and a coding convention to specify proper- ties and events. Currently, PHP - unlike languages like Delphi for Windows or C# - doesn’t have a syntax to express properties, so that must be emulated. Before

 

LISTING 1

1.

<?php

2.

require_once("vcl/vcl.inc.php");

3.

//Includes

4.

use_unit("forms.inc.php");

5.

use_unit("extctrls.inc.php");

6.

use_unit("stdctrls.inc.php");

7.

8.

//Class definition

9.

class Index extends Page

10.

{

11.

public $Button1 = null;

12.

public $Panel1 = null;

13.

}

14.

15.

global $application;

16.

17.

global $Index;

18.

19.

//Creates the form

20.

$Index=new Index($application);

21.

22.

//Read from resource file

23.

$Index->loadResource(__FILE__);

24.

25.

//Shows the form

26.

$Index->show();

27.

28.

?>

29.

 
 

LISTING 2

 
  • 1. <?php

  • 2. <object class="Index" name="Index" baseclass="page">

  • 3. <property name="Background"></property>

  • 4. <property name="Caption">Index Page</property>

  • 5. <property name="DocType">dtNone</property>

  • 6. <property name="Height">600</property>

  • 7. <property name="IsMaster">0</property>

  • 8. <property name="Name">Index</property>

  • 9. <property name="Width">800</property>

10.

<object class="Panel" name="Panel1" >

11.

<property name="Caption">Panel1</property>

12.

<property name="Height">192</property>

13.

<property name="Left">100</property>

14.

<property name="Name">Panel1</property>

15.

<property name="Top">72</property>

16.

<property name="Width">364</property>

17.

<object class="Button" name="Button1" >

18.

<property name="Caption">Button1</property>

19.

<property name="Height">25</property>

20.

<property name="Left">88</property>

21.

<property name="Name">Button1</property>

22.

<property name="Top">68</property>

23.

<property name="Width">75</property>

24.

</object>

25.

</object>

26.

</object>

27.

?>

28.

you ask “What about class variables, methods, getters and setters?” and start throwing things at me, please

understand that what we mean by properties here are class entities that can be accessed in our code directly

by assignment, or used in expressions, but are actu- ally protected by underlying class methods. Those

class methods are normally not invoked explicitly. That is the syntactic difference between class variables

in PHP and properties in Delphi. More on this under

“Component Model” later in this article. VCL for PHP was also designed to allow code reuse from other libraries. Since it doesn’t require a strict

folder structure, and needs only minimal code to imple-

ment a wrapper, you can use existing code inside the

IDE with little effort. We have wrapped into the Delphi

for PHP IDE some Zend Framework classes, some PEAR

classes, lots of qooxdoo widgets and ExtJS widgets.

You can wrap almost anything and provide a common

interface through those wrappers, so any developer will

be able to use them easily.

Resource Files

The Delphi for PHP IDE stores and reads component

properties from an .xml.php file. This file is created

by the IDE at design-time, but you are not required to

use the IDE; as it is an XML formatted text file, you

can create it with a text editor. This file is used by

the Page component to create all components and set

the properties to their initial values. This is done in

the loadResource() call, just before the show() call. Show() is what causes a component to be displayed in the browser. These files are external resources you

can use as templates, and they provide a separation

between the interface and the code. In Listing 1, you can see the basic structure of a

Page class with calls to loadResource() and show(). In

Listing 2, you can see the contents of the .xml.php

file. Resource files are not a requirement. You can cre-

ate your components and assign properties manually, as

shown in Listing 3.

Writing Your Own Components

Components can be built using anything a browser can

understand, like HTML, CSS, Javascript, Flash, Images,

etc. For example, a Button is a component built using

just the <input> HTML tag, but MonthCalendar and

DateTimePicker use DHTML Calendar, a third-party library that creates calendars with Javascript. These

14 | February 2009 www.phparch.com

VCL for PHP

FEATURE

components simply wrap the func- tionality of the library by adding

an interface of properties, methods

and events, but the hard work is done by the library.

As you can see, creating VCL for PHP components is not reinvent- ing the wheel like in some other frameworks; instead, you can just wrap existing code. Components can be non-visual and just provide functionality. The Zend Framework

components for authentication and

ACL, for instance, have no visual output. Non-visual components are represented in the designer

as small icons, and you can set

their properties and attach event handlers as with any other compo- nents.

VCL for PHP components are very simple to write; the first

method you must know about is dumpContents(). This method is called when a component needs to dump all its code to the browser,

and you simply echo all the code that makes up your component. This simple approach makes creat- ing wrappers for other libraries very easy. No complicated tags, attri-

butes, folders, etc. Just dump the code, and you are done.

Listing 4 shows the code used by the Upload component in the dumpContents() method and Figure 1 shows the Upload component in the visual designer.

Class Tree

The class library is made up of a full tree of classes, but all of them share common ancestors which implement the core functional- ity. The root class is called Object, and all classes in the library inherit from it. The next major classes that inherit from Object are Persistent, Component, and

Control. Check out Figure 2 to see a brief class tree. In this tree, each class provides specific functionality:

• Object: Property System • Persistent: Serialization and Persistence • Component: Ownership • Control: Parentship and

Visual Capabilities

Ownership and

Parentship

It’s important to understand the

difference between ownership and parentship, as that will give you an idea of how components are or- ganized inside a Page. By default, a Page owns all the components

placed inside, no matter which one

is the parent. After that, the par- ent for a control is the control into

which it is placed. Let’s imagine a Page, with a Panel, and inside the

FIGURE 1 Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)
FIGURE 1
Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)
FIGURE 2
FIGURE 2

15 | February 2009 www.phparch.com

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)

FEATURE

VCL for PHP

Panel, a Button. The Page is the owner of the Panel and of the Button, but the Page is only the parent of the Panel, and the Panel is the parent of the Button. When you call show() for a Page, it iterates through all the children, telling each of them to show(), and in turn, each child tells all of its children to show(). These nested calls cause all the controls on a Page to

be shown.

Component Model

On the other hand, PHP does provide magic methods which can be used to mimic the behaviour of proper-

ties. This is what VCL for PHP uses to let you write

methods that will be accessed like properties. As

stated earlier, all VCL for PHP classes inherit from, at

the top level, a class named Object. This class imple-

ments the PHP magic methods __

get()

and __

set()

to

allow you to create such properties. Look at Listing 6

to see what a property looks like.

PHP lacks, at this time, properties, in the sense of providing access methods to fields. A property can be

   

LISTING 4

described as something between a field and a method,

1.

<?php

2.

function dumpContents()

in which the storage is done in the field, but the access

3.

{

4.

$attributes = $this->getCommonAttributes();

to that field is done using methods, to get and set the

5.

6.

$style = $this->getCommonStyles();

value of that field. By having methods for accessing

7.

 

8.

if ($this->readHidden())

a property, you have the opportunity to write code to

 

9.

{

react to property changes or to provide some validation

10.

if (($this->ControlState & csDesigning) != csDesigning)

11.

{

or formatting code when getting the value of a prop-

12.

$style.=" visibility:hidden; ";

13.

}

erty. In languages like Delphi for Windows or C#, the

14.

}

15.

language itself provides keyword constructs for that.

16.

17.

if ($style != '') $style = 'style="' . $style . '" ';

Take a look at the Delphi for Windows code sample in

18.

Listing 5.

19.

if ($this->_onshow != null)

20.

{

 

21.

$this->callEvent('onshow', array());

22.

}

 

LISTING 3

 

23.

24.

echo '<input type="file" value="Up" id="'. $this->_name .

 

25.

 

'" name="'. $this->_name .'" '. $style .' '.

 

1.

<?php

26.

$attributes .'/>';

2.

require_once("vcl/vcl.inc.php");

27.

3.

//Includes

28.

}

4.

use_unit("forms.inc.php");

29.

?>

5.

use_unit("extctrls.inc.php");

30.

6.

use_unit("stdctrls.inc.php");

 

7.

 

8.

//Class definition

9.

class Index extends Page

   

LISTING 5

10.

{

11.

public $Button1 = null;

 
 

12.

public $Panel1 = null;

1.

unit listing5;

13.

}

2.

14.

3.

interface

15.

global $application;

4.

16.

5.

type

17.

global $Index;

6.

TMyObject=class

18.

7.

private

19.

//Creates the form

8.

FMyProperty: string;

20.

$Index=new Index($application);

9.

procedure SetMyProperty(const Value: string);

21.

10.

published

22.

$Index->Panel1 = new Panel($Index);

11.

property MyProperty:string read FMyProperty

23.

$Index->Panel1->Parent = $Index;

12.

write SetMyProperty;

24.

$Index->Panel1->Height = 192;

13.

end;

25.

$Index->Panel1->Left = 100;

14.

26.

$Index->Panel1->Name = "Panel1";

15.

implementation

27.

$Index->Panel1->Top = 72;

16.

28.

$Index->Panel1->Width = 364;

17.

{ TMyObject }

29.

18.

30.

$Index->Button1 = new Button($Index);

19.

procedure TMyObject.SetMyProperty(const Value: string);

31.

$Index->Button1->Parent = $Index->Panel1;

20.

begin

32.

$Index->Button1->Caption = "Button1";

21.

FMyProperty := Value;

33.

$Index->Button1->Height = 25;

22.

end;

34.

$Index->Button1->Left = 88;

23.

35.

$Index->Button1->Name = "Button1";

24.

end.

36.

$Index->Button1->Top = 68;

25.

37.

$Index->Button1->Width = 77;

26.

// to access the property

38.

27.

var obj: TMyObject;

39.

//Shows the form

28.

obj.MyProperty := 'Property Value';

40.

$Index->show();

29.

Writeln(obj.MyProperty);

41.

30.

42.

?>

16 | February 2009 www.phparch.com

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)

VCL for PHP

FEATURE

Public and Published

In PHP 5, the visibility of class members can be pri- vate, protected or public, but for the IDE, a new scope must be added, called published. At run-time, a pub- lished property is public, but at design-time, only pub-

lished properties will be shown in the Object Inspector. This is necessary because not all properties should be

set by the developer at design-time. Since PHP doesn’t have this visibility keyword, VCL for PHP needs some

way to accomplish it.

This is the convention the IDE uses to identify which

properties to show in the Object Inspector: proper- ties whose accessor method names start with read or write are considered public, and those whose accessor method names start with get and set are considered published.

Events

A component can have two types of events, regular events and Javascript events. Regular events are those

in which the event handler must be a PHP method; i.e., the code must be written in PHP. For Javascript

events, the event handler must be a function written in Javascript. The main difference is when and where

the code is executed. For PHP events, the code is ex-

ecuted when the form is submitted to the server. For Javascript events, the code is executed in the browser,

before anything is posted to the server. For example, a Button can have two OnClick events; the first one fired is the Javascript OnClick event, and then after the form is posted, the PHP OnClick is called. Events are regular properties - they contain a string

with the name of the method to call - so, to allow the IDE to know the difference between properties,

events and Javascript events, another convention is used. Regular events must start with On; for example, OnClick, and Javascript events must start with jsOn, for example, jsOnClick.

Calling Events

Events are called by components when all relevant con- ditions are met. Let’s take an easy example, like the Button OnClick event. In HTML, you know a form but-

ton has been clicked if, in the request, there is a form

field that has a name matching the contents of the name attribute of the <input> tag, with a value set in the value attribute of the <input> tag. This is exactly what the Button component looks for. In the init()

method of the Button class, there is code that fires the

OnClick event, which checks that those conditions are met to fire a call to the OnClick() event handler using callEvent(). All event handlers must have two parameters, $sender and $params, the first one is the object/com- ponent that has produced the event, and the second

can be anything the component wants to send, like mouse coordinates or other information. Events can

also return a value, and it depends on the component developer to use it or not. Listing 7 shows a basic example of how to create a button and attach it to an event to process clicks.

Session Persistence

One of the basic features of VCL for PHP is session persistence. This features allows you to write web ap- plications that behave like desktop apps. In a desktop application, you don’t worry when your application

starts and finishes, and there is no need to backup and restore the status of all the controls you have on a form as the user moves from screen to screen.

With VCL for PHP, you get the same behaviour, be- cause it serializes and unserializes object properties

when required. That way, the state of those compo- nents will be always what you expect. For example, if

you change the background color of a Label to red, you

expect that, no matter what happens to the applica- tion, no matter which link the user follows, the back- ground color for the Label should always be red, until you decide to change it. All this is automatic if you use VCL for PHP components, as it saves in the session

 

LISTING 6

1.

<?php

2.

3.

class TMyObject extends Object

4.

{

5.

protected $_myproperty="";

6.

7.

function getMyProperty()

8.

{

9.

return $this->_myproperty;

10.

}

11.

12.

function setMyProperty($value)

13.

{

14.

$this->_myproperty=$value;

15.

}

16.

17.

function defaultMyProperty()

18.

{

19.

return "";

20.

}

21.

}

22.

23.

?>

24.

17 | February 2009 www.phparch.com

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)

FEATURE

VCL for PHP

all properties that differ from their default values, and

restores them back again when the script is started.

Default Values

Properties can have default values, which is important for several reasons. First, the IDE’s Object Inspector

shows in bold those property values that differ from

their default value. This allows a developer to easily

see which properties have been changed from default

values and more importantly, for session persistence,

knowing what values are defaults allows us to store just

those properties whose values differ from their de- faults. This saves a lot of session space. Finally, when

the IDE saves an .xml.php file, it again saves only the

property values for those properties that differ from their default values. This saves disk space and speeds

up the .xml.php parsing and loading.

Ajax Integration

With VCL for PHP, you can make use of Ajax, by using the method ajaxCall(), which generates all the re- quired javascript code to perform a call to the server using ajax, and then process the returned results to update the browser. To make it work, you need to set the UseAjax proper- ty of the Page to true, so that processing takes place. If you need to get debug information for the ajax requests, you can set UseAjaxDebug to true and you’ll get a window with all the information. In Listing 8, you can see how easy it is to call a PHP

method from a Javascript event and let the ajax engine update the browser according to property changes.

Data Access

VCL for PHP provides several components to access

data. The standard components are based on the

ADOdb library, which provides an abstraction layer over the data. If you need faster access and don’t require server abstraction, you can use the native data access

controls for MySQL and Oracle. These controls use the native PHP functions instead of ADOdb. Delphi for Windows users will find the data connec- tion model very familiar. You use a Database compo-

nent, which represents the connection to a server and

the selection of a database. After that, you place Table

or Query components, connect to that database, get all

data from a specific table or use a query to get a subset

or a join of several tables. Then, to connect that Table or Query (all of them are Dataset descendants) to con- trols, you use a Datasource. Using this connection mechanism, components can access data without worrying about the underlying

structure, and more types of Datasets can be written,

as long they implement all required properties and

methods.

Template Engines

VCL for PHP allows you to make use of templates,

you are not restricted to use .xml.php files, and you

   

LISTING 8

 

LISTING 7

 
  • 1. <?php

 
  • 2. class Index extends Page

1.

<?php

  • 3. {

 

2.

require_once("vcl/vcl.inc.php");

  • 4. public $Label1 = null;

3.

  • 5. public $Button1 = null;

4.

use_unit("forms.inc.php");

  • 6. function Button1JSClick($sender, $params)

5.

use_unit("stdctrls.inc.php");

  • 7. {

 

6.

  • 8. //Dump the call using Ajax to the Button1Click event

7.

class MyPage extends Page

  • 9. echo $this->Button1->ajaxCall("Button1Click");

8.

{

10.

?>

9.

public $Button1=null;

11.

//Return false to prevent the button submit the form

10.

12.

return(false);

11.

function Button1Click($sender, $params)

13.

<?php

12.

{

14.

}

13.

echo "Button clicked!<hr>";

15.

14.

}

16.

function Button1Click($sender, $params)

15.

}

17.

{

16.

18.

$this->Button1->Caption = "clicked Ajax " .

17.

$MyPage = new MyPage($application);

19.

date("Y-m-d g:i:s a");

18.

$MyPage->Name = "MyPage";

20.

19.

$MyPage->Button1 = new Button($MyPage);

21.

$this->Label1->Caption = "Hello from Ajax!! " .

20.

$MyPage->Button1->Name = "Button1";

22.

date("Y-m-d g:i:s a");

21.

$MyPage->Button1->Parent = $MyPage;

23.

22.

$MyPage->Button1->Left= 100;

24.

$this->Label1->Color = "#" .

23.

$MyPage->Button1->Top= 100;

25.

dechex(rand(0, 0xFFFFFF));

24.

$MyPage->Button1->OnClick = "Button1Click";

26.

}

25.

$MyPage->init();

27.

}

26.

$MyPage->show();

28.

?>

27.

?>

29.

18 | February 2009 www.phparch.com

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)

VCL for PHP

FEATURE

can keep working with HTML templates. In fact, the template engine used by default is Smarty, so if you already have Smarty templates, you can reuse them easily. To make an HTML template work in VCL for PHP,

just place three tags in the file, so the library knows

where to put the required code:

• HeaderCode

• StartForm

• EndForm

Check Listing 9 to see what a template looks like, and where the tags should be inserted. To add VCL for PHP

components, just insert the name of a component as

a smarty tag wherever you want that component to be shown. Then, just set the TemplateEngine property to SmartyTemplate and TemplateFilename to the name of

the file in which you stored the template. When the

page is shown, the template will be used to render the

visual aspect and components will be inserted into the

page where you decided.

IDE Integration

To enable your components to be used in a visual IDE,

you need to specify some extra information, called

design-time information. This information allows the IDE to know how to handle your component, how to

edit properties in the Object Inspector, and where to

place your components on the Tool Palette.

This information is not required when you deploy your application, so it doesn’t add any overhead or

extra size; it is information specific to the IDE. To set this design-time information and install your compo-

nents in the IDE, you create a package, a php file with the extension .package.php. In Listing 10, you can see a basic package file with calls to the functions that interact with the IDE. In a package, you can specify where the IDE can find

the icons that represent your components on the Tool

Palette, the title of your package, the components you

want to install, and the page in which the Tool Palette

will be placed. To let the Object Inspector know how to handle some properties, we need to provide specific informa-

tion in the component package. For example, an array

property should be handled by a specific property

editor in the IDE, which reads the array and provides

a visual interface to edit it. Or a color property,

while the user can type a color name or rgb value, it’s

better to provide a dialog to let the user select a color

visually. At the moment, property editors like these must be written in Delphi for Windows.

Conclusion

VCL for PHP is a new approach to developing PHP web applications, not only allowing you to use a Visual IDE, but to apply techniques used when building desktop applications. This opens up a full range of new possi-

bilities and also opens the door for developers to wrap

and market PHP code according to a new component

standard.

LISTING 9

  • 1. <!DOCTYPE html PUBLIC

  • 2. "-//W3C//DTD XHTML 1.0 Transitional//EN"

  • 3. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  • 4. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">

  • 5. <head>

  • 6. <title>Test Template</title>

  • 7. <meta http-equiv="content-type"

  • 8. content="text/html; charset=utf-8" />

  • 9. {%$HeaderCode%}

  • 10. </head>

  • 11. <body>

  • 12. {%$StartForm%}

  • 13. {%$EndForm%}

  • 14. </body>

  • 15. </html>

LISTING 10

1.

<?php

2.

require_once("vcl/vcl.inc.php");

3.

use_unit("designide.inc.php");

4.

5.

setPackageTitle("Put the title of your package here");

6.

//Change this setting to the path where the icons for

7.

//the components reside

8.

setIconPath("./icons");

9.

10.

// "PaletteCateg" below should be replaced with the

11.

// category in the Tool Palette where the component

12.

// should appear

13.

14.

//Change yourunit.inc.php to the php file which contains

15.

//the component's code

16.

registerComponents("PaletteCateg",array("NewComponent"),

17.

"yourunit.inc.php");

18.

?>

josé león serna is CEO of qadram software S.L. and the main architect of Delphi for
josé león serna is
CEO
of
qadram software S.L. and
the main architect of Delphi for PHP. Delphi for PHP is a
product developed in a partnership between CodeGear
and
qadram
software
S.L.
You
can
contact
him
at
support@qadram.com.

19 | February 2009 www.phparch.com

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)

FEATURE

PART 1
PART 1

Rich Internet Applications

with Flex & PHP

by Richard Bates

You’ve probably noticed that many companies creating rich Internet applications (RIAs) use the terms Flex and Java almost interchangeably. It’s a commonly held belief that only Java technology can deliver the features needed to run a serious RIA. But those of us who work with PHP every day know that it can compete with Java in almost any market and even best it in a few major areas.

Fx
Fx
PHP is free, easy to deploy, highly adaptable, and supported by virtually every Internet hosting company-even
PHP is free, easy to deploy, highly adaptable,
and supported by virtually every Internet
hosting company-even those that charge
only $1.95 per month.
Related URLs
PHP: 5.1.4 (for Zend Framework)
So, why aren’t more people building their
Adobe Flex–based RIAs with PHP? The biggest
reason is that no major vendor has
supported an implementation
of Adobe’s Action Message
Format (AMF) integration
Other Software:
• Flex Builder v3+ or the Flex Builder plug-in for
Eclipse v3.01+
• MySQL Server version 4+
• Zend Framework 1.7+
• Apache or another PHP-enabled Web server
with PHP
...
until
now.
Useful/Related Links:
Adobe and Zend are both
• Adobe Flex 3 LiveDocs: http://livedocs.adobe.
backing Zend_Amf,
a Zend Framework
extension that allows
Flex applications to
speak their native
tongue to PHP.
com/flex/3/
• Zend Framework: http://framework.zend.com/
• ActionScript 3 CoreLib: http://code.google.
com/p/as3corelib/
• Author’s Development Blog: http://flexandair.
com/

20 | February 2009 www.phparch.com

FEATURE
FEATURE

Rich Internet Applications with Flex and PHP: Part 1

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)

Why Use Flex?

There are many reasons for choosing Flex as your RIA development platform. One of the most compelling arguments is that Flex applications run in Adobe Flash Player, which is deployed on an astounding 98% of

computers. An equally important statistic is the rate at

which new Flash Player releases are adopted. Adobe es- timates that new Flash Player releases reach 90% pen-

etration by their twelfth month of availability. In other words, almost everyone with a computer can run your

Flex applications without installing anything extra. Another advantage you’ll get from Flex is speed and

ease of development. Flex’s MXML markup language makes creating visual components and effects almost effortless. Couple that with Adobe Flex Builder, which is based on the immensely popular Eclipse integrated development environment (IDE), and you’ve got one of

the most powerful development toolkits available. This article focuses on one of Flex’s powerful features

in particular: AMF. Flash Player–based applications like those created in Flex and the Adobe Integrated

Runtime (AIR) can communicate using Adobe’s binary AMF format. Using AMF means huge cuts in bandwidth, with an estimated size as little as 1/6th the size of

the same information represented in a text format like

XML. Moreover, communicating with AMF takes a lot less code than XML. You’ll be using the new Zend_Amf extension of the Zend Framework to handle the AMF communication between Flex and PHP.

The Document Manager Application

To explore the Flex/PHP RIA building process, we’ll be creating an online document-management applica-

tion. I chose this application because you can set it

FIGURE 1
FIGURE 1

up relatively quickly, and your options for extending

it are virtually limitless. Along the way, you’ll pick up the skills you need to start building almost any type of RIA with Flex Builder, Zend_Amf, and PHP. So, let’s get

started.

Prior Planning Prevents Poor Performance

It’s a used-up old cliché but inexorably true. The first thing you’ll need to do is determine what objects you’ll be using, their structure, and how to store their under- lying data. For this document management application,

the most important object is

the document! Figure 1

... depicts the basic Document object you’ll be using for this exercise:

Firstly, the document will have an id, which is an in- teger. It will be an auto-incremented value determined by MySQL. The user_id property tells you to which user the document belongs. The name is a descrip-

tive “friendly” name that the user provides. The url property holds the location of the file after it has been uploaded. The description is a longer text field that is also provided by the user. The type is the exten- sion of the uploaded file, without a period. Finally, the file_size property denotes the file’s size in bytes. There are, of course, many other properties you might

want to keep track of, but for now, these will suffice. As referenced in the document’s user_id property, you also need an object to represent users. Creating

one now means that you can authenticate users and

show each user only his or her documents. Keep the User simple, as shown in Figure 2. The user’s id, like the document’s id, will be an auto-incremented integer from MySQL. The user will also have a “friendly” name, an email address, and a

FIGURE 2
FIGURE 2

21 | February 2009 www.phparch.com

FEATURE
FEATURE

Rich Internet Applications with Flex and PHP: Part 1

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)

password. In this sample application, we’re going to

leave the password in plain text, but Flex can support

MD5 and Secure Hash Algorithm (SHA1) hashing. See

the “Related Links” section of this article for more in-

formation.

Setting up the Database

Now that you know exactly what information you need to store for your objects, it’s time to set up the data- base for persistent storage. First, create a new data- base, and call it docs. Next, create the documents table. You can import the Structured Query Language (SQL) script in Listing 1 to set up the proper fields.

Now, create a users table. Use the SQL script in Listing 2 to set up the fields and add a default user for testing. Note: If you do use this script, note that the test

user’s email address is test@test.com and the password

is “password”.

Creating the Project Structure

Now that the database is ready, you can start defin- ing the objects in your code. You must go through this process twice, once in PHP and again in Adobe ActionScript 3. Tackle the PHP first, and begin by creating a proper folder structure. Because your Flex application will be accessing PHP through your Web

server, you must create the project under your Web

 

LISTING 1

1.

2.

CREATE TABLE IF NOT EXISTS `documents` (

3.

`id` int(11) NOT NULL auto_increment,

4.

`user_id` int(11) NOT NULL,

5.

`name` varchar(255) NOT NULL,

6.

`url` varchar(255) NOT NULL,

7.

`description` text NOT NULL,

8.

`type` varchar(12) NOT NULL,

9.

`file_size` int(15) NOT NULL,

10.

PRIMARY KEY (`id`)

11.

) AUTO_INCREMENT=6;

12.

 

LISTING 2

1.

2.

CREATE TABLE IF NOT EXISTS `users` (

3.

`id` int(11) NOT NULL auto_increment,

4.

`name` varchar(255) NOT NULL,

5.

`email` varchar(255) NOT NULL,

6.

`password` varchar(255) NOT NULL,

7.

PRIMARY KEY (`id`)

8.

) AUTO_INCREMENT=2 ;

9.

10.

INSERT INTO

11.

`users` (`id`, `name`, `email`, `password`)

12.

VALUES

13.

(1, 'Tester', 'test@test.com', 'password');

14.

root. In your Web root folder, create a directory called docs. This folder will be your application directory for the document manager’s PHP services. Within the docs folder, create an include directory; within include, create a folder called services. Figure 3 depicts this directory structure.

Adding the Zend Framework

If you don’t have the Zend Framework set up and added to your PHP include path, you’ll need to download it, and place the relevant files in the /docs directory. If you do have the Zend Framework installed, be aware that Zend_Amf is only included in version 1.7 or later.

If you have an earlier version, you’ll need to take these steps, as well. To get Zend Framework 1.7, visit http://framework.zend. com/. When you’re there, click the large banner that reads “Download Now”. Zend_Amf is included in both the full and minimal versions of Zend Framework, so

choose the one you prefer and save the archive. When the download is complete, extract the archive to a convenient location. The result is a folder named

ZendFramework-[version]. Within that folder is a direc- tory named library. If you have an existing installa- tion of an earlier version of Zend Framework, you can paste this new library folder in place of your old one. If you do not have a Zend Framework installation,

you can simply copy the needed files into your project

FIGURE 3
FIGURE 3

22 | February 2009 www.phparch.com

FEATURE
FEATURE

Rich Internet Applications with Flex and PHP: Part 1

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)

directory (Web Root/docs in this case). You can find the files you need within the library directory, which in turn contains the Zend folder. Copy the Zend folder to your Web Root/docs folder. The resulting folder structure should look similar to Figure 4.

Creating the PHP Classes

Within the /docs/include/services/ directory, cre-

ate a new PHP file called Document.php. Open the new file, and define the Document class and its properties, as shown here:

class Document { public $id = 0;

public $user_id = 0; public $name = ''; public $url = ''; public $description = ''; public $type = '';

public $file_size = 0;

}

Next, create another PHP file in the /services directory called User.php. It should contain something similar to this:

class User { public $id = 0; public $name = ''; public $email = ''; public $password = '';

}

FIGURE 4
FIGURE 4

These files simply define your custom classes and their properties. When they’re complete, save and close

them. You now need to create the files containing the

PHP methods you want to expose to the Flex applica- tion. Create one services file for each of your objects, Document and User. Begin by creating a new PHP file called DocumentService.php. Begin the code by im- porting the custom Document object and declaring the

DocumentService class:

include 'Document.php'; class DocumentService {

The first method to expose is createDocument(), which will enable the Flex application to create new Document objects and save them to the database:

/** * Save a new Document * * @param Document $document */ function createDocument(Document $document) {

$id = $document->id; $user_id = $document->user_id; $name = $document->name; $url = $document->url; $description = $document->description; $type = $document->type;

$file_size = $document->file_size;

}

This first portion simply assigns values from the

Document object that was passed in to variables. You could just refer to the properties of the object without

assigning them, but I’m doing it this way for greater

clarity. After the variables are populated, you can start building a database connection and an INSERT state- ment. Again, for clarity, the database connection will

be explicitly created in each function:

$dbh = mysql_connect(' localhost', 'root', 'password');

$query = "INSERT INTO `docs`.`documents` (id, user_id, name, url, description, type,

file_size)

VALUES

(NULL, '$user_id', '$name', '$url', '$description', '$type',

'$file_size')";

$result = mysql_query($query, $dbh);

}

Note: Be sure to replace localhost, root, and pass- word with your database information and creden- tials.

The other method you need to create is retrieveDocuments(). Use this function to get all

23 | February 2009 www.phparch.com

FEATURE
FEATURE

Rich Internet Applications with Flex and PHP: Part 1

Licensed to 63883 - Joseph Crawford (info@josephcrawford.com)

the user’s documents from the database, and return them to the Flex application. See Listing 3. As you can see, this function selects all the records with the specified user’s id from the documents table, then loops through them, creating a new Document object for each. These objects are placed into an array that is finally returned to the client.

FIGURE 5
FIGURE 5

LISTING 3

 
  • 1. <?php

 
  • 2. /**

  • 3. * Retrieve all a user's Documents from the database

  • 4. *

 
  • 5. * @param int $userid

 
  • 6. * @return array

  • 7. */

  • 8. function retrieveDocuments($userid)

  • 9. {

 

10.

$dbh = mysql_connect(

11.

'localhost', 'root', 'password');

12.

$query = "SELECT * FROM `docs`.`documents`

13.

WHERE user_id = '$userid'";

14.

$result = mysql_query($query, $dbh);

15.

$documentArray = array();

16.

while ($row = mysql_fetch_array($result)) {

17.

$document = new Document();

18.

$document->id = $row['id'];