Advertisement
patrickt

Symfony Config Loader

Mar 16th, 2017
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.86 KB | None | 0 0
  1. <?php
  2. namespace MyCompany\Api\DependencyInjection;
  3.  
  4. use Symfony\Component\DependencyInjection\ContainerBuilder;
  5. use Symfony\Component\DependencyInjection\Loader;
  6. use Symfony\Component\Config\FileLocator;
  7. use MyCompany\Api\Exception\ApiException;
  8.  
  9. /**
  10.  * Class MyCompanyApiConfig
  11.  * @package MyCompany\Api\DependencyInjection
  12.  */
  13. class MyCompanyApiConfig {
  14.   /** @var MyCompanyApiConfig - Hold an instance of the class */
  15.   private static $instance;
  16.   private static $container;
  17.  
  18.   /**
  19.    * The singleton method
  20.    *
  21.    * @return \MyCompany\Api\DependencyInjection\MyCompanyApiConfig
  22.    */
  23.   public static function getInstance() {
  24.     if (!isset(self::$instance)) {
  25.       self::$instance = new MyCompanyApiConfig();
  26.     }
  27.  
  28.     return self::$instance;
  29.   }
  30.  
  31.   /**
  32.    * Handle dynamic, static calls to the object.
  33.    *
  34.    * @param  string  $method
  35.    * @param  array   $args
  36.    * @return mixed
  37.    *
  38.    * @throws ApiException
  39.    */
  40.   public static function __callStatic($method, $args) {
  41.     $instance = static::getInstance();
  42.  
  43.     if (!$instance) {
  44.       throw new ApiException('Unable to load the class instance.');
  45.     }
  46.  
  47.     return $instance->$method(...$args);
  48.   }
  49.  
  50.   /**
  51.    * @param $varName
  52.    * @return mixed
  53.    * @throw \Symfony\Component\DependencyInjection\Exception\InvalidArgumentException
  54.    */
  55.   public static function get($varName) {
  56.     return self::loadConfig()->getParameter($varName);
  57.   }
  58.  
  59.   /**
  60.    * @return \Symfony\Component\DependencyInjection\ContainerBuilder
  61.    */
  62.   public static function loadConfig() {
  63.     if (empty(self::$container)) {
  64.       self::$container = new ContainerBuilder();
  65.  
  66.       $loader = new Loader\YamlFileLoader(self::$container, new FileLocator(__DIR__.'/../Resources/config'));
  67.       $loader->load('services.yml');
  68.       $loader->load('config.yml');
  69.     }
  70.  
  71.     return self::$container;
  72.   }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement