How to implement your business logic using the event system¶
The PIM uses the Symfony event system and fires events when something happens inside the system. For you, this means that you can create your own services that interact with those objects whenever certain action happens within the PIM.
Note
We highly recommend you to implement your business code on listeners, this way you will not depend on Akeneo or Pim interfaces, you will keep your code easily testable and you will not fear backward compatibility break anymore.
For more details about event listeners, you can read the Symfony documentation
Example¶
In the following example we will assume you want to be emailed about each product modification. In order to do that you can create an event listener that will send the email.
# /src/Acme/Bundle/AppBundle/EventListener/ProductModificationListener.php
<?php
namespace Acme\Bundle\AppBundle\EventListener;
use Symfony\Component\EventDispatcher\GenericEvent;
use Akeneo\Pim\Enrichment\Component\Product\Model\ProductInterface;
class ProductModificationListener
{
private $mailer;
public function __construct(\Swift_Mailer $mailer)
{
$this->mailer = $mailer;
}
public function onPostSave(GenericEvent $event)
{
$subject = $event->getSubject();
if (!$subject instanceof ProductInterface) {
// don't do anything if it's not a product
return;
}
$message = \Swift_Message::newInstance()
->setSubject('A product modification event have been fired')
->setFrom('[email protected]')
->setTo('[email protected]')
->setBody('...')
;
$this->mailer->send($message);
}
}
And there is the service definition:
# app/config/services.yml
services:
my.listener:
class: Acme\Bundle\AppBundle\EventListener\ProductModificationListener
arguments:
- '@swiftmailer.mailer'
tags:
- { name: kernel.event_listener, event: akeneo.storage.post_save, method: onPostSave }
Found a typo or a hole in the documentation and feel like contributing?
Join us on Github!