Accessing backend system…

We're sorry, but your session has expired due to inactivity. Please use your browser to refresh this page and log in to our system again.

Message goes here.

Message goes here.

Message goes here.

LOGIN / REGISTER
VIEW BASKET
SEARCH:
 
php|architect logo
 
SERVICES
  • MAGAZINE
  • PHP|TEK 2012
  • CODEWORKS 2011/12 TOUR
  • BOOKS
  • TRAINING
  • ADVERTISE
 
CHANNELS
  • NEWS
  • PODCAST
  • DEVELOPMENT
  • OPINION
  • WRITE

Meet Josh Holmes

Posted by Cal Evans on April 30, 2010
IN podcast
Tags: Conference · josh holmes · microsoft · motorcycle
 

Related Posts:

  • php|tek’s Call for Papers is Closing Soon
  • Check it out, tek 11 schedule is up!
  • 2011 php|tek Webcast Series
  • CodeWorks is coming to a city near you!
  • PHPDOCX: generating Word documents from PHP

If you don’t know Josh Holmes, come to TEK·X and meet him. Officially is a UX Architect Evangelist for Microsoft. Unofficially though, he is the Microsoft Ambassador to the PHP community. More than a few community members can credit Josh for helping them with problems or just finding answers and contacts within Microsoft.

Josh will be presenting our opening keynote, “The Lost Art of Simplicity” and a regular session “The Lost Art of Simplicity“.

 

 


About the author—Cal Evans is a veteran of the browser wars. (BW-I, the big one) He has been programming for more years than he likes to remember but for the past [redacted] years he's been working strictly with PHP, MySQL and their friends. Cal regularly speaks at PHP users groups and conferences, writes articles and wanders the net looking for trouble to cause. He blogs on an "as he feels like it" basis at Postcards from my life.
 
 
 

OddWeek #7: Talking with a recruiter

Posted by Cal Evans on April 29, 2010
IN podcast
Tags: employment · jobs · recruiting · scott gordon · vaco
 

Related Posts:

  • 5 meta-skills for the PHP developer

URLs and such

  • Scott Gordon’s Blog “The Anti-Pimp”
  • Scott Gordon’s Twitter account (@sgordon70)
  • Vaco – Where Scott Gordon works.
  • Scott Gordon’s recent blog post responding to ABC News
  • Cal’s recent blog post on “Breaking into PHP”
  • Big South Social Media Summit
  • Doktor Blue (The music for this episode) Go click on it, give it a listen and buy a copy.

If you have stumbled upon this page and aren’t a regular listener, subscribe to the php|architect podcast Show Notes mailing list. Each week, when we release an episode, we’ll send you an email with all the links and notes from that show.


About the author—Cal Evans is a veteran of the browser wars. (BW-I, the big one) He has been programming for more years than he likes to remember but for the past [redacted] years he's been working strictly with PHP, MySQL and their friends. Cal regularly speaks at PHP users groups and conferences, writes articles and wanders the net looking for trouble to cause. He blogs on an "as he feels like it" basis at Postcards from my life.
 
 
 

Less Code isn't Always Better

Posted by Keith Casey on
IN Development
Tags: forum · requirements
 

Related Posts:

  • phpBB 3.0.7-PL1 released

If I had more time, I’d write a shorter letter.
~ Mark Twain… T.S. Eliot.. Blaise Pascal… well, someone.

Everyone says “I could build that in an afternoon/weekend/marathon session of caffeine-fueled code-debauchery” but to actually do something well, unsurprisingly, it usually takes longer. I couldn’t help but think of both of these things as I explored a new PHP forum script from Blake O’Hare over at Nerd Paradise. It’s a simple forum system in under 1KB of code. Yes, only 964 bytes according to his count.

To be blunt, it’s not pretty and doesn’t have many features, but honestly, I fluctuate between terrified and impressed by the feat. I’m terrified because if new PHP developers explore this code and believe a Perl-style of “one line to rule them all” and short tag mess is the standard, we’re in trouble.

To all PHP developers: this is not an example of how PHP should be written. This script was an experiment only, but what you can learn from the experiment impressed me:

First, Blake chose a couple of key features to implement and stuck with those. He’s probably had requests for more features and criticism for not having the “useful” things, but sticking to the requirements for the first version is an accomplishment in itself. He prioritized and executed on those priorities.

Next, he practiced simple but effective security techniques. Since “allow HTML formatting” was not in his feature set, he didn’t worry about the messes that come with selective strip_tags and the like. He simply uses htmlspecialchars and nl2br and moves on.

Next, he used single and double quotes in the appropriate places to leverage their strengths. Instead of string concatenation, he counts on variable interpolation to shave character count. It’s not always clear, but it is effective and shows the power of each.

Finally, he uses simple language constructs and concepts. The logic of the script – once you add linebreaks and rename variables – is quite clear. As much as OO principles and Design Patterns are good and useful, they’re often used for evilness that results in mis-direction and obfuscation.

And the criticisms are almost too obvious to note, but I probably should:

  • Short tags (<?) can be a problem if you interact with XML and many hosting providers will have them off anyway, so although not wrong, they’re not recommended;
  • Linebreaks are your friend and should be used when appropriate;
  • Other than simple counters, single letter variable names are not acceptable;
  • Using $_REQUEST instead of $_GET, $_POST, or $_COOKIE hides where the values are provided – while this isn’t problem in this case, it useful to know and limit which methods can perform which actions. For example, a $_GET shouldn’t delete.
  • Mixing business logic and database logic and presentation makes for messes, as it does here;
  • This is a script and not a system, so there’s no reasonable way to extend it to add users, theme it easily, or add all of those other features that “make” it a forum.

More than anything, it’s refreshing and fascinating to see what someone can do when they set clear, simple, direct priorities and focus exclusively on those. As I’ve pondered this, it’s impossible to miss where I’ve drifted from the requirements in my own code and wonder if this scope creep was necessary or optional.

And for the record, this writeup is 4x longer than the code.

 

Photo courtesy of M Anima. http://www.flickr.com/photos/banky177/2099793096/ Released under Creative Commons Attribution licenses.


About the author—Keith Casey has been a developer for over a decade and helps organize various tech communities. Previously, he was a professional agitator within the Washington, DC until he decided to explore Austin, TX in 2010. To pay the bills, he works as a Developer Evangelist for Twilio to get good tools to good developers so they can build great things. Previously, he built large-scale PHP-based systems for organizations ranging from major news companies to small non-profits. In his spare time, he is a core contributor to web2project, works to build and support the Austin PHP community, co-founded the HubAustin coworking space in South Austin communities, blogs regularly at CaseySoftware.com and is completely fascinated by monkeys.
 
 
 

First beta of Doctrine 2 released

Posted by Marco Tabini on April 28, 2010
IN News
Tags: database · doctrine · library · oop · ORM · php
 

Related Posts:

  • Analysis: Following Ruby Makes PHP Number Two
  • ORM Designer
  • Oracle PHP Generator
  • Impel, the Javascript ORM
  • php|tek’s Call for Papers is Closing Soon

The first beta of Doctrine 2, the generic Data Mapper for PHP, has been released today. Doctrine 2 is one of the few object-relational mappers for PHP which implement the Data Mapper pattern instead of the Active Record one; as a result, it is expected to be revolutionary for PHP development as much as Hibernate was for the Java world. For example, Symfony has chosen Doctrine as its default Orm and will follow-up with its second major version, while Zend Framework will provide integration of Doctrine 2 in the form of application resources.

The abstraction of having every object available in memory

The Data Mapper pattern is in general very flexible: you can create domain classes as Plain Old PHP Objects, which do not extend any abstract base class; subsequently a Data Mapper layer abstracts the database as a generic storage. Though, application-specific Data Mappers are generally boring and repetitive to write, while also being prone to errors.

With Doctrine 2, you still produce an object model and, with the aid of mapping metadata in the form of small XML files or annotations, the schema of the related relational database  is inferred, while the client code in the rest of the application lives the illusion of an in-memory object graph.

You can largely ignore the database, considering it an implementation detail. The schema can be generated and created from the command line, and there are more than one thousand unit tests to target the different database management systems used as back ends (MySQL, Postgresql, Oracle, Sqlite) to avoid unpleasant surprises. Depending on your vendor of choice, database-specific SQL code will be generated for the creation phase and during querying.

Underlying technology

Doctrine 2 goes to a great extent to avoid introducing unnecessary code for persistence purposes only. The objects’ content are accessed and reconstituted via reflection, avoiding the use of getters or initialization methods, while part of the object graph can be substituted by lazy-loading proxies which take the place of real objects by dynamically subclassing them; however performance can be problematic if you over use this feature. Moreover, this first beta of Doctrine 2 is the first to support constructors with non-optional arguments; objects are recreated via cloning to bypass the constructor call, further extending the metaphor of objects that never leave memory.

If you have already been using Doctrine 2 in its alpha stage, there is a guide to the upgrade from the alpha 4 version. The official documentation is also fairly good for a project which is not yet officially stable. If you want to contribute to the codebase instead, the development has been moved on github and only a fork divides you from producing a useful patch.


About the author—Marco is the keeper of keys and Chief Garbage Collector at Blue Parabola, php|architect's parent company. He can be found on Twitter as @mtabini.
 
 
 

Enjoy a free article from our April 2010 issue!

Posted by Arbi Arzoumani on
IN php|architect
Tags: magazine · php|architect
 

Related Posts:

  • Today only: Half off all training!
  • Seeing Triple!
  • php|architect Summer eBook Contest Winners!
  • Enjoy a free article from our March 2010 issue!
  • New Classes! New Prices!

We are happy to announce the release of the April 2010 issue of php|architect, in which we cover PHP in the real world. In this issue you will also find our new JavaScript Corner column that lays down the foundation for more advanced subjects coming in the near future.

The FREE article this month is the Drupal Corner column: “Creating Custom Displays with Views”. PHPA APR 10 – Drupal Corner

As always, if you are one of our wonderful subscribers, you can download the issue from your account page—and if you don’t subscribe, you can always buy the single issue from its dedicated page, or—even better—get yourself a healthy discount and subscribe.

Bonus: wondering what the magazine looks like now that we’re electronic-only? Take a look at this free article!

Create Your Own PHP+MySQL CMS

Ever wondered how a CMS works? This article will demonstrate how a very basic CMS can be developed and will assist you in understanding how relatively simple it can be to set up a CMS from scratch.–by Giulio Bai

Adapting Agile Methods for Teams of Two…or Even One

Interested in agile development but worried that your team is too small to make the most of it? This article will introduce you to a new development method that is based on Scrum, but is specifically tailored to even the tiniest of teams.–by Carl Anderson

Aspect-Oriented Programming In PHP

Thought Aspect-Oriented Programming (AOP) was just for Java geeks? Think again. AOP is an amazing tool to reduce code and simplify complex applications, and it can drastically reduce development time and improve application stability and robustness. This article discusses AOP theory and concepts and describes my implementation of an AOP engine in pure PHP.–by Will Barden

Git-Up Your Life

If you are looking for a version control system that you can rely on, check out git. It is stable, reliable, inexpensive, and fast, and that’s just the beginning.–by Sebastian Marek
Don’t forget to download the GIT screencasts created specifically for this article by the author and see git live in action! For more details see the article in this issue on Page 38.

Sideshow PHP

Championing PHP when it is only a small part of the overall organization.–byJames Baugh

JavaScript Corner: PHP & JavaScript

In this first column, we will lay down the basics to help you understand how to communicate between JavaScript and PHP. With this foundation, we will be able to move into more advanced topics in upcoming columns.–by Christian Tiberg

Drupal Corner: Creating Custom Displays with Views

An important part of building a capable Drupal site is creating displays that list your site content. The Views module makes this process fairly easy and very efficient (administratively speaking). In this column, I’ll show you what the Views module is and how to use it.–by Adrian Webb

Download this column for free: PHPA APR 10 – Drupal Corner

Security Corner: Click Me, If You Can!

We’ve thought about vulnerabilities in our server-side code and our client-side scripts, but what about third-party apps that we use? Learn how CSS may be enabling them to hijack our traffic.–by Arne Blankerts

exit(0): Flowers of Winter

Get Marco’s take on the release of PHP 5.3.–by Marco Tabini

About the author—
 
 
 

Putting glob() to the test

Posted by Bill Karwin on
IN Development
Tags: metrics · performance · php
 

Related Posts:

  • php|tek’s Call for Papers is Closing Soon
  • Finding Exactly Where You Are
  • Geolocation: Easier Than It Looks
  • Building the Backside – Part 1
  • Mobile Dashboards Made Easy – Part 2

In a new NetTuts+ post, Marcus Schumann offers a quick tip: Loop Through Folders with PHP’s Glob().

Are you still using opendir() to loop through folders in PHP? Doesn’t that require a lot of repetitive code everytime you want to search a folder? Luckily, PHP’s glob() is a much smarter solution.

The glob() function is convenient but the solution using the fewest lines of code isn’t always the most efficient — if by efficient you mean fastest.

This came up in a question on Stack Overflow in January.  A user asked how best to get a list of files in a directory (excluding “.” and “..” and other subdirectories) and return it as an array.  Several readers offered suggestions, and out of curiosity I benchmarked all their alternatives.  I ran each method 1,000 times on a directory containing about 400 files.  My benchmark results ranged from 12.4 seconds down to 1.2 seconds. That’s a pretty wide spread, so it’s worth paying attention to performance as well as coding convenience. Here are the results in order from slowest to fastest method:

The first method was to use glob() to return an array, and then loop over the result to exclude directories.  This was the slowest, running in 12.4 seconds.

    foreach(glob('*') as $file_or_dir) {
        if( !is_dir($file_or_dir) ) // is_dir will match . and ..
        {
            $files[] = $file_or_dir;
        }
    }

Next was simply using glob() without filtering directories. This ran in 8.1 seconds.

    $files = glob('*');

Using glob() with the optional GLOB_NOSORT argument shows how much impact sorting has on the results. If you don’t need sorted results, it’s worthwhile to say so, because this solution ran in 6.4 seconds — nearly double the performance of the slowest method.

    foreach(glob('*', GLOB_NOSORT) as $file_or_dir) {
        if( !is_dir($file_or_dir) ) // is_dir will match . and ..
        {
            $files[] = $file_or_dir;
        }
    }

The scandir() function is another alternative.  This ran in 6.5 seconds.

    $files = scandir('.');
    $result = array();
    foreach ($files as $file)
    {
        if (($file == '.') || ($file == '..'))
        {
            continue;
        }
        $result[] = $file;
    }

Next using scandir() with array_diff() to filter out the dot-directories had slightly better performance at 6.4 seconds, and this is almost as concise as using glob().

    $files = array_diff(scandir('.'), array('.', '..'));

The opendir() method for which Marcus wanted to find an alternative isn’t so shabby. This ran in 5.3 seconds.

    $files = array();
    $dir = opendir('.');
    while(($currentfile = readdir($dir)) !== false)
    {
        if( !is_dir($currentfile) )
        {
            $files[] = $currentfile;
        }
    }
    closedir($dir);

But using glob() in a bare form with GLOB_NOSORT shows that it may have been pretty costly to loop over the results.  This ran in 2.2 seconds.

    $files = glob('*', GLOB_NOSORT);

Or perhaps is_dir() was the source of the performance problem, because if we use opendir() and filter results by comparing to literal dot-directory names, we get the time down to 1.2 seconds.

    $files = array();
    $dir = opendir('.');
    while(($currentFile = readdir($dir)) !== false)
    {
        if ( $currentFile == '.' or $currentFile == '..' )
        {
            continue;
        }
        $files[] = $currentFile;
    }
    closedir($dir);

Of course it’s desirable to write concise code, but don’t assume this always equates to fast code. Rapid development and rapid code are independent goals, and you need to decide which has greater priority on a case-by-case basis.

And remember to use GLOB_NOSORT unless you actually need the list of files sorted.

Photo courtesy of Rick Audet. http://www.flickr.com/photos/spine/2425394931/ Released under Creative Commons Attribution licenses.


About the author—
 
 
 

Book Review: Reflections on Management

Posted by Cal Evans on April 27, 2010
IN Opinion
Tags: book review · management · Watts S. Humphrey
 

Related Posts:

  • Friday Webcast "Care and feeding of remote developers"
  • 5 tips for finding talent

If you know me, you know that I am passionate about managing software development teams and the projects they work on. So I was very interested when Addison Wesley wrote me and asked me if I wanted to review their latest offering “Reflections on Management: How to Manage Your Software Projects, Your Teams, Your Boss, and Yourself” by Watts S. Humphrey. (I was even more excited when they sent me the ePub version as I’m trying to justify my purchase of an iPad.)

The book is only 288 pages long (539 if you set the point size to a readable size on the iPad) but honestly it is jammed packed with things that managers of software development teams and projects need to know. I really am at a loss for where to start reviewing it because I feel the need to simply reiterate all the points that Mr. Humphrey made in the book.

Who it is for

This but is a must read for anyone managing a medium to large size software development team. Actually, I would say that it is a must read for any C-Level or VP level at a company who either develops software as their primary function or their business is built around software that is built in house. It is that good.

Who it is not for

If you are managing a small shop or working with small teams, this book won’t give you much in the way of practical advice. It gives you some great big picture advice but nothing that you can readily apply on a day-to-day basis.

What is in it

First off, here is my favorite quote from the book.

When projects go badly, our reaction is often to work harder—by which
we mean work longer hours. But it’s rarely that simple. Projects often
go wrong at the very start, and their problems are generally symptoms
of a deeply dysfunctional organization.

Looking back at the projects I’ve been on, managed, or discussed with clients, I can attest to this gem of wisdom. That quote is from Bill Thomas and comes from the preface of the book. Even so, it indicative of the wisdom that is sprinkled liberally throughout the book.

Mr. Humphrey goes on to touch on just about every one of my hot buttons in the rest of the eight chapters. His advice runs the gamut from “how to manage a project”, to “how to manage a team”, to “how to manage your boss”. All of it drawing from his 60 years of experience in IT.

Unlike most modern management books that tend to be pithy with pull-quotes, and written in a style reminiscent of motivational speakers, “Reflections on Management” is written in a much more formal style. (I’d say like you would expect form an old white guy but I am told these days that I am an old white guy.) It’s not stuffy at all but it can be a bit dry at times. What keeps your attention though are his liberal sprinkling of real-life examples of the points he is making.

Conclusion

The ideas and principals espoused by Mr. Humphrey are solid. Even if you disagree with this methodologies, it is difficult for anyone to disagree with the principals. Personally, I think it that a copy of this book should be presented to every management candidate at least 3 weeks before their promotion. Reading this book will help them either determine that they don’t want to be in management or get started on the right foot. Either way, the company and the candidate wins.


About the author—Cal Evans is a veteran of the browser wars. (BW-I, the big one) He has been programming for more years than he likes to remember but for the past [redacted] years he's been working strictly with PHP, MySQL and their friends. Cal regularly speaks at PHP users groups and conferences, writes articles and wanders the net looking for trouble to cause. He blogs on an "as he feels like it" basis at Postcards from my life.
 
 
 

Webcast: Mongo Scale!

Posted by Cal Evans on
IN podcast
Tags: Kristina Chodorow · MongoDB · webcast
 

Related Posts:

  • TEK·X Webcast "Mongo Scale!"
  • Meet Kristina Chodorow
  • New version of MongoDB
  • Webcast: Caching for WordPress
  • Win a free ticket to TEK·X

Kristina Chodorow talks about scaling MongoDB.

This is part of the spring TEK·X webcast series and is sponsored by Microsoft and hosted by php|architect.


About the author—Cal Evans is a veteran of the browser wars. (BW-I, the big one) He has been programming for more years than he likes to remember but for the past [redacted] years he's been working strictly with PHP, MySQL and their friends. Cal regularly speaks at PHP users groups and conferences, writes articles and wanders the net looking for trouble to cause. He blogs on an "as he feels like it" basis at Postcards from my life.
 
 
 

Using a framework? Why you should still learn OO and SQL

Posted by Carl Anderson on
IN Opinion
Tags: best practices · database · frameworks · oo · sql
 

Related Posts:

  • PostgreSQL 9.0 beta released
  • Oracle PHP Generator
  • Development principles
  • Static methods vs singletons: choose neither
  • Arrogance is Limiting Framework Adoption

It was just one short year ago that I began a new job working as a “programmer;” prior to that, I’d styled myself a “Web developer” or something similar, but the new job meant that I’d be doing something much different than before. During the interview, terms like “object-oriented programming” and “SQL” were tossed about, and I truthfully acknowledged that I understood and used such things in my working life, although not terribly frequently. (My previous job was a Filemaker and procedural programming shop.)

When I arrived and began programming Web applications, I took a look at CakePHP, and suggested we use it. Soon, it was implemented for basically all new development projects. I quickly realized, though, that I had a huge knowledge gap. Sure, I know what object-oriented programming is, and even done a bit of stuff previously, but when my boss suggested we might use things like an observer pattern on some legacy code, or when he talked of extending CakePHP’s controllers in various ways, I knew I’d need to expand my skills.

And even with the database side of things, where I felt a bit more comfortable, I found that my knowledge of SQL was a bit rusty in spots—such that I couldn’t decide if what CakePHP was doing (say, with joins) was correct or whether I’d need to do things differently.

Frameworks like CakePHP, Zend Framework, and Symfony allow you to quickly and easily write a “real” application, but in doing so they tend to shield you from things like raw SQL and obviate the need to manually load or extend classes, for example. I contend that this is a good thing, but only if you understand the “guts” of the system—that is, OO and SQL, for example.

Why? Consider what happens if your framework loads data into a variable in a completely unexpected way. If you don’t understand the SQL that’s going on under the hood, what chance do you have of determining whether the framework is wrong—or perhaps you’re not calling the data in the right way?

In a similar vein, knowing how to program in an object-oriented way is also vital. I’ve looked at the Lithium framework recently, and confess to not understanding a lot of what’s going on. Sure, there’s some documentation, but I’m certain my learning process would be helped if I understood things like singletons, or lazy loading, or even anonymous functions.

This goes beyond mere debugging or learning new technologies. As in the example I gave earlier, it’s quite possible that you’re going to hit a point at which you want to do something the framework doesn’t do natively; in this case, your OO skills come into play, letting you get the job done. Or what if the framework can’t handle the poorly designed legacy database you inherited? Suddenly your SQL-fu doesn’t look so useless, since you’ll be able to write occasional custom queries when the framework falls flat.

But even beyond that, there will be times during which you can’t (or don’t want to) use a framework. I recently took a look at CouchDB and PHPillow, and I confess that I still can’t get PHPillow to work. My OO chops are simply not up to par. That experience taught me that I really need to start taking my favorite PHP book to bed with me a little more frequently.

So, even if you use a framework, take the time to get to know object-oriented programming and SQL (useful even if you’re using a document-oriented database, I think). They truly form the building blocks of programming.

Image of building blocks from Flickr user Artful Magpie. Published under a Creative Commons Attribution-Noncommercial-No Derivative Works 2.0 Generic license. http://www.flickr.com/photos/kmtucker/3355551036/


About the author—Carl works for Michigan State University's National Superconducting Cyclotron Laboratory as an Applications Programmer. A Zend Certified Engineer, Carl uses PHP in creative ways to solve some of the lab's interesting software problems. He's interested in PHP, human-computer interaction, and all manner of "shiny new things."
 
 
 

How I learned to stop worrying and start loving the wizard – Part 1

Posted by Cal Evans on April 26, 2010
IN Development
Tags: adobe · amf · data connection wizard · flash · flash builder · flex · php · zend framework
 

Related Posts:

  • Mobile Development with PHP
  • How I learned to stop worrying and love the wizard – Part 3
  • Learning to be Flexible
  • Meet Ryan Stewart
  • Building the Backside – Part 1

I hate wizards. No, not the Harry Potter kind (although, I will confess I don’t like that kind very much either), but I hate wizards that pretend to help programmers do things. More often than not, they end up either getting in the way or hiding some magic that I need to know about. This isn’t really a problem when working with PHP, since most of the code I write in PHP is back end code and doesn’t require a UI per se. That being the case, wizards aren’t a normal part of my life. (For the record, the closest I come to using a wizard regularly is Zend_Tool but even then, I know enough about the magic going on to write my own providers, so it’s not a wizard as much as it’s just a convenience.

However, of late I have been working with Flex Builder 3 and now Flash Builder 4 (FB4). While wizards for programming might not be the norm for PHP developers, Flash and Flex developers apparently do like them. To be honest, after working with FB4 now for a few weeks, I am starting to see that wizards aren’t all bad—in fact, some of them are even kind of cool. In this two-part post, I want to talk about connecting Flex applications to server-side PHP APIs using the Data Services wizard that ships as part of FB4.

The Old Way

First, let me say that, as nice as the new Data Services are, I worked with Flex Builder 3 and really liked the old way of connecting to data services. The HTTPService object was super flexible and very simple to use—in fact, when I first started working on the code for this series, it was my intention to prove that the new way was inferior to the old way. It’s funny how technology can surprise you sometimes.

In Flex Builder 3, the way you connected to an API (XML or JSON usually) was to use something like this:

<s:HTTPService id="twitter"
               showBusyCursor="true"
               fault="showFault(event)"
               result="doSomething(event);"
               url="http://example.com/myapi" />

See, that is easy. There is no behind the scenes magic: like PHP, I can get what I need done, done and move on to the next task. I’ve built several AIR and AIR2 applications using HTTPService as my multi-tool for connecting to the outside world because it is just so easy to work with; I like simple tools and HTPService was as about as simple as it got. This is why I was nonplussed when Adobe added “Data Services” to Flash Builder 4.

The New Way

When you first create an FB4 Application, you will immediately notice a difference from Flex Builder 3, the “Declarations” section of the code

<fx:Declarations>
<!-- Place non-visual elements (e.g., services, value objects) here -->
</fx:Declarations>

FB4 now divides your declarations from your visual elements. That is the first thing you have to get used to. It is still easy to hand code an HTTPSerivce—you just have to put it in the new <fx:Declarations> section.

This is still my favorite method for connecting to third party web services like Twitter’s API (the Hello World of Web 2.0). Fetching data like this is dead simple, but, if you want to get into more complex operations like updates and deletions, you inevitably end up writing code by hand. Depending on the API you are talking to, this can quickly become tedious and, if you are a good OO programmer, it will most likely mean encapsulating all of this in its own class. If that sounds familiar, the new Data Services option is going to save you a lot of time and hand coding.

Figure 1: Connecting to Data Services

The “Connect to Data Service” button is on the upper right of the Data Services tab. Clicking that button will open the wizard and help you get connected.

Figure 2: Selecting Service Type

The first thing you have to do is select the type of service you are connecting to. PHP is one of your options. Selecting PHP will require you to point the wizard to the actual class you will be talking to so that it can use PHP’s reflection to gather information about the class. This means that if the API is hosed on a server you don’t have access to; you will need to use HTTP instead. While this will negate some of the benefits of the wizard, it will still set things up for you and you can manually configure your Data Service.

Figure 3: Configuring PHP Service

NOTE: For some reason, the class has to be inside your web root. Since this is considered a bad practice, you probably wouldn’t normally have the class available where Flash Builder 4 is looking.  I feel confident that the answer to this conundrum is a simple configuration setting but I’ve yet to find it. For the purposes of the demo, I put everything inside of web root. I will post a follow-up post once I have a solution for this problem.

Once you have entered a class location, it will attempt to use PHP’s Reflection to pull out methods, parameters and return types. To do this, Flash Builder 4 needs Zend Framework. If you have not already configured it, you will get the following dialog box:

Figure 4: Install Zend Framework

If you already have Zend Framework installed on your system you can save yourself ~20MB by pressing cancel, backing out, finding amf_config.ini and setting the zend_path setting.

For the purposes of demonstration, let’s have it generate a sample class for us. (See Figure 3), Again, everything needs to be inside the web root for things to work properly.

NOTE: This feature is for prototyping only! The program warns you, and for good reason, that you do not want to use this code in production, ever, for any reason, period.

Figure 5: Generate a sample PHP class

Flash Builder will generate the PHP class plus all the necessary ActionScript code to manipulate a table in your database. The resulting class will have your database credentials hard coded in it and will be in your web root. You can see why it’s not a good idea to use this code in production now.

That having been said, I gave it the wp_user table from a test install of WPMU I have on my local machine and it did a good job. The PHP code is quite good. It is primarily procedural code wrapped in an object wrapper but it for prototype code, it’s good.

Since FB4 uses PHPDoc blocks as part of its introspection process, it generates the appropriate docblocks for each of the methods. In my case, it generated 6 methods necessary to add/edit/delete and list the users of my test blog. More importantly though, the wizard created 2 ActionScript classes necessary to talk to the API, _Super_WpusersService.as and WpusersService.as, both in the Services directory. The first one, _Super_WpusersService.as is where the code necessary to talk to the API is hosted. The header comment makes note that this is generated code and should not be edited. It can however, be regenerated at will. The second file, WpusersService.as, is where any customizations go. It is this class, a subclass of the first class and  is the class that is actually instantiated. You can override any of the methods and add your own functionality here. This is a verbose but overall well-thought-out solution to having generated code will still allowing for modifications.

Conclusion

As you can see, connecting to PHP code from Flex is actually much easier in Flash Builder 4 and now you actually have more options with the ActonScript  classes being automatically built for you. The old way of doing things still works and there are legitimate cases where it is the best answer. However the new Data Services wizard does have some nice benefits.

Figure 1: Connecting to Data Services
Figure 1: Connecting to Data Services
Figure 2: Selecting Service Type
Figure 2: Selecting Service Type
Figure 3: Configuring PHP Service
Figure 3: Configuring PHP Service

Figure 5: Generate a sample PHP class
Figure 5: Generate a sample PHP class
Figure 4: Install Zend Framework
Figure 4: Install Zend Framework
Flash_Builder 4



About the author—Cal Evans is a veteran of the browser wars. (BW-I, the big one) He has been programming for more years than he likes to remember but for the past [redacted] years he's been working strictly with PHP, MySQL and their friends. Cal regularly speaks at PHP users groups and conferences, writes articles and wanders the net looking for trouble to cause. He blogs on an "as he feels like it" basis at Postcards from my life.
 
 
 

This month's issue

January 2012
Buy · $5 — Subscribe · starts at $35
 

 

Upcoming Training Courses

Course Start Date
Essential PHP 2012-02-03
AJAX Programming with PHP and … 2012-02-10
Essential Zend Framework 2012-02-17
Mobile HTML5, JavaScript and P… 2012-03-02
Professional PHP Development 2012-03-09
 

About us

  • What we do
  • Contact us
  • Write for us

Policies & legal

  • Customer support
  • Privacy policy
  • Refund policy
  • Terms & Conditions

Online Store

  • Magazine
  • Training courses
  • Books

Special sections

  • Codeworks 2011
 

Copyright © 2002-2012 Blue Parabola, L.L.C. — All amounts in USD - WP3