Drupal Entities – PHP Class per bundle

If you would like a bit more polymorphism in your drupal entities, this might cheer you up :-D

I was looking for a way to have a class hierarchy that matched the bundle “hierarchy” of entities in drupal. Yes, they are all “subclasses” of ONE parent, but it is still useful to be able to have a class per bundle.

The entity bundle plugin does a good job of providing a plugin framework to instantiate classes per bundle type. There is also an example of how to use this. However, this was a bit of overkill for me. I did however borrow the idea (and some code) to implement it in a simpler fashion.

Implement a custom controller and override the create and the query methods

 

class MyEntityAPIController extends EntityAPIController {
  /**
   * Overrides EntityAPIController::query().
   */
  public function query($ids, $conditions, $revision_id = FALSE) {
    $query = $this->buildQuery($ids, $conditions, $revision_id);
    $result = $query->execute();
    $result->setFetchMode(PDO::FETCH_ASSOC);

    // Build the resulting objects ourselves, since the standard PDO ways of
    // doing that are completely useless.
    $objects = array();
    foreach ($result as $row) {
      $row['is_new'] = FALSE;
      $objects[] = $this->create($row);
    }
    return $objects;
  }

  /**
   * Overrides EntityAPIController::create().
   */
  public function create(array $values = array()) {
    if (!isset($values[$this->entityInfo['entity keys']['bundle']])) {
      throw new Exception(t('No bundle provided to MyEntityAPIController::create().'));
    }

    $bundle = $values[$this->entityInfo['entity keys']['bundle']];
      // Add is_new property if it is not set.
    $values += array(
      'is_new' => TRUE,
    );

    $default_class = isset($this->entityInfo['entity class']) ? $this->entityInfo['entity class'] : NULL;
    $class = isset($this->entityInfo['bundles'][$bundle]['entity class']) ? $this->entityInfo['bundles'][$bundle]['entity class'] : $default_class;
    if (!class_exists($class)) {
      $class = "Entity";
    }

    return new $class($values, $this->entityType);
  }

}

I can now define a PHP class for each bundle as follows in hook_entity_info

 

  $entity['myentity'] = array(
    'label' => t('myentity'),
    'module' => 'mymodule',
    'entity class' => 'MyEntity',  // Default entity class if not defined in bundle
    'controller class' => 'MyEntityAPIController',
    'base table' => 'myentity',
    'entity keys' => array(
      'id' => 'id',
      'label' => 'name',
      'bundle' => 'bundle',
    ),
    'bundles' => array(
      'bundle1' => array(
        'label' => 'Bundle 1',
        'entity class' => 'Bundle1Entity',
      ),
      'bundle2' => array(
        'label' => 'Bundle 2',
        'entity class' => 'Bundle2Entity',
      ),
    ),

Don’t forget to clear the cache and you should be able to get bundle specific classes instantiated. It will fall back to the ‘entity class’ defined for the entity if the bundle ‘entity class’ is not defined or cannot be found.

Destructible World in Battlefield 4

Found this video of an entire skyscraper being destroyed in Battlefield 4. My! things have moved on a fair bit in the world of computer games. Here I was enjoying the lush scenery of Skyrim and all of a sudden, an entire world that can be destroyed?

It is a shame that with all of this power, some of the features I have really enjoyed in games like witty banter with your companions (The Baldurs gate series being a very good example) are still so sorely missed. :-(

Pulling At My Heart Strings

This the story of a Wood Elf, he woke up in a cart, his memories fuzzy and faded, little knowledge of who he was and what he was doing. He wanders the frozen wastes of Skyrim doing as he feels. Without a clue as to who he was, he discovers who he is. Finding himself at Riften, he joined the thieves guild. He also got Mjoll the Lioness to accompany him on his journeys after finding Grimsever for her. All seemingly through chance.

I found myself in Ivarstead one morning on my way to Whiterun. The walk was largely dull except for me trying to play hunter. Trying to shoot an arrow into a moving deer is more difficult than I imagined. Needless to say, little was achieved more than losing a few arrows.

Walking past the alchemists hut, I snuck in to see if the herbs and grown, ready for another pruning ;-) but it was not. It re-ignited my curiosity about the previous owner of the hut but I got distracted by a deer. After losing another few arrows, I decided to focus on picking some mountain flowers and other alchemical ingredients.

Things were dull until I got to Riverwood. I suddenly remembered that I was supposed to deliver a note from Faendal (the scoundrel) to some girl at the bar. I didn’t like how he wanted me to lie about some guy and as luck would have it, the guy was at the bar too singing something.

He probably deserves to know what was happening so I told him the truth. Now he wants me to lie and say that Faendal wrote a stupid letter. Now this was not my intention. Now I am in a situation where it is obvious that this town has not one but two lying idiots. I mean – what’s wrong with these people – can’t they sort this out themselves? I mean even a old fashioned duel would still better than this lying about each other.

I headed over to the girl resolving to tell her that both the men in her life are idiots. I started to tell her that Sven (that was the other guys name now that I remember) wanted me to lie about Faendal and before I would explain that Faendal was the same, she shouted some abuse about Sven and told me that I should probably thank Faendal. Oh wait, the women are crazy too. To each their own I thought and wandered across to Faendals house.

It was a little late in the night and he was fast asleep. I couldn’t be bothered to wait till morning, so i broke into his house. Considering that he’s a lying bastard and he was soundly sleeping, I robbed him of all valuables – which honestly was really not that much. I then woke him up and told him the good news – he seemed happy. The things we do for love… I thought.. For a moment, I wondered if I had done such silly things in my life… but only for a moment and jumped off the balcony and ran across to Whiterun.

Running past the honningbrew meadery, I remember that I had kicked the previous owner out and put somebody else in place for Maven Black Briar (one of the things I did for the Thieves Guild). I thought to drop him a visit and see how he was getting on.

He was happy to see me and told me how fortunate he was to go for being somebodies lackey to a very wealthy man overnight. He did not even offer me a free mead. I went upstairs and robbed him of all his valuables and I was just about to head out when I saw that the bar was full of bottles of Black Briar Mead. Not only are they delicious, they are also worth a fair bit of money, so I snuck around and shoved them all into my pockets.

I also tried to pickpocket the now wealthy Mallus but he had nothing on him that I could find…

It was pretty late when I got into town and stumbling into the first tavern, it turns out they don’t have rooms. I then made it across to the town square which had another tavern. This one did have rent out rooms – thank god.

After ditching all of my extra stuff that I could at the merchants, I headed back out in the direction of Markarth. I did various things on the way including killing a bandit leader is some cave and speaking to Kematu which was enlightening and further eroding faith in people.

Finally, I reached Rorikstead, it seemed like a nice quiet town. I even met Rorik who seemed like such a nice man to have bought a bunch of land for people to live off.

It was a nice enough place that I decided to spend a day hanging around and taking in the scenery and the loveliness of it all. There were even kids running around playing.

As one of them ran past, I stopped her and talked to her but it didn’t quite go the way I hoped. “Most days, I do all I can to stay away from my sister and my father. The beating’s the same from either one.” she told me. Sure enough her sister was right behind her and I realised that they were not actually playing…

This made me very curious and instead of hanging about soaking in the atmosphere, I followed people around trying to confirm how true this was and it saddened me a great deal to find out that it was indeed true. As it turns out Lemkil, their Father had lost his wife to the birth of the twins. A sad thing no excuse for what his daughters are going through.

I was overcome with a desire to put their father out of his misery. I did not even have the patience to wait until it was dark. He was working on a farm, I went up on a hill and hid behind a rock. I took aim and the first arrow hit the rock and rolled down the hill. I couldn’t help but giggle. I then readied another arrow, aimed a little higher and let it loose. Time slowed as the arrow left and found its mark.

Erik screamed bloody murder – pointing out it was in cold blood but I was well hidden and safe. Erik had told me how much he wanted to travel and be an adventurer. Hey, two birds with one stone eh? ;-)

Getting Started: Emacs & C++ (w/ cmake) (On the fly syntax highlighting)

I am a recent convert to emacs. My vast majority of development is in Java EE and I have not found an easy way to get the functionality in eclipse into emacs. So I still use eclipse for this.

However, I like to tinker with C++ and I wanted to get some of the CDT functionality into emacs. In truth, I have used very little CDT so my expectations from emacs will be set differently. Considering that emacs has been used for C/C++ development for decades, I am hopeful that it will be more feature-rich than eclipse or any of the other IDE’s like Anjuta, Code::Blocks etc (both I have tried to use).

First things first. In the world of Java, I am a massive fan of maven which makes build management so easy and simple. Having used it now for years, it is easy to forget how much of a learning curve it had to get started.

Autotools are a massive pain to use and has a very steep learning curve. I have used it in the past to set up build environments and it works fine. pkg-config is pretty awesome and in a lot of ways, maven does pale in comparison. i.e. instead of having maven pull in dependencies, you just use your systems package manager like apt-get or yum and it installs the libraries for you.

Read more »

WARN – Missing artifact descriptor for XXX

Working on an Arquillian test deployment which had some library changes recently, I ran into the following error.

WARN - Missing artifact descriptor for org.javassist:javassist:jar:3.16.1-GA

The particular library was in the pom.xml dependency hierarchy but it was resolving to an earlier  version. Maven was switched to offline mode during the tests and I had never needed this version of the library before. This meant  that the local version of my maven repository did not have jar and maven emits it slightly unhelpful error. It would be better if it told us that it could not find the artifact and since its in offline mode, can’t go and retrieve it.

Read more »

WordPress Themes