1

I'm writing a Command for a web app running on Symfony 2. A Command has a set structure and must be implemented as a Class with two set methods (configure & execute), plus any user-defined functions.

I want a few pre-defined variables that are accessible to all the functions, similar to how instance variable work in Java. How can I implement this in PHP?

1 Answer 1

2

This works using the DependencyInjection component. DI is what you're looking for!

When using symfony2 standard if you extend ContainerAwareCommand - symfony will inject the container automatically ...

use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;

class MyCommand extends ContainerAwareCommand

.. configure container-parameters in parameters.yml or config.yml

parameters:
    my_parameter: my_value

then access your container-parameters using

 $this->container->getParameter('my_parameter')

This way you can access those parameters from any "service" in your application as long as you have access to the container. You can even inject only the parameters which is advised as injecting the whole container is costly in terms of performance and makes testing harder.

Sign up to request clarification or add additional context in comments.

1 Comment

You're stealing my speciality tag, I'll never earn more reputation :P (+1)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.