Sort an ArrayCollection in Flex

Posted on August 12, 2010
by

As nothing’s as straight forward as PHP, I had to write my own class to sort ArrayCollections. My work was inspired by what Peter Dehaan did.

The method is to be used as follows:

ArrayUtils.sort(games, "playerScore", "DESC", true);

to sort an ArrayCollection of games by player score, with a descending order. The last parameter indicates that we want a numeric sorting rather than a alphabetical sorting.

I encapsulated the method in an ArrayUtils class, but you’re free to do as you wish. That’s because I think I will add more methods to my class in a near future. You can download the class here: ArrayUtils.as

package classes.utils
{
import mx.collections.ArrayCollection;
import mx.collections.Sort;
import mx.collections.SortField;
 
/**
* Useful functions to manipulate arrays
*
* @author Cyril Mazur cyrilmazur.com
*/
public class ArrayUtils
{
/**
* Sort an arrayCollection by key
* order MUST be either "ASC" or "DESC"
*
* @author Cyril Mazur cyrilmazur.com
* @see http://blog.flexexamples.com/2007/08/05/sorting-an-arraycollection-
using-the-sortfield-and-sort-classes/
*
* @param ArrayCollection arrayCollection
* @param String sortBy
* @param String order
* @param Boolean numericSort
*
* @return ArrayCollection
*/
public static function sort(arrayCollection:ArrayCollection, sortBy:String,
order:String, numericSort:Boolean):ArrayCollection {
/* Create the sort field and fill it */
var dataSortField:SortField = new SortField();
dataSortField.name = sortBy;
dataSortField.caseInsensitive = true;
dataSortField.numeric = numericSort;
 
/* Set the order, by default it's ascending */
if (order.toUpperCase() == "DESC") {
dataSortField.descending = true;
}
 
/* Create the Sort object and add the SortField object
created earlier to the array of fields to sort on. */
var dataSort:Sort = new Sort();
dataSort.fields = [dataSortField];
 
/* Set the ArrayCollection object's sort property to our
custom sort, and refresh the ArrayCollection. */
arrayCollection.sort = dataSort;
arrayCollection.refresh();
 
/* Return the collection */
return arrayCollection;
}
}
}

Download the source here: ArrayUtils.as

I’m open to any suggestion to improve the code :-)

getDefinitionByName(), ReferenceError: Error #1065: Variable is not defined

Posted on August 8, 2010
by

In Flex (as in Java, or even PHP) you can dynamically get references to a class from its name. Just to remind you, it’s that easy in PHP:

$className = 'User';
$myUser = new $className;

Not a lot more complicated in Java:

Class className = Class.forName("User");
Object myUser = className.newInstance();

The Flex way is as follows:

var className:Class = getDefinitionByName("package.User") as Class;
var user:Object = new className();

But despite PHP and Java, there is a little subtlety for Flex. You can encounter the following error when executing this code:

ReferenceError: Error #1065: Variable User is not defined

And it took some time for me to figure out what the problem was… After looking at the right speling of my class name and so worth, I figured out that the problem comes from the way that Flex compiles its code. Actually, Flex compiles its code so that if a class is not used, it will keep this class off the final compiled program. And even a

import package.User

won’t change a thing. The only way to get it done, is to put a reference to that class somewhere in your code, wherever … as long as it’s referenced somewhere, Flex will not forget the class at the compilation process. A simple and ugly way is to add a dummy reference to this class somewhere, like:

private var _dummyUser:User;

or shorter:

User;

and you’re done.

It has been already discussed on forums and blogs, but as I came across this I had to write an article about it :)

Unique ID for Java classes

Posted on August 5, 2010
by

As I was writing some Java code for my finale dissertation, I wanted to give my objects an unique ID in order to distinguish them easily. I thus wrote the following abstract class that does the job well for me:


package motd.utils;
 
/**
* Makes a class identifiable with an unique ID for its objects
*
* @author Cyril Mazur cyrilmazur.com
*/
abstract public class Identifiable {
 
  /**
  * The object's ID
  */
  protected int id;
 
  /**
  * Constructor
  */
  public Identifiable() {
    this.id = getNextId();
  }
 
  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  // GETTERS AND SETTERS
 
  public int getId() {
    return id;
  }
 
  // - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
  // STATIC
 
  /**
  * Index for the object's ID
  */
  protected static int index = 0;
 
  /**
  * Return next ID
  * @return int
  */
  protected static int getNextId() {
    return ++index;
  }
}

Download Identifiable.java here

Make your class to extend Identifiable, don’t forget to call the super() constructor, and you’re done.

Now, all of your objects will have an ID attribute which will identify them in a unique way. Of course this attribute is private, and I’ve added a getter for it, since it’s a good OOP practice.

Note 1: with my class, the counter is global. It means that when the counter increments, it increments for all the classes that extend Identifiable in your program. Two objects of different classes will never have the same ID. I don’t know if it’s wrong or if it’s right in the end… If someone has an idea on how to make the counter dedicated to each class, feel free to leave a comment :)

Note 2: I’m far from being a god of Java, and it’s likely that my tip is just for beginners who don’t use frameworks that would already encapsulate this feature

Socket server in PHP

Posted on March 29, 2010
by

A socket UK plug

Recently I had to develop a chat room system very quickly. I absolutely wanted to use my favorite language: PHP. So I had to figure out how do sockets work in PHP, and how to give PHP a daemon behavior (read: Give PHP a daemon behavior).

I found many resources on the Internet, more or less exact, more or less commented… All the articles I read were going around the same solution, and actually by having read some other articles about sockets in C and Java afterwards, it’s indeed the same logic for the 3 languages.

I won’t explain the principles of sockets, nor how to implement them in PHP, it’s already fully documented on the Net (see at the bottom of the article). However, as I wrote a class to help me creating socket servers in PHP, I’m going to share it and explain how to use it.

Give PHP a daemon behavior

Posted on March 22, 2010
by

BSD daemon with PHP logoWell, I fully admit PHP is not the best language to write daemons, because of all the performance issues we all know, and infinite loops are not the most beautiful thing you can see in a procedural script. However, it may happen that for a reason X or Y, you want to use PHP to write daemons (it has even happened to me!).

These are my thoughts about this subject. Again, I read a lot of articles over the Internet, took the best of each, add some of my imagination, and made a set of functions and scripts to easily turn a PHP script into a daemon. For those who want the code right now, help yourself: PHP daemonizer

PHP class for cURL

Posted on November 6, 2008
by

I discovered libcurl a long time ago, but never really worked with… until yesterday! It was during a Solaris course, my classmate showed me some stuff he did with libcurl, and I was amazed of the capabilities! On the evening I jumped onto my macbook and wrote a class to manage cURL requests.

My main utilization is to get quickly, and in an automatic manner, information on my accounts in some websites (such as social networks, affiliation programs or banks – yes, libcurl handle HTTPS!) and why not retrieving all of that in a widget.