Getting all articles, ordered by title, with EntityFieldQuery

EntityFieldQuery is a class that can be used to... query entities... by field! And, other things too.

Today I needed to get a list of all nodes, of a certain type, ordered by title. One might go to the database for this, but I decided to do things the 'right' way, by leveraging the Drupal 7 entity system.

  // Create a new EntityFieldQuery.
  $query = new EntityFieldQuery();
  // Filter by the 'node' entity.
  $query->entityCondition('entity_type', 'node')
    // Filter by the 'article' bundle.
    ->entityCondition('bundle', 'article')
    // OrderBy the 'title' property. Yup, because 'title' is a property of Node, not a field.
    -> propertyOrderBy('title', 'ASC');
  // Execute the query and get the results.
  $result = $query->execute();
  // The result is returned as an associative array of entity types, with inner arrays keyed by entity id.
  $nids = array_keys($result['node']);
  // Now that we have all of the nids for all articles ordered by title we can load the nodes.
  $articles = node_load_multiple($nids);

I've used EntityFieldQuery before, but I must admit that I had to do some research today to figure out how to order by title. I knew that it was possible to fieldOrderBy() and discovered that it was possible to entityOrderBy() (although admittedly I don't understand entityOrderBy yet). Remembering that title is a property of Node helped me find my way to propertyOrderBy().