gpt4 book ai didi

php - 构建选择列表的最佳实践是什么

转载 作者:行者123 更新时间:2023-12-04 05:17:35 24 4
gpt4 key购买 nike

我有一个带有选择类型元素的表单。我需要用数据填充它。据我所知,有3种方法。

1. Controller :

// Controller
public function myAction()
{
$choices = ...; // create choices array
$form = $this->createForm(new MyFormType($dm), null, array(
'choices' => $choices,
));
}

// Form
class MyFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('cars', 'choice', array(
'choices' => $options['choices']
));
}
}

2.表单类+存储库
// Controller
public function myAction()
{
$dm = $this->get('doctrine')->getManager();
$form = $this->createForm(new MyFormType($dm));
}

// Form
class MyFormType extends AbstractType
{
private $dm;

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

public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('cars', 'choice', array(
'choices' => $options['choices']
));
}

public function setDefaultOptions(OptionsResolverInterface $resolver)
{
$list = array();
foreach($this->dm->getRepository('MyBundle:Cars')->findAll() as $car) {
$list[$car->getName()] = $car->getName();
}

$resolver->setDefaults(array(
'choices' => $list,
));
}
}

3.表单类+定制服务
// Controller
public function myAction()
{
$dm = $this->get('doctrine')->getManager();
$form = $this->createForm(new MyFormType(), null, array(
'myservice' => $this->get('myservice'),
));
}

// Form
class MyFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('cars', 'choice', array(
'choices' => $options['myservice']->getCars()
));
}
}

// Service
class MyService
{
const ENTITY_CAR = 'MyBundle:Cars';

/** @var DocumentManager */
private $dm;

public function __construct(DocumentManager $dm)
{
$this->dm = $dm;
}

public function getCars()
{
return $this->dm->getRepository("MyBundle:Cars")->findAll();
}
}

我来表达我的想法。

第一个选项不是最佳实践。特别是当涉及复杂的逻辑时。 Controller 应该尽可能小。

第二个好多了。但它公开了实体名称,如果我决定重命名它,可能会出现问题。

第三个是最好的选择,恕我直言。实体名称集中在一处,更好的 IDE 类型提示,集中的实体管理(搜索、保存、删除...)。主要缺点是可能过度设计的类,因为它负责许多读/写操作。另一方面,它可以分成几部分。

你怎么看?

最佳答案

如果您必须在代码中的其他地方重用该服务,则第三个选项很好(如果该服务与您编写的相比有所增长,我们稍后会看到)。这样,正如您所说,该实体的“经理”是一个,并且包含自己的 repo 名称、const 等。
但是
如果此服务仅用作通过隐藏其名称来访问您的存储库的“推送器”,我认为此解决方案仍然没有看起来那么好。
显然,如果认为该服务具有多个持久性选项和多个检索选项(基于您选择的 ORM),那么这可能是最佳实践。
在其他情况下,我认为第二个总是更好。
第一个是不切实际的,除非你想忽略所有的好习惯

关于php - 构建选择列表的最佳实践是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14067065/

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