Instantly share code, notes, and snippets.

Embed
What would you like to do?
2012-12-04-doctrine2-comportamiento-softdelete-en-symfony2.markdown
{
"require": {
"gedmo/doctrine-extensions": "dev-master"
}
}
imports:
- { resource: doctrine_extensions.yml }
<?php
namespace Acme\DemoBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class MiControlador extends Controller
{
public function eliminarAction()
{
$em = $this->getDoctrine()->getEntityManager();
$entidad = $em->getRepository('DemoBundle:Entidad')->find(1); // suponemos que hay un Entidad id 1
// $entidad existe
$entidad->getDeletedAt(); // retorna NULL
$em->remove($entidad);
$em->flush();
$entidad = $em->getRepository('DemoBundle:Entidad')->find(1);
// $entidad ahora es NULL
// desactivando el filtro softdeleteable, podremos retornar las entidades eliminadas anteriormente
$em->getFilters()->disable('soft-deleteable');
$entidad = $em->getRepository('DemoBundle:Entidad')->find(1);
// $entidad vuelve a ser un objeto tipo Entidad
$entidad->getDeletedAt(); // retorna un \DateTime
}
}
?>
services:
extension.listener:
class: Acme\DemoBundle\Listener\DoctrineExtensionListener
calls:
- [ setContainer, [ @service_container ] ]
tags:
- { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
gedmo.listener.softdeleteable:
class: Gedmo\SoftDeleteable\SoftDeleteableListener
calls:
- [ setAnnotationReader, [ @annotation_reader ] ]
tags:
- { name: doctrine.event_subscriber, connection: default }
<?php
namespace Acme\DemoBundle\Listener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class DoctrineExtensionListener implements ContainerAwareInterface
{
/**
* @var ContainerInterface
*/
protected $container;
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
public function onKernelRequest(GetResponseEvent $event)
{
$doctrine = $this->container->get('doctrine');
$doctrine->getEntityManager()->getConfiguration()->addFilter(
'soft-deleteable',
'Gedmo\SoftDeleteable\Filter\SoftDeleteableFilter'
);
$em = $doctrine->getEntityManager();
$em->getFilters()->enable('soft-deleteable');
}
}
?>
<?php
namespace Acme\DemoBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
/**
* Entidad
*
* @ORM\Table()
* @ORM\Entity()
* @Gedmo\SoftDeleteable(fieldName="deletedAt")
*/
class Entidad
{
// ...
/**
* @ORM\Column(name="deletedAt", type="datetime", nullable=true)
*/
private $deletedAt;
// ...
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment