Symfony2 - how to extend a vendor bundle (e.g. of

2019-04-08 13:59发布

问题:

Scenario:

I'm using a bundle (FOSFacebookBundle) that allows me to set parameters for exactly one facebook app in my configuration. Everything works perfectly fine, but now I need to set not only one app, but multiple.

My approach:

I've created a AcmeFacebookBundle, which allows multiple apps to be defined (configuration defined in Acme\FacebookBundle\DependencyInjection\Configuration) in an array like so:

acme_facebook:
    apps:
        some_competition:
            server_url: %acme.facebook.some_competition.server_url%
            file:   %kernel.root_dir%/../vendor/facebook/php-sdk/src/base_facebook.php
            alias:  facebook
            app_id: %acme.facebook.some_competition.app_id%
            secret: % acme .facebook.some_competition.secret%
            cookie: true
            permissions: [email, user_birthday, user_location]
        some_other_competition:
            server_url: %acme.facebook. some_other_competition.server_url%
            file:   %kernel.root_dir%/../vendor/facebook/php-sdk/src/base_facebook.php
            alias:  facebook
            app_id: %acme.facebook. some_other_competition.app_id%
            secret: % acme .facebook. some_other_competition.secret%
            cookie: true
            permissions: [email, user_birthday, user_location]

In Acme\FacebookBundle\DependencyInjection\AcmeFacebookExtension I am then looping through all apps. The idea is to compare the server_url parameter against the current URL and override the fos_facebook configuration with mine.

class AcmeFacebookExtension extends Extension
{
    ...
    /**
     * {@inheritDoc}
     */
    public function load(array $configs, ContainerBuilder $container)
    {
        $configuration = new Configuration();
        $config = $this->processConfiguration($configuration, $configs);

        foreach ($config['apps'] as $app)
        {
            // check for matching path here?
            foreach (array('file', 'app_id', 'secret', 'cookie', 'domain', 'logging', 'culture', 'permissions') as $attribute)
            {
                $container->setParameter('fos_facebook.' . $attribute, $app[$attribute]);
            }
        }
    }

Problem:

But this is exactly where I'm stuck. Obviously, I have no access to the Request object or the DiC from within AcmeFacebookExtension to do this comparison. Am I going completely wrong in my approach? Do you have any better idea on how to tackle this problem?

回答1:

What you want to create is a CompilerPass so that you can manipulate the Container after all other configuration has loaded. These should get you started:

  • Symfony2: Service Container Compiler Passes
  • Symfony2: Manipulating Service Parameters and Definitions
  • Create a CompilerPass