我有一个我一直在用作其他服务的类。我现在正在设置一个Command类来为我运行cron作业。这个Command类需要使用包含在我作为Service设置的类中的函数。所以我认为访问这个函数的最好方法是将它注入到我的Command类中。所以在我的服务中,我有Symfony2注入服务
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是包含我需要的函数的类。 UapiCronCommand是我执行我的Cron的命令类。
于是我有我的命令类
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();
}
}
现在我在想,这将与我的UapiService类被注入,所以我现在就可以使用它的功能,但是当我测试的东西出来与
PHP应用程序/控制台NickAlertBundle:uapi_cron
我得到的错误
[InvalidArgumentException]
在“NickAlertBundle”命名空间中没有定义任何命令。
我想这可能是因为我已经添加了一个__construct函数的Command类,但不是肯定。如果这就是原因,那我该如何为这个班级提供服务?
感谢
难道是因为你没有公共函数期望你可以调用的构造函数吗? – KhorneHoly 2015-03-02 12:21:35
命令文件中的命名空间在哪里? – 2015-03-02 12:31:48
命名空间位于我的文件顶部,未包含在上面的代码中 – 2015-03-02 12:49:41