oliverbusk's avatar

Handling Multiple Events

I have a web application where users can uploads image documents.

Now, after a new document is uploaded into the system, it should:

  1. Be optimized. (OCR)
  2. Perform various rules on the OCR output.

For this, I rely on Events in Laravel.

I have registered below events for my model Document.php:

protected $dispatchesEvents = [
    'created' => DocumentCreated::class, //Once document has been uploaded.
    'updated' => DocumentUpdated::class, //Once OCR has been performed.
];

Now, for each event, I have also defined listeners.

This is my EventServiceProvider.php:

DocumentCreated::class => [
    PerformOCROnDocument::class,
],
DocumentUpdated::class => [
    ParseDocument::class,
],

So when a new document is created, it will:

  1. Perform OCR on the document. This class PerformOCROnDocument will do various tasks. Most importantly, PerformOCROnDocument will ultimately call:
$document->save();

Since I have defined updated on my Document model, once the save() method is called, it will trigger the next event: DocumentUpdated.

  1. Now, ParseDocument will run, and do some various tasks as well.

Important:

The ParseDocument cannot run before PerformOCROnDocument has finished.

Now my question is: is this the correct way of doing this and handling events? Ultimately, my events will implement ShouldQueue so everything will be added to a queue and handled async.

0 likes
4 replies
ftiersch's avatar

I think technically it would run well. But I'd say "updated" is not the right event for your ParseDocument since an update event can come from lots of places (maybe not now but when your application grows it's easy to forget that).

I'd probably create another Event OCRFinished that get's fired in the PerformOCROnDocument listener to make sure OCR has really finished.

oliverbusk's avatar

So inside PerformOCROnDocument, would you place the event like this:

$document->save();
event(new OCRFinished($document));

And then in EventSerivceProvider.php, do like this:

OCRFinished::class => [
    ParseDocument::class,
],

?

ftiersch's avatar
ftiersch
Best Answer
Level 28

Exactly. That makes it more stable in my opinion because the parsing happens only after an OCR process has finished.

Otherwise you would parse the document after every update - also later after parsing it has finished already.

Please or to participate in this conversation.