简体   繁体   中英

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

正如您在UapiCronCommand类中看到的那样,在$this->setName('OntroAlertBundle:uapi_cron')定义的“命令名称”是OntroAlertBundle:uapi_cron和NOT NickAlertBundle:uapi_cron (如错误消息中也显示)。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM