4

We use event integration (native and custom) in a lot of the plugins we build and I was wondering if anyone has come up with a simple way to raise those events at will, without having to follow a specific flow of execution.

For example, if you are listening for entries.saveEntry and don't want to manually save an entry in order for that event to be raised/triggered.

I think it would be nice to have a simple way of doing this and interested in seeing if anyone has found the need for such thing.

With enough patience, one could fake many events and call the service that raises them but I'm sure that there other developer way more clever than me that may have solved this already.

5

I believe events can be raised programmatically by calling them from services. You could mimic this behavior by creating an Event object ($event) and calling calling craft()->entries->onBeforeSaveEntry($event) yourself, for example. You would need to set up the event context and create a new Event object as the code does in the Entries Service below.

$event = new Event($this, array(
  'entry'      => $entry,
  'isNewEntry' => $isNewEntry
));

$this->onBeforeSaveEntry($event);

Check out the Entries Service around lines 165 to see how Craft uses events in that context.

For each event call, the code is calling $this->raiseEvent('eventName', $event);

I bet with some minimal setup, you could write a test controller that can call these events at will. Good question - I've been going down the manual path for all my testing too!

| improve this answer | |
  • Yeah, I've been doing something very similar to this for some native events. We actually have some custom events raised by our Sprout Commerce plugin like onCheckoutStart and onCheckoutEnd for which this technique gets too involved since you have to fake a lot of models (orders, payments, addresses, etc.) before we can call SproutCommerce()->onCheckoutStart(Event $event). – Selvin Ortiz Feb 3 '15 at 0:44
  • You know what, it just occurred to me that one could use something like Faker github.com/fzaninotto/Faker to aid in the process. – Selvin Ortiz Feb 3 '15 at 0:48
  • Totally! I was thinking of something like that, or writing some assertion testing with PHP Unit. I often use libraries like Faker to spoof AJAX result and database calls. – Aaron Berkowitz Feb 3 '15 at 0:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.