RulesBundle
This bundle creates the facility to add a basic rules engine. It's inspired by this article: http://jwage.com/post/76799775984/using-the-symfony-expression-language-for-a-reward, (*1)
The bundle creates a Rule entity which is comprised of three elements:, (*2)
1. Event - the dispatched event that causes this rule to be invoked (e.g. 'user:registered')
2. Conditions - a json array of expressions. (e.g. '["data.age > 67", "data.weight > 200"]') See [http://symfony.com/doc/current/components/expression_language.html](http://symfony.com/doc/current/components/expression_language.html) for more on the ExpressionLanguage component.
3. Actions - a json array of events to be dispatched. (e.g. '["user:mark-as-retired", "user:send-email|Retirement"]'. Note that it is possible to send a single parameter by adding a '|' after the name of the action/event to be dispatched)
Installation
First, install it with composer:, (*3)
composer require vouchedfor/rules-bundle:dev-master
Then, add the following in your AppKernel bundles (note that 'new DataDog\AuditBundle\DataDogAuditBundle(),' may have been added previously)., (*4)
// app/AppKernel.php
public function registerBundles()
{
$bundles = array(
...
new VouchedFor\AuditUiBundle\VouchedForRulesBundle(),
...
);
...
}
Create the 'rule' database table used by the bundle:, (*5)
Using Doctrine Migrations Bundle:, (*6)
php app/console doctrine:migrations:diff
php app/console doctrine:migrations:migrate
Using Doctrine Schema:, (*7)
php app/console doctrine:schema:update --force
Usage
Create a class that extends VouchedFor\RulesBundle\Event\RuleEvent., (*8)
Add the events you want to listen to as tags for a RuleListener service (in this example, 'user:mark-as-retired' and 'user:send-email'):, (*9)
// app/config/services.yml
app.rule.listener:
class: VouchedFor\RulesBundle\EventListener\RuleListener
arguments:
- "@doctrine.orm.entity_manager"
- "@event_dispatcher"
tags:
- { name: kernel.event_listener, event: user:registered, method: handleEvent }
- { name: kernel.event_listener, event: user:updated, method: handleEvent }
Add a listener/subscriber to listen to the dispatched actions when a rule passes. For example:, (*10)
<?php
namespace AppBundle\EventListener;
...
class UserSubscriber implements EventSubscriberInterface
{
public static function getSubscribedEvents()
{
return [
'user:mark-as-retired' => 'userMarkAsRetired',
'user:send-email' => 'userSendEmail',
];
}
public function userMarkAsRequired(UserEvent $event)
{
$entity = $event->getEntity());
$entity->setStatus('retired');
...
}
public function userSendEmail(UserEvent $event)
{
$entity = $event->getEntity());
$parameter = $event->getActionParameter());
$this->sendMail($entity, $parameter); // Send email to $entity with template $parameter
...
}
License
The Rules Bundle is free to use and is licensed under the MIT license, (*11)