Skip to content

MissingDependencies

Mauro Gadaleta edited this page Mar 17, 2017 · 3 revisions

Ignoring Missing Dependencies

The behavior of ignoring missing dependencies is the same as the "null" behavior except when used within a method call, in which case the method call itself will be removed.

In the following example the container will inject a service using a method call if the service exists and remove the method call if it does not:

JS
container
	.register(id, NewsletterManager)
	.addArgument(new Reference('app.mailer', true))
YAML
services:
    app.newsletter_manager:
        class: './App/Newsletter/NewsletterManager'
        arguments: ['@?app.mailer']

In YAML or JSON, the special @? syntax tells the service container that the dependency is optional. Of course, the NewsletterManager must also be rewritten by adding a constructor method:

class NewsletterManager { 
    /*
     * @param {Mailer|null} mailer
     */
    constructor (mailer = null) {
        // ...
    }
}

Missing dependencies in your method calls

YAML
services:
    app.newsletter_manager:
        class: ./App/Newsletter/NewsletterManager
        calls:
            - [setMailer, ['@?app.mailer']]
JSON
{
	"services": {
		"app.newsletter_manager": {
			"class": "./App/Newsletter/NewsletterManager",
			"calls": [
				[
					"setMailer",
					[
						"@?app.mailer"
					]
				]
			]
		}
	}
}

And remember to add nullable mailer argument for example.

class NewsletterManager { 
    /*
     * @param {Mailer|null} mailer
     */
    setMailer(mailer = null) {
        // ...
    }
}