2013-04-05 21 views
2

在我的捆綁擴展我添加方法調用(動態,基於配置),以我的服務定義my.service檢查定義是否有方法,添加(或不)方法調用?

/** 
* {@inheritdoc} 
*/ 
public function load(array $configs, ContainerBuilder $container) 
{ 
    // ... 

    // Get the defintion 
    $definition = $container->getDefinition('my.service'); 

    // Dynamically add method calls to the definition 
    foreach($config['options'] as $name => $value) { 
     $definition->addMethodCall('set'.ucfirst($name), array($value)); 
    } 

    // ... 
} 

我想不叫addMethodCall如果方法不存在中定義。有什麼方法可以檢查嗎?

回答

3

我假設你只想要添加的方法如果您的服務等級具有這些方法的定義,請致電您的服務等級

$serviceMethods = get_class_methods($definition->getClass()); 
//loop on your added methods 

$method = 'set'.ucfirst($name); 
if(in_array($method, $serviceMethods)) 
{ 
    $definition->addMethodCall($method, array($value)); 
} 
2

你能不使用獲取類..

$class = $definition->getclass(); 

,然後檢查方法添加它之前存在..

foreach($config['options'] as $name => $value) { 
    $method = 'set'.ucfirst($name); 

    if (method_exists($class, $method) 
    { 
     $definition->addMethodCall('set'.ucfirst($name), array($value)); 
    } 
} 
相關問題