gpt4 book ai didi

php - 交响乐 2 : how to reduce this code?

转载 作者:搜寻专家 更新时间:2023-10-31 21:08:44 25 4
gpt4 key购买 nike

在完成 CRUD -stuff 时,我经常重复这些行:

// ../myBundle/Controller/MyController.php
$entityManager = $this->getDoctrine()->getManager();
$repository = $entityManager->getRepository('myBundle:myEntity');

我的想法是在 __construct() 中定义 $entityManager$repository,但据我所知,是 I'd have to define a service for my class 。这感觉被夸大了。

我怎样才能以有用的方式减少我的代码?

提前致谢

B.

最佳答案

实际上,只有在持久化实体时才需要管理器。如果你的 Controller 的这个 Action 只需要获取它们,那么你可以:

  • 只检索存储库,例如$this->getDoctrine()->getRepository(...)
  • 将存储库本身包装到一个服务中,这样它就可以通过 $this->container->get('my_bundle.my_entity.repository')
  • 访问

根据您的用例,您可以使用更适合的方法。

然而,从意识形态上讲,您所有的获取逻辑都应该在您的存储库中实现,因此您永远不必将您的存储库放入局部变量中。您应该能够执行 $this->getDoctrine()->getRepository('MyBundle:MyEntity')->findBySomething($args...),其中 $args 是您的标准。

如果您想从 Controller 中分离出所有持久性逻辑,那么管理器就是最佳选择。基本上,您将实现一个处理持久性和获取的类,可能委托(delegate)给它的依赖项。看看FOSUserBundle's UserManager得到这个想法。这种模式的用例看起来很像这样:

<?php

class CatsController extends Controller
{
public function list()
{
return $this->get('my_bundle.cats_manager')->findAll();
}

public function get($name)
{
return $this->get('my_bundle.cats_manager')->findOneByName($name);
}

public function create(Request $request)
{
$cat = new Cat(
'Micky',
'siamese'
);

$this->get('my_bundle.cats_manager')->persist($cat);
}

// ...
}

关于php - 交响乐 2 : how to reduce this code?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26920954/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com