如何从数据库加载Symfony的配置参数(Doctrine)

Bai*_*aig 12 php symfony

parameters.yml我试图从数据库加载它们而不是硬编码参数.并非所有parameters.yml中的参数都需要从数据库加载一些,比如paypal的api细节

config.yml我已经导入了parameters.php

imports:
    - { resource: parameters.php }
Run Code Online (Sandbox Code Playgroud)

如果我parameters.php像下面那样添加静态信息,它可以正常工作

$demoName = 'First Last';
$container->setParameter('demoName', $demoName);
Run Code Online (Sandbox Code Playgroud)

但是我无法从数据库表中获取信息.我以为我应该创建类并使用$em = this->getDoctrine()->getManager();它,它应该工作,但它没有,我得到错误

Notice: Undefined variable: paypal_data in /opt/lampp/htdocs/services/app/config/parameters.php (which is being imported from "/opt/lampp/htdocs/services/app/config/config.yml").

这是我的尝试如下,但代码似乎没有进入 __construct()

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Doctrine\Bundle\DoctrineBundle\Registry;
use Doctrine\ORM\Mapping as ORM;

class parameters extends Controller
{
    public $paypal_data;

    function __construct() {
        $this->indexAction();
    }

    public function indexAction(){

        $em = $this->getDoctrine()->getManager();
        $this->paypal_data = $em->getRepository('featureBundle:paymentGateways')->findAll();

    }

}
$demoName = 'First Last';
$container->setParameter('demoName', $demoName);
$container->setParameter('paypal_data', $this->paypal_data);
Run Code Online (Sandbox Code Playgroud)

任何帮助都感激不尽.

Mic*_*bov 13

你做错了事.您需要声明CompilerPass并将其添加到容器中.整个容器将被加载...在编译时,您将可以访问其中的所有服务.

只需获取实体管理器服务并查询所需参数并将其注册到容器中.

分步说明:

  • 定义编译器传递:

    # src/Acme/YourBundle/DependencyInjection/Compiler/ParametersCompilerPass.php
    class ParametersCompilerPass implements CompilerPassInterface
    {
        public function process(ContainerBuilder $container)
        {
            $em = $container->get('doctrine.orm.default_entity_manager');
            $paypal_params = $em->getRepository('featureBundle:paymentGateways')->findAll();
            $container->setParameter('paypal_data', $paypal_params);
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)
  • 在bundle定义类中,您需要将编译器传递添加到容器中

    # src/Acme/YourBundle/AcmeYourBundle.php
    class AcmeYourBundle extends Bundle
    {
        public function build(ContainerBuilder $container)
        {
            parent::build($container);
    
            $container->addCompilerPass(new ParametersCompilerPass(), PassConfig::TYPE_AFTER_REMOVING);
        }
    }
    
    Run Code Online (Sandbox Code Playgroud)

  • 更新"设置"实体时清除缓存 (2认同)