If you aren't using Entity API to create nodes, you are doing it wrong

If you aren't using Entity API to create nodes, you are doing it wrong

For many years now I've written code to programmatically create nodes. I've done it for dozens of clients starting with Drupal 5. It has always looked the same, been very procedural and felt very wrong. Recently I started playing around with turning this chore into object oriented and started writing a module.

Well yet again it turns out there is already a module for that. The entity module. Not only did it do (almost) everything that I was trying to make my module do but it does far far more. In fact, it has totally revolutionized the way I write integration code.

Have you ever done something like this?


$node = node_load(1);
$node->field_reference[LANGUAGE_NONE][0]['nid'] = '463';
$node->field_text[LANGUAGE_NONE][0]['value'] = 'Some Value';
node_save($node);

If you have, don't ever do it again.

Many of you know that the Entity module is great for defining new entity types using the Entity API but it has another really great API within it. That is turning all the core entities into REAL objects, not just pretend objects. By this I mean that it adds a lot of methods to the objects as well as just properties.

The example above would be:


$node = new EntityDrupalWrapper('node', 1);
$node->field_reference[0]->set(463); // Note that this is a multi value field.
$node->field_text->set('Some Value'); // Note that this is a single value field.
$node->save();

Or if you want to get extra fancy, you can do the following:

 

class Node extends EntityDrupalWrapper {
public function __construct($data = NULL, $info = array()) {
parent::__construct('node', $data, $info);
}

}

$node = new Node(1);
$node->field_reference[0]->set(463); // Note that this is a multi value field.
$node->field_text->set('Some Value'); // Note that this is a single value field.
$node->save();

It makes me so excited to be able to interact with core entities in an entirely object oriented fashion. The Entity API module with the EntityDrupalWrapper will wrap most of the core drupal entities with plenty of useful helper methods.

It has revolutionized the way that I write integration code and hopefully it will yours as well. So next time you need to programmatically create nodes, check out the Entity API and the EntityDrupalWrapper.

Photo courtesy of http://www.flickr.com/photos/avlxyz/2667291630/