2

在我的 Bundle 扩展中,我将方法调用(基于配置动态地)添加到我的服务定义中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有没有办法检查这个?

4

2 回答 2

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));
}
于 2013-04-05T15:28:58.150 回答
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));
    }
}
于 2013-04-05T15:26:38.580 回答