6

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?

Vitalii Zurian
  • 17,858
  • 4
  • 64
  • 81
Flask
  • 4,966
  • 1
  • 20
  • 39

3 Answers3

28

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.

Besnik
  • 6,469
  • 1
  • 31
  • 33
Problematic
  • 17,567
  • 10
  • 73
  • 85
  • 4
    +1, your answer is clearer and correct to me as the above one. It's better to ask for services - and not for bundles. – Besnik Sep 18 '12 at 15:15
2

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...
}
markymark
  • 629
  • 4
  • 7
  • Dear @markymark, are you sure this will give you right result? Imagine situation: bundle is present on the filesystem, but wasn't registered in `AppKernel` (meaning neither bundle's routes neither services were loaded). Isn't it true that `class_exists('Some\Name\Space\Class') will try to autoload the class even despite it wasn't registed with the bundle? I wonder what do you think about it? HTH – Dimitry K Jun 26 '14 at 14:48
  • See https://stackoverflow.com/a/6271443/3027445 <- way better to check for service name instead of class name – podarok Aug 27 '18 at 14:38
0

The Kernel class contains a list of helper methods to check if a certain class is part of an active bundle or if a bundle is registered.

public BundleInterface[] getBundles()
    Gets the registered bundle instances.

public bool isClassInActiveBundle(string $class)
    Checks if a given class name belongs to an active bundle.
Sorin S.
  • 229
  • 1
  • 4