gremo
gremo

Reputation: 48909

How to make a Symfony 2 bundle with an optional dependency?

Say that your bundle use some RESTful service and can work with two different PHP HTTP clients: guzzle/guzzle as well as with kriswallsmith/Buzz. Because it uses adapters and interfaces.

How can I defined this dependency as optional? Would you do something like this, for example in compiler pass?

if(!is_file('/path/to/guzzle') && !is_file('/path/to/buzz')) {
    throw new \RuntimeException('You need to install guzzle or Buzz browser.');
}

Is this the right way to define an optional dependency for a bundle?

Upvotes: 1

Views: 568

Answers (1)

Sgoettschkes
Sgoettschkes

Reputation: 13189

First, you would not do it like the above, mainly because checking if files are present at some path won't work. What if the user installs them somewhere else (for whatever reason) and manages to get namespacing right?

My first question would be why you want the user to choose. Is there any difference? Is the user even capable of deciding which client to use. For example when I use assetics, I of course have to decide which filters I want to use, because they have a big impact on what happens (e.g. if I have scss files, a less filter is useless).

There are other problems like the one that the user has to manage dependencies himself. Sometimes this is worth it, sometimes it's not.

Now, if you decided you want the user to choose, I would go for a configuration option where the user passes either the string guzzle or the string buzz. Maybe there is a default value.

In your bundle, you try to create your object depending on this configuration. You could surround it with a try catch block to catch missing dependencies or see if a certain class is avaiable. As said, you would not test for the existence of a certain file, but of a certain class with the php function class_exists. Your test should be on the class or classes you actually want to use.

Upvotes: 2

Related Questions