如何在服务中使用Entty Manager?

时间:2015-07-24 17:40:54

标签: php symfony orm doctrine-orm doctrine

我从Symfony 2开始,我遇到了问题。 使用ORM返回我的查询返回的对象不是我希望的方式。 我在服务中正确使用ORM?

我有这项服务

class RequestListener{   
     protected $request;
     protected $em;

     public function __construct(RequestStack $request, EntityManager $em){
        $this->request  = $request->getCurrentRequest();
        $this->em       = $em;
    }


    public function onRequest()
    {

        if ( !$this->request->query->has('apikey') && !$this->request->headers->has('X-API-App-Token') ) {
             throw new BadCredentialsException('No API key found');
        }

        $test = $this->em->getRepository("AutenticacaoBundle\Entity\Sistema")->findOneBy(array('id' => '1'));

        echo "<pre>"; print_r($test);

        die();
    }  
}

和我的文件service.yml看起来像这样:

services:
    kernel.listener.request_listner:
        class: AutenticacaoBundle\EventListener\RequestListener
        arguments: ['@request_stack', '@doctrine.orm.entity_manager']
        public: true
        scope: request
        tags:
            - { name: kernel.event_listener, event: kernel.request, method: onRequest }

我的实体:

class Sistema{
/**
 * @var string
 *
 * @ORM\Column(name="nome", type="string", length=45, nullable=false)
 */
private $nome;

/**
 * @var string
 *
 * @ORM\Column(name="autenticacao", type="string", length=10, nullable=false)
 */
private $autenticacao;

/**
 * @var integer
 *
 * @ORM\Column(name="id", type="integer")
 * @ORM\Id
 * @ORM\GeneratedValue(strategy="IDENTITY")
 */
private $id;

/**
 * @var \Doctrine\Common\Collections\Collection
 *
 * @ORM\ManyToMany(targetEntity="Procob\AutenticacaoBundle\Entity\Usuario", mappedBy="sistema")
 */
private $idUsuario;

/**
 * Constructor
 */
public function __construct()
{
    $this->idUsuario = new \Doctrine\Common\Collections\ArrayCollection();
}


/**
 * Set nome
 *
 * @param string $nome
 * @return Sistema
 */
public function setNome($nome)
{
    $this->nome = $nome;

    return $this;
}

/**
 * Get nome
 *
 * @return string 
 */
public function getNome()
{
    return $this->nome;
}

/**
 * Set autenticacao
 *
 * @param string $autenticacao
 * @return Sistema
 */
public function setAutenticacao($autenticacao)
{
    $this->autenticacao = $autenticacao;

    return $this;
}

/**
 * Get autenticacao
 *
 * @return string 
 */
public function getAutenticacao()
{
    return $this->autenticacao;
}

/**
 * Get id
 *
 * @return integer 
 */
public function getId()
{
    return $this->id;
}

/**
 * Add idUsuario
 *
 * @param \Procob\AutenticacaoBundle\Entity\Usuario $idUsuario
 * @return Sistema
 */
public function addIdUsuario(\Procob\AutenticacaoBundle\Entity\Usuario $idUsuario)
{
    $this->idUsuario[] = $idUsuario;

    return $this;
}

/**
 * Remove idUsuario
 *
 * @param \Procob\AutenticacaoBundle\Entity\Usuario $idUsuario
 */
public function removeIdUsuario(\Procob\AutenticacaoBundle\Entity\Usuario $idUsuario)
{
    $this->idUsuario->removeElement($idUsuario);
}

/**
 * Get idUsuario
 *
 * @return \Doctrine\Common\Collections\Collection 
 */
public function getIdUsuario()
{
    return $this->idUsuario;
}
}

我希望收到在对象中格式化的查询结果,但是我的字段比我需要的多,并且返回是一个巨大的对象

返回对象:

AutenticacaoBundle\Entity\Sistema Object(
[nome:AutenticacaoBundle\Entity\Sistema:private] => API ANTI FRAUDE
[autenticacao:AutenticacaoBundle\Entity\Sistema:private] => TOKEN
[id:AutenticacaoBundle\Entity\Sistema:private] => 1
[idUsuario:AutenticacaoBundle\Entity\Sistema:private] => Doctrine\ORM\PersistentCollection Object
    (
        [snapshot:Doctrine\ORM\PersistentCollection:private] => Array
            (
            )

        [owner:Doctrine\ORM\PersistentCollection:private] => AutenticacaoBundle\Entity\Sistema Object
        *RECURSION*
        [association:Doctrine\ORM\PersistentCollection:private] => Array
            (
                [fieldName] => idUsuario
                [targetEntity] => AutenticacaoBundle\Entity\Usuario
                [mappedBy] => sistema
                [type] => 8
                [inversedBy] => 
                [isOwningSide] => 
                [sourceEntity] => AutenticacaoBundle\Entity\Sistema
                [fetch] => 2
                [cascade] => Array
                    (
                    )

                [isCascadeRemove] => 
                [isCascadePersist] => 
                [isCascadeRefresh] => 
                [isCascadeMerge] => 
                [isCascadeDetach] => 
                [orphanRemoval] => 
            )

        [em:Doctrine\ORM\PersistentCollection:private] => Doctrine\ORM\EntityManager Object
            (
                [config:Doctrine\ORM\EntityManager:private] => Doctrine\ORM\Configuration Object
                    (
                        [_attributes:protected] => Array
                            (
                                [entityNamespaces] => Array
                                    (
                                        [AutenticacaoBundle] => AutenticacaoBundle\Entity
                                    )

                                [metadataCacheImpl] => Doctrine\Common\Cache\ArrayCache Object
                                    (
                                        [data:Doctrine\Common\Cache\ArrayCache:private] => Array
                                            (
                                                [DoctrineNamespaceCacheKey[sf2orm_default_489a22580630c4a54db185d7439d487df1380fa671bd29dc59b5de5271068a56]] => 1
                                                [sf2orm_default_489a22580630c4a54db185d7439d487df1380fa671bd29dc59b5de5271068a56[AutenticacaoBundle\Entity\Sistema$CLASSMETADATA][1]] => Doctrine\ORM\Mapping\ClassMetadata Object
                                                    (
                                                        [name] => AutenticacaoBundle\Entity\Sistema
                                                        [namespace] => AutenticacaoBundle\Entity
                                                        [rootEntityName] => AutenticacaoBundle\Entity\Sistema
                                                        [customGeneratorDefinition] => 
                                                        [customRepositoryClassName] => 
                                                        [isMappedSuperclass] => 
                                                        [parentClasses] => Array
                                                            (
                                                            )

                                                        [subClasses] => Array
                                                            (
                                                            )

                                                        [namedQueries] => Array
                                                            (
                                                            )

                                                        [namedNativeQueries] => Array
                                                            (
                                                            )

                                                        [sqlResultSetMappings] => Array
                                                            (
                                                            )

1 个答案:

答案 0 :(得分:1)

首先检查如何创建服务,因为您不需要在构造函数中注入请求。阅读此documentation pagethis one,告诉您如何从附加内核请求事件的函数中收到的事件中获取请求。

另一方面,你正在使用实体经理,请再解释一下你得到了什么以及你想得到什么。