在 Symfony2 中放置模型辅助函数的位置 [英] Where to put model helper functions in Symfony2

查看:22
本文介绍了在 Symfony2 中放置模型辅助函数的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下功能:

function array_duplicates($array)
{
    $duplicates = array();
    $unique = array_unique($array);
    for ($i = 0; $i < count($array); $i++) {
        if (!array_key_exists($i, $unique)) {
            $duplicates[] = $array[$i];
        }   
    }   
    return $duplicates;
}

此功能显然不适用于任何特定模型,也不是模板助手.放置此功能的合适位置在哪里?(请不要说任何你想要的地方".)

This function obviously doesn't apply to any certain model, and it's not a template helper. Where would be the appropriate place to put this function? (Please don't say "anywhere you want.")

推荐答案

这可能是您放入服务的类型.创建一个这样的类:

This might be the type of thing you'd put into a service. Create a class like this:

class ArrayUtils
{
    function array_duplicates($array)
    {
        ... 
        return $duplicates;
    }
}

然后将其定义为服务.如果您使用的是 YAML,您可以将这样的内容放入 config.yml 文件中:

And then define it as a service. If you're using YAML, you'd put something like this into your config.yml file:

services:
    arrayUtils:
        class:        Full\Path\To\ArrayUtils

在此配置下,Symfony 将创建您的 ArrayUtils 的单个实例,并为您的所有控制器提供访问权限.然后你可以这样称呼它:

Under this configuration, Symfony will create a single instance of your ArrayUtils, and give all your controllers access to it. Then you can call it like this:

class SomeController
{
    public function someAction()
    {
        ...
        $duplicates = $this->get("arrayUtils")->array_duplicates($array);
        ...
    }
}

这都是 Symfony 依赖注入框架的一部分.它非常酷,我建议在这里阅读它:http://symfony.com/doc/2.0/book/service_container.html

This is all part of Symfony's dependency injection framework. It's pretty cool, and I recommend reading up on it here: http://symfony.com/doc/2.0/book/service_container.html

替代方案

现在,对于这么小的代码块来说,这可能有点矫枉过正.如果您只想在单个包中使用它,那么您可能只想将它放入一个基本控制器中,并让所有其他控制器扩展该基本控制器.

Now, that might be a little overkill for such a small chunk of code. If you're only going to be using this in a single bundle, then you might want to just put it into a base controller, and have all your other controllers extend that base controller.

class BaseController
{
    function array_duplicates($array)
    {
        ...
    }
}

class SomeController extends BaseController
{
    function someAction()
    {
        $this->array_duplicates($array);
    }
}

这篇关于在 Symfony2 中放置模型辅助函数的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆