2017-02-23 101 views
0

我在symfony項目中構建一個包時遇到了意想不到的行爲。
我已經建在DependencyInjection命名空間,我只是做了一個exportclass:Symfony爲您的軟件包設置導出類和配置

public function load(array $configs, ContainerBuilder $container) 
    { 
     $configuration = new Configuration(); 
     $config = $this->processConfiguration($configuration, $configs); 

     $container->setParameter('auction.path', $config[ 'path' ]); 
     $container->setParameter('auction.miao', $config[ 'miao' ]); 
     $container->setParameter('auction.stock.pain', $config[ 'stock' ][ 'pain' ]); 

     $loader = new YamlFileLoader(
      $container, 
      new FileLocator(__DIR__.'/../Resources/config/') 
     ); 
    } 
} 

從理論上講,我應該簡單地定義3個變量。如果我轉儲配置變量我得到以下輸出:

Array 
(
    [path] => C:\progetti_symfony\repository-cms\src\AuctionBundle\DependencyInjection../web/images/tmp/ 
    [miao] => C:\progetti_symfony\repository-cms\src\AuctionBundle\DependencyInjection../web/images/pmt/ 
) 

其中嵌套stock.pain部分(見下snippetfor細節)被忽略。

我則在同一文件夾中,我定義了配置該捆綁包的配置類(這裏是我失去了我的指南針):

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

     $rootNode 
         ->children() 
          ->scalarNode('path')->defaultValue(__DIR__ . '../web/images/tmp/')->end() 
          ->scalarNode('miao')->defaultValue(__DIR__ . '../web/images/pmt/')->end() 
          ->arrayNode('stock') 
           ->children() 
            ->scalarNode('pain')->defaultValue(__DIR__ . '../web/images/mpt/')->end() 
           ->end() 
          ->end() 
         ->end(); 
     return $treeBuilder; 
    } 
} 

如何組織和訪問該配置的任何建議?

+0

是什麼問題? – zenith

回答

2

如果未設置空值數組,您可以將其定義爲空數組stock。然後pain將被設置爲默認值。

$rootNode 
    ->beforeNormalization() 
     ->ifTrue(function($v) { 
      return !isset($v['stock']); 
     }) 
     ->then(function($v) { 
      $v['stock'] = array(); 
      return $v; 
     }) 
     ->end() 
    ->children() 
     ->scalarNode('path')->defaultValue(__DIR__ . '../web/images/tmp/')->end() 
     ->scalarNode('miao')->defaultValue(__DIR__ . '../web/images/pmt/')->end() 
     ->arrayNode('stock') 
      ->children() 
       ->scalarNode('pain')->defaultValue(__DIR__ . '../web/images/mpt/')->end() 
       ->end() 
      ->end() 
     ->end(); 

UPDATE:

更好的決策:使用addDefaultsIfNotSet()

$rootNode 
    ->children() 
     ->scalarNode('path')->defaultValue(__DIR__ . '../web/images/tmp/')->end() 
     ->scalarNode('miao')->defaultValue(__DIR__ . '../web/images/pmt/')->end() 
     ->arrayNode('stock') 
      ->addDefaultsIfNotSet() 
      ->children() 
       ->scalarNode('pain')->defaultValue(__DIR__ . '../web/images/mpt/')->end() 
       ->end() 
      ->end() 
     ->end();