Let’s say that a Human can have Item(s) inside his pocket. Each Item has different effect on the Human.
When he use an item, it goes to 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");
}
}
Does the heal function can be placed here ? I believe that it’s not supposed to be in the Controller. But I also believe it should not be placed inside the Item Entity (because of the Response, and because it uses $Human)
It depends. My reasoning for these type of questions is this: if I’ll only use the function in the controller, it can stay there. But if it’s likely to be a shared function, I’ll create a service for it. Maybe you want to be able to heal humans via a command, or a different controller or something. In that case it makes sense to use shared code for this.
Creating a service is really easy, and enables you to keep logic in a shared place. In my opinion the controller is more useful to handle the request flow.