Symfony3

时间:2017-06-20 09:48:48

标签: php symfony dependency-injection

我有一个我想用作服务的课程:

<?php

namespace AppBundle\Entity;

use Doctrine\ORM\EntityManager;
use Symfony\Component\Config\Definition\Exception\Exception;

class Functions
{


private $em;

public function setEntityManager(EntityManager $em)
{
    $this->em = $em;
}

/**
 * Init the add Event to Eventlog function
 *
 * @param string $text Text to save
 * @param User $user
 *
 * @return boolean
 */
public function addEvent($text, User $user)
{

    $event = new Event();
    $event->setUser($user);
    $event->setText($text);
    $event->setEventTimestamp(new \DateTime());
    $this->em->persist($event);

    try{
        $this->em->flush();
    }catch (Exception $e){
        return false;
    }

    return true;

}

}

我通过services.yml注入服务,如下所示:

services:
    app.ccrm:
        class: AppBundle\Entity\Functions
        calls:
            - [setEntityManager, ["@doctrine.orm.default_entity_manager"]]

并在我的控制器中使用它进行调用:

$this->get('app.ccrm')->addEvent('Event IDXXX',$this->getUser());

不,它给了我

  

您已请求不存在的服务&#34; app.ccrm&#34;。

我做的事情:

  • php bin/console cache:clear
  • php bin/console cache:clear --env=prod
  • dev
  • 中手动删除prodvar/cache
  • 使用其他浏览器
  • 阅读thisthis
  • 运行了php bin/console debug:container app.ccrm,结果是:

    Service ID app.ccrm Class AppBundle\Entity\Functions Tags - Calls setEntityManager Public no Synthetic no Lazy no Shared yes Abstract no Autowired yes Autoconfigured yes

现在我完全没有想法!任何提示?

1 个答案:

答案 0 :(得分:1)

再次检查php bin/console debug:container app.ccrm的输出,然后查看public: no行。您需要将服务设置为公开。

services:
    app.ccrm:
        class: AppBundle\Entity\Functions
        public: true
        calls:
            - [setEntityManager, ["@doctrine.orm.default_entity_manager"]]

此外,请检查documentation about default service visibility