Giter VIP home page Giter VIP logo

mongodb-odm-softdelete's Introduction

Doctrine MongoDB ODM SoftDelete Functionality

This library gives you some additional classes and API for managing the soft deleted state of Doctrine MongoDB ODM documents. To get started you just need to configure a few objects and get a SoftDeleteManager instance:

Setup

use Doctrine\ODM\MongoDB\SoftDelete\Configuration;
use Doctrine\ODM\MongoDB\SoftDelete\UnitOfWork;
use Doctrine\ODM\MongoDB\SoftDelete\SoftDeleteManager;
use Doctrine\Common\EventManager;

// $dm is a DocumentManager instance we should already have

$config = new Configuration();
$evm = new EventManager();
$sdm = new SoftDeleteManager($dm, $config, $evm);

SoftDelete Documents

In order for your documents to work with the SoftDelete functionality they must implement the SoftDeleteable interface:

interface SoftDeleteable
{
    function getDeletedAt();
}

An implementation might look like this:

use Doctrine\ODM\MongoDB\SoftDelete\SoftDeleteable;

/** @mongodb:Document */
class User implements SoftDeleteable
{
    // ...

    /** @mongodb:Date */
    private $deletedAt;

    public function getDeletedAt()
    {
        return $this->deletedAt;
    }

    // ...
}

Managing Soft Delete State

Once you have the $sdm you can start managing the soft delete state of your documents:

$jwage = $dm->getRepository('User')->findOneByUsername('jwage');
$fabpot = $dm->getRepository('User')->findOneByUsername('fabpot');
$sdm->delete($jwage);
$sdm->delete($fabpot);
$sdm->flush();

The above would issue a simple query setting the deleted date:

db.users.update({ _id : { $in : userIds }}, { $set : { deletedAt : new Date() } })

Now if we were to restore the documents:

$sdm->restore($jwage);
$sdm->flush();

It would unset the deletedAt date:

db.users.update({ _id : { $in : userIds }}, { $unset : { deletedAt : true } })

Events

We trigger some additional event lifecycle events when documents are soft deleted or restored:

  • Events::preSoftDelete
  • Events::postSoftDelete
  • Events::preRestore
  • Events::postRestore

Using the events is easy, just define a class like the following:

class TestEventSubscriber implements \Doctrine\Common\EventSubscriber
{
    public function preSoftDelete(LifecycleEventArgs $args)
    {
        $document = $args->getDocument();
        $sdm = $args->getSoftDeleteManager();
    }

    public function getSubscribedEvents()
    {
        return array(Events::preSoftDelete);
    }
}

Now we just need to add the event subscriber to the EventManager:

$eventSubscriber = new TestEventSubscriber();
$evm->addEventSubscriber($eventSubscriber);

When we soft delete something the preSoftDelete() method will be invoked before any queries are sent to the database:

$sdm->delete($fabpot);
$sdm->flush();

Cascading Soft Deletes

You can easily implement cascading soft deletes by using events in a certain way. Imagine you have a User and Post document and you want to soft delete a users posts when you delete him.

You just need to setup an event listener like the following:

use Doctrine\Common\EventSubscriber;

class CascadingSoftDeleteListener implements EventSubscriber
{
    public function preSoftDelete(LifecycleEventArgs $args)
    {
        $sdm = $args->getSoftDeleteManager();
        $document = $args->getDocument();
        if ($document instanceof User) {
            $sdm->deleteBy('Post', array('user.id' => $document->getId()));
        }
    }

    public function preRestore(LifecycleEventArgs $args)
    {
        $sdm = $args->getSoftDeleteManager();
        $document = $args->getDocument();
        if ($document instanceof User) {
            $sdm->restoreBy('Post', array('user.id' => $document->getId()));
        }
    }

    public function getSubscribedEvents()
    {
        return array(
            Events::preSoftDelete,
            Events::preRestore
        );
    }
}

Now when you delete an instance of User it will also delete any Post documents where they reference the User being deleted. If you restore the User, his Post documents will also be restored.

mongodb-odm-softdelete's People

Contributors

jjbohn avatar jmikola avatar julesbou avatar jwage avatar kriswallsmith avatar leek avatar matwright avatar tacker avatar websirnik avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

mongodb-odm-softdelete's Issues

Is method "getDeletedAt()" necessary?

Is it really necessary to force this method in the SoftDeletable interface, while it's not used anywhere but in the tests? Everything is based on the configured field.

Version tags for repository

Please add version tags for this repository. Just to make it easier to manage dependencies properly

Please... :)

Did you plan to create a softDelete for the ORM ?

Hi,

I think loads of people would like to know the anwser too, that's why Im asking it here.

Did you plan to create a softDelete extension for the Doctrine2 ORM ?

Many thanks for the work you do.

SoftDelete aware createQueryBuilder?

Hi.

I've been looking for a solution I could use to query soft deleted objects without adding this code:

$results = $this->documentManager->createQueryBuilder('classname')
                    ->field('deletedAt')->equals(NULL) //This is an unnecessary row, IMO :)
                    ->getQuery()
                    ->execute();

I think all soft deleted objects should be excluded from queries by default and requiring programmers to add that line introduces hundreds of chances to make a mistake in any application.

Is there a centralized way of doing this already? Or should there be? What do you guys think?

ps. I know this is not a discussion forum, but as this is kind of a feature request, I put this here.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.