Skip to content

Instantly share code, notes, and snippets.

@carteni
Last active September 25, 2021 10:47
Show Gist options
  • Save carteni/089cdd3c66041a7f3aafc406cc1c6d39 to your computer and use it in GitHub Desktop.
Save carteni/089cdd3c66041a7f3aafc406cc1c6d39 to your computer and use it in GitHub Desktop.
Symfony Dependency Injection. Create a custom config loader.
<?php
use Symfony\Component\Config\Loader\LoaderInterface;
use Symfony\Component\HttpKernel\Kernel;
class AppKernel extends Kernel
{
public function registerBundles()
{
// ...
return $bundles;
}
protected function getContainerLoader(\Symfony\Component\DependencyInjection\ContainerInterface $container)
{
$delegating = parent::getContainerLoader($container);
/** @var \Symfony\Component\Config\Loader\LoaderResolver $resolver */
$resolver = $delegating->getResolver();
$resolver->addLoader(new \AppBundle\DependencyInjection\Loader\MyCustomConfigLoader($container));
return $delegating;
}
}
imports:
- { resource: my_custom_loader }
<?php
namespace AppBundle\DependencyInjection\Loader;
use Symfony\Component\Config\Loader\Loader;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class MyCustomConfigLoader extends Loader
{
/**
* @var ContainerBuilder
*/
protected $container;
/**
* MyCustomConfigLoader constructor.
*
* @param \Symfony\Component\DependencyInjection\ContainerBuilder $container
*/
public function __construct(ContainerBuilder $container)
{
$this->container = $container;
}
/**
* Loads a resource.
*
* @param mixed $resource The resource
* @param string|null $type The resource type or null if unknown
*
* @throws \Exception If something went wrong
*/
public function load($resource, $type = null)
{
$this->container->setParameter("app.my_custom_loader_parameter", "value");
// Loads services...
}
/**
* Returns whether this class supports the given resource.
*
* @param mixed $resource A resource
* @param string|null $type The resource type or null if unknown
*
* @return bool True if this class supports the given resource, false otherwise
*/
public function supports($resource, $type = null)
{
return ("my_custom_loader" === $resource);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment