我有一个类,我一直把它用作其他事情的服务。我现在正在设置一个Command类来为我运行cron作业。这个Command类需要使用一个函数,该函数包含在我设置为服务的类中。所以我认为访问这个函数的最好方法是将它注入到我的命令类中。所以在我的服务中,我有
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"命名空间中没有定义任何命令。
我想这可能是因为我在Command类中添加了__construct函数,但不能确定。如果是这样的话,我该如何为这个班级提供服务?
感谢
正如您在UapiCronCommand
类中看到的,$this->setName('OntroAlertBundle:uapi_cron')
中定义的"命令名"是OntroAlertBundle:uapi_cron和NOT NickAlertBundle:uapi_cron
(如错误消息中所示)。