假设一个人
的口袋里可以有Item
。每个 Item
对 Human
都有不同的影响。
当他使用一个项目时,它会转到 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
可以放在这里吗? 我认为它不应该放在 Controller 中。但我也认为它不应该放在 Item Entity
中(因为响应,并且因为它使用 $Human)
最佳答案
这取决于。我对这类问题的推理是这样的:如果我只使用 Controller 中的功能,它可以留在那里。但如果它可能是一个共享功能,我会为它创建一个服务。也许你希望能够通过命令或不同的 Controller 或其他东西来治愈人类。在这种情况下,为此使用共享代码是有意义的。
Creating a service真的很简单,并使您能够将逻辑保存在一个共享的地方。在我看来, Controller 对于处理请求流更有用。
关于php - 在 Symfony2 中,我应该把 Controller 使用的函数放在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11236312/