在symfony中重构Controller以适应六边形体系结构

问题描述 投票:2回答:1

我创建了一个控制器,用于在数据库中创建所有者记录。一切都是在CreateOwnerController上完成的,并且正常工作:

class CreateOwnerController extends Controller
{
     public function executeAction(Request $request)
     { 
       $em = $this->getDoctrine()->getManager();
       $owner = new Owner($request->request->get("name"));
       $em->persist($owner);
       $em->flush();

    return new Response('Added',200);
}

}

现在,为了重构我创建了一个定义OwnerRepository的接口:

interface OwnerRepositoryInterface {
    public function save(Owner $owner);
}

以及实现此接口的OwnerRepository:

class OwnerRepository extends EntityRepository implements OwnerRepositoryInterface {
    public function save(Owner $owner) {
        $this->_em->persist($owner);
        $this->_em->flush();
    }
}

然后我为应用层创建了一个CreateOwnerUseCase类,它接收一个OwnerRepository并执行一个方法来保存到OwnerRepository中:

class CreateOwnerUseCase {
    private $ownerRepository;
    public function __construct(OwnerRepositoryInterface $ownerRepository) {
        $this->ownerRepository = $ownerRepository;
    }

    public function execute(string $ownerName) {
        $owner = new Owner($ownerName);
        $this->ownerRepository->save($owner);
    }
}

好的,我正在拆分初始的控制器介绍层域/应用程序/框架层。

CreateOwnerController现在我已经实例化了Use Case并作为参数传递给OwnerRepository,如下所示:

class CreateOwnerController extends Controller {
    public function executeAction(Request $request) { 
        $createOwnerUseCase = new CreateOwnerUseCase(new OwnerRepository());
        $createOwnerUseCase->execute($request->request->get("name"));
        return new Response('Added',200);
    }

}

但是在创建新所有者的请求时失败:

警告:缺少Doctrine \ ORM \ EntityRepository :: __ construct()的参数1,在/ansible/phpexercises/Frameworks/mpweb-frameworks-symfony/src/MyApp/Bundle/AppBundle/Controller/CreateOwnerController.php中调用

它发生在作为参数传递的OwnerRepository上。它需要一个$em和Mapped Class ......这个映射类的含义是什么?怎么解决这个错误?

php doctrine-orm frameworks symfony
1个回答
1
投票

这个答案适用于Symfony 3.3 + / 4 +。

您需要将存储库注册为服务。您应该使用组合而不是继承来代替扩展第三方代码。

final class OwnerRepository implements OwnerRepositoryInterface
{
    private $entityManager;

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

    public function save(Owner $owner) 
    {
        $this->entityManager->persist($owner);
        $this->entityManager->flush();
    }
}

并将其注册为服务:

# app/config/services.yml
services:
    App\Repository\:
        # for location app/Repository
        resource: ../Repository

您可能需要稍微调整路径,以使其工作。

要获得更多扩展答案,请参阅How to use Repository with Doctrine as Service in Symfony

© www.soinside.com 2019 - 2024. All rights reserved.