简体   繁体   English

Symfony2注入服务

[英]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. 我现在正在设置Command类来为我运行cron作业。 This Command class needs to use a function which is contained within the class I have set up as a Service. 这个Command类需要使用一个包含在我已经设置为Service的类中的函数。 So I thought the best way to get access to this function would be to inject it into my Command Class. 因此,我认为最好的访问此功能的方法是将其注入到Command类中。 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. UapiService是包含我需要的功能的类。 UapiCronCommand is the Command Class where I am performing my Cron. UapiCronCommand是我执行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 现在我正在考虑将其注入我的UapiService类,以便现在可以使用其功能,但是当我使用

php app/console NickAlertBundle:uapi_cron PHP应用程序/控制台NickAlertBundle:uapi_cron

I get the error 我得到错误

[InvalidArgumentException] [InvalidArgumentException]
There are no commands defined in the "NickAlertBundle" namespace. 在“ NickAlertBundle”命名空间中没有定义任何命令。

I think this may be because I have added a __construct function to the Command class, not to sure though. 我认为这可能是因为我不确定要在Command类中添加__construct函数。 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 (如错误消息中也显示)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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