2016-11-21 81 views
0

我想在控制器外部访问我的配置变量。

当我尝试:

class pdfFooter extends \TCPDF 
{ 
public function footer() 
{ 
    $config = $this->get('core_parameters'); 
} 
} 

我得到这个错误:

Uncaught PHP Exception Symfony\Component\Debug\Exception\UndefinedMethodException: "Attempted to call an undefined method named "get" of class "Plugin\PrintBundle\Controller\pdfFooter".

简单地调用:

$this->writeHTMLCell($config->getParameter('heading_color_config')); 

触发它。我遇到的这个问题的大多数其他主题都建议将其全球化。当然有更好的方法?

+1

刚注入容器,https://stackoverflow.com/questions/40692433/how-to-get-the-root-path-in-helper-class-symfony2/40693266#40693266 – Federkun

+1

不管你做什么,都不要注入容器。相反,学习一些关于服务的知识,然后注入配置对象。 http://symfony.com/doc/current/service_container.html – Cerad

+0

为什么要注入容器是坏的? (愚蠢的问题,我敢肯定,我是Symfony的新手) – billblast

回答

3

您必须注入容器,以便您可以访问您需要的服务和参数。

但是,像@Cerad说的那样,主要原因(其中包括许多:无类型提示,无法控制使用的服务,RunTime编译错误,缺少依赖关系等)为什么注入容器不是一个好主意,因为依赖关系替换:如果在库中定义了服务,那么您将无法使用本地依赖关系来替换依赖关系,从而满足您的需求[1]

如果可能的话,你应该避免它。 这里是什么样子注入只是你需要的参数:

(该PARAMS必须definef提前在配置文件)

services: 
    yourapp.bundle.pdffooter: 
     class: App\Bundle\Foo\pdfFooter 
     arguments: ['%param1%','%param2%',...] 

在你的类:

class pdfFooter 
{  
private $param1; 
private $param2; 
// ... 

public function __construct($param1,$param2,...) 
{ 
    $this->param1 = $param1; 
    $this->param2 = $param2; 
    // ... 
} 

public function footer() 
{ 

    // you can access your params directly here 
} 
+0

不完全。首先,ContainerInterface在这里对你没有任何帮助。其次,不使用容器的原因与大小和内存使用量无关。考虑调整你的答案以显示被注入的core_parameters? – Cerad