source

Symfony 2 Entity Manager 주입 인 서비스

goodcode 2022. 10. 6. 21:35
반응형

Symfony 2 Entity Manager 주입 인 서비스

독자적인 서비스를 작성했기 때문에 EntityManager 교리를 삽입해야 하는데, 그것이 보이지 않습니다.__construct()내 담당이 호출받았는데 주사도 안 먹혔어

코드와 설정은 다음과 같습니다.

<?php

namespace Test\CommonBundle\Services;
use Doctrine\ORM\EntityManager;

class UserService {

    /**
     *
     * @var EntityManager 
     */
    protected $em;

    public function __constructor(EntityManager $entityManager)
    {
        var_dump($entityManager);
        exit(); // I've never saw it happen, looks like constructor never called
        $this->em = $entityManager;
    }

    public function getUser($userId){
       var_dump($this->em ); // outputs null  
    }

}

여기 있습니다services.yml내 보따로

services:
  test.common.userservice:
    class:  Test\CommonBundle\Services\UserService
    arguments: 
        entityManager: "@doctrine.orm.entity_manager"

나는 그 .yml을 에 Import했다.config.yml내 앱에서 그렇게

imports:
    # a few lines skipped, not relevant here, i think
    - { resource: "@TestCommonBundle/Resources/config/services.yml" }

컨트롤러에서 서비스를 호출할 때

    $userservice = $this->get('test.common.userservice');
    $userservice->getUser(123);

오브젝트(늘이 아님)는 취득하지만$this->emUserService는 null입니다.앞서 말씀드렸듯이 UserService의 컨스트럭터는 호출된 적이 없습니다.

또한 컨트롤러와 사용자 서비스는 다른 번들로 구성되어 있습니다(프로젝트를 정리하기 위해 꼭 필요합니다).그 외의 모든 것은 정상적으로 동작하며, 전화도 할 수 있습니다.

$this->get('doctrine.orm.entity_manager')

UserService 및 유효한(늘이 아닌) EntityManager 개체를 가져오는 데 사용하는 컨트롤러와 동일한 컨트롤러에 있습니다.

UserService 와 Attrin 설정 사이의 구성 또는 링크가 누락되어 있는 것 같습니다.

클래스의 생성자 메서드를 호출해야 합니다.__construct(),것은 아니다.__constructor():

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

최신 참조를 위해 Symfony 2.4+에서는 더 이상 생성자 주입 방법에 대한 인수 이름을 지정할 수 없습니다.설명서에 따르면 다음 내용을 전달합니다.

services:
    test.common.userservice:
        class:  Test\CommonBundle\Services\UserService
        arguments: [ "@doctrine.orm.entity_manager" ]

그런 다음 인수를 통해 나열된 순서대로 사용할 수 있습니다(1개 이상일 경우).

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

주의: Symfony 3.3 현재 EntityManager는 감가상각되어 있습니다.Entity Manager 사용대신 인터페이스를 사용합니다.

namespace AppBundle\Service;

use Doctrine\ORM\EntityManagerInterface;

class Someclass {
    protected $em;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->em = $entityManager;
    }

    public function somefunction() {
        $em = $this->em;
        ...
    }
}

2017년Symfony 3.3 이후 Repository를 서비스로 등록할 수 있으며 모든 이점을 누릴 수 있습니다.

보다 일반적인 설명은 Symfony에서 서비스로서의 독트린을 사용저장소 사용 방법참조하십시오.


구체적인 경우 튜닝을 사용한 원래 코드는 다음과 같습니다.

1. 서비스 또는 컨트롤러에서 사용

<?php

namespace Test\CommonBundle\Services;

use Doctrine\ORM\EntityManagerInterface;

class UserService
{
    private $userRepository;

    // use custom repository over direct use of EntityManager
    // see step 2
    public function __constructor(UserRepository $userRepository)
    {
        $this->userRepository = $userRepository;
    }

    public function getUser($userId)
    {
        return $this->userRepository->find($userId);
    }
}

2. 새로운 커스텀 저장소 생성

<?php

namespace Test\CommonBundle\Repository;

use Doctrine\ORM\EntityManagerInterface;

class UserRepository
{
    private $repository;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->repository = $entityManager->getRepository(UserEntity::class);
    }

    public function find($userId)
    {
        return  $this->repository->find($userId);
    }
}

3. 서비스 등록

# app/config/services.yml
services:
    _defaults:
        autowire: true

    Test\CommonBundle\:
       resource: ../../Test/CommonBundle

언급URL : https://stackoverflow.com/questions/10427282/symfony-2-entitymanager-injection-in-service

반응형