在 Symfony2 中,我应该把控制器使用的函数放在哪里


In Symfony2, where should I put that function used by my Controller?

假设一个Human的口袋里可以有Item。 每个ItemHuman有不同的影响。

当他使用一个物品时,它会变成ItemController

class ItemController extends Controller
{
    public function useAction() {
       // Human
        $human = new Human();
       // Item
        $request = Request::createFromGlobals();
        $item_id = $request->request->get('item_id', 0);
        $item = new Item($item_id);
        // Different effects depending on the Item used
        switch($item->getArticleId()) {
            case 1: $this->heal($human, $item, 5); break; // small potion
            case 2: $this->heal($human, $item, 10); break; // medium potion
            case 3: $this->heal($human, $item, 15); break; // big potion
        }
    }
    // The following Heal Function can be placed here ?
    private function heal($human, $item, $life_points) {
        $human->addLife($life_points);
        $item->remove();
        return new Response("You have been healed of $life_points");
    }
}

heal function可以放在这里吗?我相信它不应该在控制器中。但我也认为它不应该放在Item Entity内(因为响应,因为它使用了$Human)

这取决于。我对这类问题的推理是:如果我只使用控制器中的函数,它可以留在那里。但是,如果它可能是一个共享功能,我将为它创建一个服务。也许您希望能够通过命令或不同的控制器或其他东西来治愈人类。在这种情况下,为此使用共享代码是有意义的。

创建服务非常简单,它使您能够将逻辑保存在共享位置。在我看来,控制器对于处理请求流更有用。

我认为你可以这样做:

1:继承

  class BaseHumanController extend Controller{
  public function heal($param1, $param2, $param3){
  //put logic here
  }
} 
//Extend from BaseHumanController in any controller for call heal() method
class ItemController extend BaseHumanController{
//....
 $this->heal(...)
} 

2:使用 heal() 方法创建一个类,并配置为 @Peter Kruithof 的服务

我绝对认为它会进入控制器。 来自维基百科:

控制器调解输入,将其转换为模型的命令 或查看。

如果你看一下由symfony2 crud生成器生成的删除函数,它会在实体上调用删除:

/**
 * Deletes a Bar entity.
 *
 * @Route("/{id}/delete", name="bar_delete")
 * @Method("post")
 */
public function deleteAction($id)
{
    $form = $this->createDeleteForm($id);
    $request = $this->getRequest();
    $form->bindRequest($request);
    if ($form->isValid()) {
        $em = $this->getDoctrine()->getEntityManager();
        $entity = $em->getRepository('FooBundle:Bar')->find($id);
        if (!$entity) {
            throw $this->createNotFoundException('Unable to find Bar entity.');
        }
        $em->remove($entity);
        $em->flush();
    }
    return $this->redirect($this->generateUrl('bar_index'));
}

我认为没有理由不应该在控制器中。只需将其设置为私有方法,如果您只打算在那里使用它。