Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dependencies Symfony2

I'm wondering if there is a proper way to check the dependencies.

For example I've got a NewsBundle. Now I'll have to check if there is a CommentBundle. If there is one, it should execute a few more Code.

Any suggestions?

like image 498
Flask Avatar asked May 31 '11 08:05

Flask


People also ask

What is dependency injection stack overflow?

Dependency injection is a pattern to allow your application to inject objects on the fly to classes that need them, without forcing those classes to be responsible for those objects. It allows your code to be more loosely coupled, and Entity Framework Core plugs in to this same system of services.

What is dependency injection in Symfony?

The Dependency Injection Container in Symfony2 allows components to be injected with their dependencies, and is often used as a Service Locator, which when combined with the DI-container pattern is considered to be an anti-pattern by many.

What is dependency injection framework?

Dependency injection in . NET is a built-in part of the framework, along with configuration, logging, and the options pattern. A dependency is an object that another object depends on. Examine the following MessageWriter class with a Write method that other classes depend on: C# Copy.

What is PHP dependency injection?

Dependency injection is a procedure where one object supplies the dependencies of another object. Dependency Injection is a software design approach that allows avoiding hard-coding dependencies and makes it possible to change the dependencies both at runtime and compile time.


2 Answers

In addition to markymark's answer, you can check if a specific service exists from your controller (or any other container-aware code) with the following snippet:

if ($this->container->has('foo_service.alias'))
{
    // service is loaded and usable
}

If you're not sure of the exact alias of a given service, or just for kicks and giggles, you can run the console command php app/console container:debug to see all services registered with the container.

like image 66
Derek Stobbe Avatar answered Sep 23 '22 23:09

Derek Stobbe


You could use class_exists on the main Bundle class that every bundle should have.

For example:

if (class_exists('Acme\CommentBundle\AcmeCommentBundle'))
{
    // Bundle exists and is loaded by AppKernel...
}
like image 29
markymark Avatar answered Sep 23 '22 23:09

markymark