Nick Price
Nick Price

Reputation: 963

Symfony2 inject a service

I have a class which I have been using as a Service for other things. I am now setting up a Command class to run a cron job for me. This Command class needs to use a function which is contained within the class I have set up as a Service. So I thought the best way to get access to this function would be to inject it into my Command Class. So in my services I have

services:
    alert_bundle.api_service:
        class: Nick\AlertBundle\Service\UapiService
        arguments: [@service_container]

    alert_bundle.cron_service:
            class: Nick\AlertBundle\Command\UapiCronCommand
            arguments: [@alert_bundle.api_service]

UapiService is the Class that contains the function I need. UapiCronCommand is the Command Class where I am performing my Cron.

So then I have my Command Class

class UapiCronCommand extends ContainerAwareCommand
{
    protected $api_service;

    public function __construct(UapiService $api_service)
    {
        $this->api_service = $api_service;
    }

    protected function configure()
    {
        $this->setName('OntroAlertBundle:uapi_cron')
            ->setDescription('Cron Job for Alerts');
    }

    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $em = $this->getContainer()->get('doctrine.orm.entity_manager');
        $allAlerts = $em->getRepository("NickAlertBundle:Alert")->getAlertEntity();

        foreach($allAlerts as $alert) {
            if ($alert instanceof Alert) {
                $this->api_service->addFlightsAction($alert);
            }
        }

        $em->flush();
    }
} 

Now I was thinking that this would be injected with my UapiService class so I could now use its function, however when I test things out with

php app/console NickAlertBundle:uapi_cron

I get the error

[InvalidArgumentException]
There are no commands defined in the "NickAlertBundle" namespace.

I think this may be because I have added a __construct function to the Command class, not to sure though. And if this is the reason, how can I then get my service to this class?

Thanks

Upvotes: 1

Views: 71

Answers (1)

gp_sflover
gp_sflover

Reputation: 3500

As you can see in your UapiCronCommand class the "command name" defined in the $this->setName('OntroAlertBundle:uapi_cron') is OntroAlertBundle:uapi_cron and NOT NickAlertBundle:uapi_cron (like showed also in the error message).

Upvotes: 1

Related Questions