如何从Symfony 2中的任何类访问配置参数?

如何从Symfony 2中的任何类访问配置参数?

问题描述:

I've got a simple Model class that loads and saves a file:

<?php

namespace AppBundle\Model;

class WidgetModel {

    public function load() {}

    public function save() {}

}

From this class, I need to access configuration parameters defined in config.yml:

parameters:
    widgets:
        1:
            width: 300
            height: 250
        2:
            width: 240
            height: 320

In a controller, I would normally use the syntax $widgetConfig = $this->getParameter('widget'); but obviously it won't work in this case.

What would be the correct way to do this from any class?

If you are speaking about a Service, you can inject parameters.

If you speak about inject parameters in your Entities, it is sadly bad practise. A Symfony Entity is designed to be POPO (plain old php object), so it should not know anything outside its scope (that is, no persistence, no container, ...).