Symfony 3.1 — создать глобальный параметр для AppBundle

#php #dependency-injection #configuration #symfony-3.1

#php #внедрение зависимости #конфигурация #symfony-3.1

Вопрос:

Я пытаюсь определить некоторые параметры внутри AppBundle, но безуспешно. Это один из моих первых тестов на этом фреймворке, поэтому может быть очевидная концепция, которую я неправильно понял.

Первой проблемой является поле bundle_version, которое не читается внутри файла YAML. Возвращаемая ошибка заключается в следующем :

 [SymfonyComponentConfigDefinitionExceptionInvalidConfigurationException]
The child node "bundle_version" at path "costs" must be configured.
  

Когда я комментирую эту строку, я получаю другую ошибку :

 [SymfonyComponentDependencyInjectionExceptionInvalidArgumentException]
There is no extension able to load the configuration for "costs" (in W:wamp64wwwtestsrcAppBundleDependencyInjecti
on/../Resources/configcosts.yml). Looked for namespace "costs", found none
  

src/AppBundle/DependencyInjection/Configuration.php

 namespace AppBundleDependencyInjection;

use SymfonyComponentConfigDefinitionConfigurationInterface;
use SymfonyComponentConfigDefinitionBuilderTreeBuilder;

class Configuration implements ConfigurationInterface
{
    public function getConfigTreeBuilder()
    {
        $treeBuilder = new TreeBuilder();
        $rootNode = $treeBuilder->root('costs');

        $rootNode->children()
                    // THIS LINE DON'T WORK AND CAUSE THE 1st PROBLEM
                    ->floatNode('bundle_version')->isRequired()->end() 
                    ->arrayNode('shipping')
                        ->children()
                            ->floatNode('es')->isRequired()->end()
                            ->floatNode('it')->isRequired()->end()
                            ->floatNode('uk')->isRequired()->end()
                        ->end()
                    ->end()

                    ->arrayNode('services')
                        ->children()
                            ->floatNode('serviceA')->isRequired()->end()
                            ->floatNode('serviceB')->isRequired()->end()
                        ->end()
                    ->end()
                ->end();

        return $treeBuilder;
    }
}
  

/src/AppBundle/Resources/config.costs.yml

 costs:
    bundle_version: 1.0 # THIS FIELD IS NOT RECOGNIZED
    shipping:
        es: 18.00
        it: 19.00
        uk: 20.00
    services:
        serviceA: 15.00
        serviceB: 20.00
  

/src/AppBundle/DependencyInjection/AppExtension.php

 namespace AppBundleDependencyInjection;

use SymfonyComponentDependencyInjectionContainerBuilder;
use SymfonyComponentHttpKernelDependencyInjectionExtension;
use SymfonyComponentDependencyInjectionLoaderYamlFileLoader;
use SymfonyComponentConfigFileLocator;

class AppExtension extends Extension
{

    public function load(array $config, ContainerBuilder $container)
    {
        $loader = new YamlFileLoader(
                $container,
                new FileLocator(__DIR__.'/../Resources/config')
                );
        $loader->load('costs.yml');
    }
}
  

Ответ №1:

Решение довольно простое, как я и ожидал… В /app/config/config.yml есть предопределенная клавиша «параметры», и мы должны поместить сюда наши параметры, если они не относятся к конкретному пакету.

Итак, это просто что-то вроде :

 # /app/config/config.yml
imports:
    - { resource: parameters.yml }
    - { resource: security.yml }
    - { resource: services.yml }

# Put parameters here that don't need to change on each machine where the app is deployed
 # http://symfony.com/doc/current/best_practices/configuration.html#application-    related-configuration
parameters:
      locale: fr
my_param: my_value
  

Затем в вашем контроллере :

 //   /src/AppBundle/Controller/DefaultController.php

    class DefaultController extends Controller
    {
        /**
         * @Route("/", name="homepage")
         */
        public function indexAction(Request $request)
        {
            $this->getParameter('my_param'); // or $this->getContainer()->getParameter('my_param');

            // replace this example code with whatever you need
            return $this->render('default/index.html.twig', [
                'base_dir' => realpath($this->getParameter('kernel.root_dir').'/..').DIRECTORY_SEPARATOR,
            ]);
        }
    }
  

Надеюсь, это поможет