php - 在 Symfony2 中,我应该把 Controller 使用的函数放在哪里?

标签 php symfony controller

假设一个的口袋里可以有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 可以放在这里吗? 我认为它不应该放在 Controller 中。但我也认为它不应该放在 Item Entity 中(因为响应,并且因为它使用 $Human)

最佳答案

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

Creating a service真的很简单,并使您能够将逻辑保存在一个共享的地方。在我看来, Controller 对于处理请求流更有用。

关于php - 在 Symfony2 中,我应该把 Controller 使用的函数放在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11236312/

相关文章:

PHP 画廊,缩略图列表

php - 允许 symfony 访问控制中的 Controller 操作

php - MVC PHP : Data manipulation in View loop or Controller loop (ie. 1 个循环或 2 个循环)

ruby-on-rails - Rails Controller 测试 : Does database state change persist after success of test?

php - Symfony 2 Acls insertClassAces

Grails Controller 变量在 View 中不可见

php - CodeIgniter MVC 最佳实践 - Controller

php - 使用mysql使用另一列获取唯一ID

php - 使用 ZipArchive 提取文件夹内容

javascript - 从JS发送数据到Controller中的函数,并从函数中获取结果