从实体中获取config.yml值


getting config.yml value out of an entity

我想从symfony2实体的config.yml中获取一个值。

config.yml:

my_example_bundle:
    slug_pattern: "/^[a-z0-9'._'-]{2,20}$/"

实体:

function setUsername($username) {
    $pattern = ""; // need to get it from slug_pattern in config.yml
    if (!preg_match($pattern, $username)) {
        throw new 'InvalidArgumentException("Username has to match " . $pattern);
    }
    ...
}

谢谢!

更新:Dev4TheWeb也发布了一个不错的解决方案:http://dev4theweb.blogspot.ch/2012/08/how-to-access-configuration-values.html

条令实体的问题在于何时从数据库中检索它们。它们是由条令指定的,而不经过构造函数,因此可能与生成new语句时具有不同的依赖关系。

正因为如此,让你的模特意识到这一点可能是个坏主意。您可能更喜欢使用外部服务,也更喜欢贫血模型(简单的数据对象)。然后,您可以将所有逻辑委托给一个专用服务。

如果你不想,你仍然可以手动注入depedenceis(例如在构造函数中)。只有当您手动初始化实体时,这才有效。

然后,您必须利用条令postLoad事件来注入相同的依赖关系(例如通过setter)。这种重复有些糟糕。

  • 条令2向加载的模型注入数据
  • Symfony2/Doctrine2:在侦听器中管理多个实体管理器的问题
  • 带有Symfony DI容器的条令2