Archive for May, 2009
JSON Utility 0.1 Released!
May 31st
I have just created an application (still a very early version!) that is aimed at making development with the JSON data-interchange format a whole lot easier. This application basically accepts a JSON string, validates it (using the JSONDecoder class from as3corelib) and generates an ActionScript 3.0 class from it. You can download it here!
The opening screen:
…and the output!
I’ve got quite a few more features planned (hence the version “0.1″). If you have any comments, queries or suggestions, leave them in a comment below.
Thanks to Dan White for the use of his skin Granite!
Parsing XML in PHP5 with SimpleXML
May 16th
PHP5 includes a library for parsing XML data called SimpleXML. This class (and associated classes) is a fantastic way to parse XML data in PHP5. Parsing of XML comes into almost every project i work on, whether it be creating/manipulating RSS feeds, sending data between Flex and PHP, and whatever else the client wants really
Below is the XML data i will be working with in this tutorial:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | <languages> <language year="1999"> <name>ActionScript 3.0</name> <description>ActionScript is a scripting language based on ECMAScript. ActionScript is used primarily for the development of websites and software using the Adobe Flash Player platform (in the form of SWF files embedded into Web pages).</description> </language> <language year="1995"> <name>PHP</name> <description>PHP is a scripting language originally designed for producing dynamic web pages. It has evolved to include a command line interface capability and can be used in standalone graphical applications.</description> </language> <language year="1995"> <name>Java</name> <description>Java is a programming language originally developed by James Gosling at Sun Microsystems and released in 1995 as a core component of Sun Microsystems' Java platform. The language derives much of its syntax from C and C++ but has a simpler object model and fewer low-level facilities. Java applications are typically compiled to bytecode that can run on any Java virtual machine (JVM) regardless of computer architecture.</description> </language> <language year="2007"> <name>LOLCODE</name> <description>LOLCODE is an esoteric programming language inspired by the language expressed in examples of the lolcat Internet meme. The language was created in 2007 by Adam Lindsay, researcher at the Computing Department of Lancaster University.</description> </language> </languages> |
Now, say we wanted to parse this XML file using PHP, and extract the name of each of these languages…
1 2 3 4 5 6 | <?php $languages = simplexml_load_file("languages.xml"); foreach($languages as $language) echo $language->name."<br/>"; ?> |
In the above code, one can extrapolate that SimpleXML will go through your XML file and assign the nodes to an array, and in that array it will create an untyped Object with the data assigned to properties of that Object.
Simple enough, right?
Now, what if you wanted to access an attribute of each of these languages (in this scenario – the year attribute of each language)?
That’s also really easy with SimpleXML! You can reference the attributes of each node by using array notation…
1 2 3 4 5 6 | <?php $languages = simplexml_load_file("languages.xml"); foreach($languages as $language) echo $language["year"]."<br/>"; ?> |
Ok. So what if you wanted your returned data to be mapped to a class? I.e. each element in the array that is returned must be strongly typed to a class, rather than the unspecific stdClass Object that’s returned by default… This can also be done with SimpleXML!
Here’s the Language.php class i created for the returned array elements to be typed as (note that it ,must extend the SimpleXMLElement class):
1 2 3 4 5 6 7 8 | <?php class Language extends SimpleXMLElement { public $year; public $name; public $description; } ?> |
…and the code to return each array element as a Language Object:
1 2 3 4 5 6 7 8 9 | <?php require_once("Language.php"); $languages = simplexml_load_file("languages.xml", "Language"); foreach($languages as $language) { print_r($language); } ?> |
If you look at the output, you will see that the year attribute is not assigned to $year property of the Language class, but rather to a @attributes property. However, if you add this function to the Language.php class, the attributes will be assimilated to their respective properties:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | <?php class Language extends SimpleXMLElement { public $year; public $name; public $description; public function attrToProp() { foreach($this->attributes() as $prop => $val) $this->$prop = (string) $val; } } ?> |
…and run the script again, but adding this line of code:
1 2 3 4 5 6 7 8 9 10 | <?php require_once("Language.php"); $languages = simplexml_load_file("languages.xml", "Language"); foreach($languages as $language) { $language->attrToProp(); // -- add this line print_r($language); } ?> |
Using Conditional Statements with MySQL
May 14th
While working on a project, i got lazy (as i always do…); I didn’t feel like fetching an array of rows from MySQL and filtering the data in PHP according to a condition… Too much of a ballache to be honest. I thought: ‘Fuck it… Let’s see if one can use conditional statements in MySQL‘.
After doing a little research, i came across this page (http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html). After scouring through the normally indecipherable MySQL reference manual, i managed to get the hang of it…
Although the scenarios where the application of this functionality are few and far between, i felt it’d still be a cool idea to share this (seemingly) arbitrary tit-bit.
Consider the following scenario…
You have a table of users. In this table, you keep the following information about each user:
- name
- surname
- gender
Now, depending on the gender of your user, you would like to return their details with a certain prefix, namely Mr for a male or Ms for a female. Here’s the database structure, and two rows of sample data:
CREATE TABLE IF NOT EXISTS `users` ( `name` VARCHAR(255) NOT NULL, `surname` VARCHAR(255) NOT NULL, `gender` enum('M','F') NOT NULL ) ENGINE=MyISAM DEFAULT CHARSET=latin1 ROW_FORMAT=DYNAMIC; -- -- Sample data -- INSERT INTO `users` (`name`, `surname`, `gender`) VALUES ('Joe', 'Shmo', 'M'), ('Jane', 'Shmane', 'F');
…and here’s the SQL query
SELECT *, CONCAT(IF(gender = "M", "Mr ", "Ms "), name, " ", surname) AS fullName FROM users
If that looks a little too indecipherable/complicated, here’s the previous query in a more simplified (albeit less efficient) way:
SELECT *, IF(gender = "M", CONCAT("Mr ", name, " ", surname), CONCAT("Ms ", name, " ", surname)) AS fullName FROM users
Essentially the IF() statement is structured like this:
IF(condition, true code, false code)
However, you can place an IF statement anywhere in a query (from what i can tell thus far), it gets executed in place and is replaced by either the true code or the false code.
Another (much simplified) example:
SELECT IF(1 > 0, "TRUE!", "FALSE!");
…and that’s conditionals with MySQL!
Handling multiple remote services with RemoteObject – the easy way!
May 6th
Ok, so you’re developing a Flex application with a bit of server-side integration (using PHP, Java, Ruby, .NET, etc) and your application is getting a little intense; multiple service calls to the server, custom logic for success and failure of said calls and everything in between.
You could use the following syntax for handling mutliple method-calls from a remote script (in this example MyService):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | <mx:RemoteObject id="service" destination="amfphp" source="MyService" makeObjectsBindable="true"> <mx:method name="doSomething" result="doSomethingResult(event)" fault="doSomethingFault(event)"/> <mx:method name="doAnotherSomething" result="doAnotherSomethingResult(event)" fault="doAnotherSomethingFault(event)"/> </mx:RemoteObject> <mx:Script> <![CDATA[ private function doSomethingResult(event:ResultEvent):void { // custom logic } private function doSomethingFault(event:FaultEvent):void { // custom logic } private function doAnotherSomethingResult(event:ResultEvent):void { // custom logic } private function doAnotherSomethingFault(event:FaultEvent):void { // custom logic } ]]> </mx:Script> |
I dunno about you, but to have to define special tags in MXML for each bloody method in your script is too much effort (and can leave you with some nasty/tricky bugs if you forget to add a new tag after adding a new method in your server-side script!). I used the following mechanism in my post about integrating CodeIgniter, Flex and PHP if i remember correctly… Give me a break… I was too lazy to check (it’s midnight and i’m sleepless).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 | <mx:RemoteObject id="service" destination="amfphp" source="MyService" makeObjectsBindable="true" result="resultHandler(event)" fault="faultHandler(event)"/> <mx:Script> <![CDATA[ private function resultHandler(event:ResultEvent):void { var message:RemotingMessage = event.token.message as RemotingMessage; switch(message.operation) { case "doSomething": // custom logic break; case "doAnotherSomething": // custom logic break; default: trace("Shit... Missed this one... " + message.operation); break; } } private function faultHandler(event:FaultEvent):void { var message:RemotingMessage = event.token.message as RemotingMessage; switch(message.operation) { case "doSomething": // custom logic break; case "doAnotherSomething": // custom logic break; default: trace("Shit... Missed this one... " + message.operation); break; } } ]]> </mx:Script> |
Seems much easier, doesn’t it? Essentially all you’re doing is examining the event parameter of the ResultEvent or FaultEvent, finding which method was just called and acting accordingly… This will work with any number of method calls, from any number of different RemoteObjects. You can point them all to the same handlers!
If you guys have any alternative ways of doing this, let me know!

