Symfony调用类对象的呼叫数据库



在我的symfony项目上,我尝试从类对象调用学说,这个想法是将信息从对象的构造函数中放入数据库中。

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

我的对象:

/** class object */
use MainBundleServicesUserService;
use MainBundleEntityItem;
use MainBundleEntityUser;
use DoctrineORMMapping 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: MainBundleServicesItemService
        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 "MainBundleObjectMyListObject".

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

谢谢。请我的英语友好,我尽力!

我真的不知道我在哪里出错

您的课程应扩展clasteraware

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

喜欢,因此您可以访问容器及其所有服务。

symfony 3

use SymfonyComponentDependencyInjectionContainerInterface
use SymfonyComponentDependencyInjectionContainerAwareInterface;   
class ItemService implements ContainerAwareInterface
   {
       private $container;
       public function setcontainer(containerinterface $container = null)
       {
           $this->container = $container;
       }
   }

最新更新