php[architect] logo

Want to check out an issue? Sign up to receive a special offer.

How I learned to stop worrying and love the wizard – Part 3

Posted by on June 14, 2010

In part 1, we discussed how to use the new Flash Builder 4 Data Connection Wizard to connect to a PHP API. We used FB4’s prototyping feature to build a simple class that allows us to read/write users from a WordPress user list. In part 2, we discussed how to use that data connection to ease building data-centric applications. For both of these however, we used the simple prototype class that we generated. It is also possible to use your own code to do the same thing as long as you understand what needs to be there. In this, part 3, we will write a simple class and use it with the Data Connection Wizard.

Before all else, write the code

To keep this simple, I will follow the same rules as before, I will not attempt to add or delete users, just list them and then allow them to be edited. We will call our class WPUser.

As before, for Flex to be able to inspect it, it has to be within the webroot of your project.

class WPUser
{

    protected $db;

    /**
     * @return void
     */
    public function __construct()
    {
        $this->db = mysqli_connect('localhost','root','','wpmu');
        return;
    }

When we create the class, let’s go ahead and create a connection to the database. Let me make a couple of notes here for those who might be concerned by that line. First, this code is running on my local machine against my test database. So yes, root is the user I use and there is no password on it. This is not a best practice. Please don’t copy and paste that code and just add your root password.

Second, if I were building a real application, I would use dependency injection to had my model a connection to the persistent data store. However, this is simple example so I am taking a few liberties. Again, please don’t copy this code verbatim and use it.

    /**
     * @return array
     */
    public function listUsers()
    {
        $stmt = mysqli_prepare($this->db, "SELECT * FROM wp_users");

        mysqli_stmt_execute($stmt);

        $rows = array();

        mysqli_stmt_bind_result($stmt, $row->ID, $row->user_login, $row->user_pass, $row->user_nicename, $row->user_email, $row->user_url, $row->user_registered, $row->user_activation_key, $row->user_status, $row->display_name, $row->spam, $row->deleted);

        while (mysqli_stmt_fetch($stmt)) {
            $row->user_registered = new DateTime($row->user_registered);
            $rows[] = $row;
            $row = new stdClass();
            mysqli_stmt_bind_result($stmt, $row->ID, $row->user_login, $row->user_pass, $row->user_nicename, $row->user_email, $row->user_url, $row->user_registered, $row->user_activation_key, $row->user_status, $row->display_name, $row->spam, $row->deleted);
        }

        mysqli_stmt_free_result($stmt);
        mysqli_close($this->db);

        return $rows;
    }

Ok, our listUsers() function is next. If you are paying attention, you will notice that it looks a lot like the one in the prototype class that FB4 generated. That is because it is good example code so why re-write it? The important thing to note here is the docBlock comment at the top. FB4 doesn’t actually know anything about PHP code. Instead, it relies on the docBloc comments to figure out parameters and return types.

To show the results of incorrect settings in a docBlock, I’ve changed the return value to string for listUsers()

    /**
     * @return array
     */
    public function listUsers()

Now, trying to attach our data grid to our new WPUser class will show this error:

You can see that the return type for listUsers() is now reported as String even though I’ve not actually changed the code. Since string is not an acceptable return type for a DataGrid to process. So make sure the docBolcs are not only correct, make sure that the return value you are specifying is valid for the intended use.

Now, let’s look at the code for fetchUser(). This method shows us how to specify a parameter sot ha FB4 can pick it up.

    /**
     * @param int $id
     * @return array
     */
    public function fetchUser($id)
    {
        $stmt = mysqli_prepare($this->db, "SELECT * FROM $this->tablename where ID=?");
        mysqli_stmt_bind_param($stmt, 'i', $id);
        mysqli_stmt_execute($stmt);
        mysqli_stmt_bind_result($stmt, $row->ID, $row->user_login, $row->user_pass, $row->user_nicename, $row->user_email, $row->user_url, $row->user_registered, $row->user_activation_key, $row->user_status, $row->display_name, $row->spam, $row->deleted);

        if(mysqli_stmt_fetch($stmt)) {
            $row->user_registered = new DateTime($row->user_registered);
            mysqli_close($this->db);
            return $row;
        } else {
            mysqli_close($this->db);
            return null;
        }
    }

Again, making sure you get these correct is the secret to making sure the docBlocs are correct.

Rounding out our WPUser class is the update() method. This takes as a parameter a stdClass. Behind the scenes, FB4 is using Zend_Amf (Remember when we installed Zend Framework?) to communicate with PHP using the Action Message Format. This allows it to serialize classes in FB4 pass them to PHP and unserialize them.

    /**
     * Updates the passed item in the table.
     *
     * Add authorization or any logical checks for secure access to your data
     *
     * @param stdClass $item
     * @return void
     */
    public function update($item) {
	$stmt = mysqli_prepare($this->db, "UPDATE $this->tablename SET user_login=?, user_pass=?, user_nicename=?, user_email=?, user_url=?, user_registered=?, user_activation_key=?, user_status=?, display_name=?, spam=?, deleted=? WHERE ID=?");
	throw new Exception(mysqli_errno($link), mysqli_error($this->db));

	mysqli_stmt_bind_param($stmt, 'sssssssisiii', $item->user_login, $item->user_pass, $item->user_nicename, $item->user_email, $item->user_url, $item->user_registered->toString('YYYY-MM-dd HH:mm:ss'), $item->user_activation_key, $item->user_status, $item->display_name, $item->spam, $item->deleted, $item->ID);
	throw new Exception(mysqli_errno($link), mysqli_error($this->db));

	mysqli_stmt_execute($stmt);
	throw new Exception(mysqli_errno($link), mysqli_error($this->db));

	mysqli_stmt_free_result($stmt);
	mysqli_close($this->db);
	return;
    }

}

Changing out Data Connections

Now that we’ve created a class that we can hook a Data Connection to, let’s setup our application to use the new one instead of the old one. Follow the instructions in part 1 of the article with one exception. Do not have it generate a sample class. Instead, click the Browse button and find the WPUser.php you just created. Once you do, the wizard should look something like this:

If everything looks correct, go ahead and press Finish and you will see the new Data Service in the Data Services panel.

To make it the data service for your Data Grid, click on the grid. A small icon will appear in the upper left corner like this:

Clicking on that icon will bring up a dialog that will allow you to select WPUser service. Once you do that it will need to test the call and gather information on the return value. Clicking on the “Change return type…” link (as highlighted below) will bring up a dialog that will walk you through the two steps for automatically discovering and setting the return type.

Once you’ve done that, your data grid will now be using the WPUser data service instead of the original Wpusersservice service.

Wrapping it up

I’ve attempted to give you a taste for the different things that the Data Connection Wizard can do for you when working with PHP files. In the right hands, it is a powerful tool and can save developers time and headaches. However, there are some limitations you have to be able to work with to use it.

The main one, as I’ve pointed out and discussed in previous articles, is that all of your PHP code has to be accessible in your web root. FB4 will attempt to explore your code to analyze it but it does so by opening each file and reading it as opposed to using PHP’s native reflection methods to gather this info. This isn’t a problem as long as you realize it.

In a future article we will examine the alternative to using the PHP Data Connection Wizard, the HTTP Data Connection Wizard.

…and yes, I still dislike Harry Potter. Not as a person mind you. Wizards in real life as well as in fiction tend to annoy me. I don’t like magic when it comes to my code, I want to see what is going on.


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.
Tags: , , ,
 

Responses and Pingbacks

[…] Click Here to Read Full Story   […]

Wizards can be great, they solve our problems in only a few clicks, but if positive things are summed up, the negative isn’t far away…

Wizards can be of great help, and do a great job, in this case it can come in handy. But in some cases a wizard creates a lot of code in the back, without any notice of the user. If you are a professional, and know what the code does and really understand it, this is no problem.
But in most cases, wizards are used by noobs or starters, and when a problem comes along in the future, they might get into trouble as they cannot change the code without making the problem even worse.

I only want to say, be careful in the use of wizards, it might be tricky in the end if you are not fully aware of what is happening…

In the book ‘The pragmatic Programmer‘, a whole chapter is dedicated to the use of wizards and is a must read for every self-respecting software developer!!!

Leave a comment

Use the form below to leave a comment: