Symfony从类对象调用数据库

时间:2016-06-24 07:42:12

标签: php service doctrine-orm symfony

在我的symfony项目中,我尝试从类对象调用doctrine,其目的是将信息从对象的构造函数中放入数据库。

首先,我必须检查对象是否已经在数据库中,如果没有,我必须创建对象并将其添加到数据库中。 我是从类对象中做到的,因为很多信息是在一个循环中完成的,为了优化,我想从对象中完成它。

我的对象:

/** class object */
use MainBundle\Services\UserService;
use MainBundle\Entity\Item;
use MainBundle\Entity\User;
use Doctrine\ORM\Mapping as ORM;

class MyListObject{
    function MyListObject($data,$bddUser=null){
        if ($data->getSuccess()){
            foreach($data->getIdItem() as $id){
                $item = new IntItem($id,$data,$this);

                //database stuff
                $repository = $this->get('service.item');//get the table user from the database
                $existItem = $repository->getItemById($id);//get the item

                if ($existItem == null){
                    $itemBdd = new Item();
                    $itemBdd->setIditem($item->getId());
                    $itemBdd->setIdfull($item->getClassIdFull());
                    $itemBdd->setName($item->getName());


                }

我的服务:

services:
    service.item:
        class: MainBundle\Services\ItemService
        arguments: ['@doctrine.orm.default_entity_manager']

我的服务类:

<?

class ItemService
{

    private $entityManager;

    /*
     * @param EntityManager $entityManager
     */
    public function __construct(EntityManager $entityManager)
    {
        $this->entityManager = $entityManager;
    }

    /*
     * @param integer $blogId
     *
     * @return Blog
     */
    public function getItemById($itemId)

        return $this->entityManager
                    ->getRepository('MainBundle:Item')
                    ->find($itemId);
    }
}

然后我收到了这个错误:

Attempted to call an undefined method named "get" of class "MainBundle\Object\MyListObject".

之后我想从我的对象再次调用doctrine将项添加到数据库中。我真的不知道如何解决这个问题。我尝试的所有注射都没有工作,我也尝试扩展控制器,但我得到了另一个错误。

感谢。 请跟我的英语好,我尽力了!

我真的不知道哪里出错了

2 个答案:

答案 0 :(得分:0)

你的类应该扩展ContainerAware类

use \Symfony\Component\DependencyInjection\ContainerAware;

class MyListObject extends ContainerAware
{
    public function someMethod() 
    {
        $this->container->get('service.item');
        ...
    }
}

这样你就可以访问容器及其所有服务。

答案 1 :(得分:0)

whith symfony 3

use Symfony\Component\DependencyInjection\ContainerInterface
use Symfony\Component\DependencyInjection\ContainerAwareInterface;   

class ItemService implements ContainerAwareInterface
   {
       private $container;

       public function setcontainer(containerinterface $container = null)
       {
           $this->container = $container;
       }
   }