doctrine/mongodb-odm — pull request #436 by extr3m0 (2012-10-23 21:23:42+00:00)
Title: Added support for document initializers.

I felt there was a need to be able to initialize a document class before using it. For example: Sometimes it would be nice to be able to pass a "Mailer"-Instance to a document, so the Document could send mails itself. So this would represent some sort of dependency injection.

So to accomplish this it would first create a MailerAwareInterface and an initializer for my mailer instance:

```php
interface MailerAwareInterface {
public function setMailer(...);
}

class MailerInitializer implements DocumentInitializerInterface
{
public function initialize($instance) {
if(instance instanceof MailerAwareInstance) {
$instance->setMailer(...);
}
}
}
```

Then I would register this initializer. Either globally or for a specific document:

```php
$initializer = new MailerInstance();

// Only for instances of MyDocument
$dm->getClassMetadata('MyDocument')->registerInitializer($initializer);

// Globally for all documents
ClassMetadata::registerStaticInitializer($initializer);
```

The only downside would be that (when using initializers), documents created with the _new_ keyword will not be initialized. For the reason the ClassMetadata::newInstance method has to be used:

```php
// Not initialized
$doc = new MyDocument();

// Initialized
$doc = $dm->getClassMetadata('MyDocument')->newInstance();
```

I would be happy to read your opinions regarding this. :)