Skip to content

Instantly share code, notes, and snippets.

@nietzscheson
Last active August 29, 2015 14:24
Show Gist options
  • Save nietzscheson/e4be084140f407e8e189 to your computer and use it in GitHub Desktop.
Save nietzscheson/e4be084140f407e8e189 to your computer and use it in GitHub Desktop.
[#Symfony] BaseModel Event - EventListener
1 - Inicio
2 - Se crea una class final
3 - Se crea una class Event
4 - Se crea una class EventListener
5 - Se registra el Listener como servicio
6 - Se lanza el event
<?php
namespace AppBundle;
final class AppEvents
{
/**
* Se lanzará antes de crearse el usuario en el sistema
* @var string
*/
const SENDMAIL_NEW_USER = 'usuarios.pre_save';
}
<?php
namespace AppBundle\Event;
use Symfony\Component\EventDispatcher\Event;
use ACL\ACLBundle\Entity\Usuarios;
class UsuariosEvent extends Event
{
protected $usuario;
protected $container;
function __construct(Usuarios $usuario, $container)
{
$this->usuario = $usuario;
$this->container = $container;
}
public function getUsuario()
{
return $this->usuario;
}
public function getContainer()
{
return $this->container;
}
}
<?php
namespace AppBundle\EventListener;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use AppBundle\AppEvents;
use AppBundle\Event\UsuariosEvent;
class UsuariosListener implements EventSubscriberInterface
{
public function onPreUsuarioSave(UsuariosEvent $event)
{
$user = $event->getUsuario();
echo $event->getContainer();
exit();
}
public static function getSubscribedEvents()
{
return array(AppEvents::SENDMAIL_NEW_USER => 'onPreUsuarioSave');
}
}
services:
usuarios.event_listener:
class: AppBundle\EventListener\UsuariosListener
tags:
#- { name: usuarios.event_listener, event: usuarios.pre_save, method: 'onPreUsuarioSave'}
- { name: kernel.event_subscriber }
public function save($model)
{
$event = new UsuariosEvent($model, $this->container);
$this->dispatcher->dispatch(AppEvents::SENDMAIL_NEW_USER, $event);
//exit('Se persiste');
// $this->em->persist($model);
// $this->em->flush();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment