2017-09-25 103 views
2
$form = new Form(); 
return $form->addHiddenElement('somename', 'value') 
    ->addTextInputElement('someothername', 'value') 
    ->generate(); 

我们有一个简单的表单生成器,其工作方式与上面的一样。如何在PHP中动态调用函数的对象链?

是否有可能完成这个配置,例如一个简单的PHP数组?

我知道关于:http://php.net/manual/en/function.call-user-func-array.php和其他类似的功能。但是,在上面我们有各自的功能未知数量使用参数未知数量和每个必须链到下一个...

对于这个数组可能正确映射..

return [ 
    'addHiddenElement' => [ 
     'somename', 'value' 
    ], 
    'addTextInputElement' => [ 
     'someothername', 'value' 
    ] 
] 

这是可能在PHP?

(在JavaScript中,这可能与邪恶的eval来完成;),但我的想法有可能做到这一点在PHP)

+0

你正在使用什么框架? –

+0

您可能想要查看**服务管理器**及其各种实现(symfony等)的概念。其中一部分正是你打算做的。 – Calimero

+0

@AlivetoDie我们没有框架,不幸的是不能切换到一个框架。 @ Calimero好吧,将调查,认为可能是抽象这种事情在PHP – John

回答

2

是的,你可以在香草做到这一点(wihout某种框架之有道)PHP通过在每个函数中返回$this。考虑该类

class Form{ 
    public function addHiddenElement($name, $value) 
    { 
     /**Do some stuff**/ 
     return $this; //This will allow you to chain additional functions 
    } 
    public function addTextInputElement($name, $value) 
    { 
     /** Do some more stuff */ 
     return $this; 
    } 
} 

这样,因为你总是返回$this你可以从一起上课链其他方法(如$form->addHiddenElement('name','value')->addTextInputElement('name','value');

既然你总是返回$this你应该使用exceptions错误处理。

编辑:要使用配置生成的函数列表你可以使用一个简单的函数是这样的:

function buildForm($config) 
{ 
    $form = new Form(); //Create the form object 
    foreach($config as $function=>$params){ //iterate over the requested functions 
     if(method_exists($form, $function){ //Confirm the function exists before attemting execution 
      /** Updating $form to the result of the function call is equivalent to chaining all the functions in the $config array */ 
      $form = call_user_func_array(array($form, $function), $params); 
     } 
    } 
    return $form; 
} 

你可以这样调用该函数是这样的:

$config = [ 
    'addHiddenElement' => [ 
     'somename', 'value' 
    ], 
    'addTextInputElement' => [ 
     'someothername', 'value' 
    ] 
]; 
$form = buildForm($config); 

此函数的功能等同于你的链接功能。

请注意一些注意事项。

  1. 上述函数假定$config中包含的所有方法都返回$this。如果你愿意,你可以添加一些验证逻辑来​​说明那些没有的方法。
  2. 这个函数可以让你调用Form中的任何公共方法,在执行函数之前你可能想添加一些逻辑来验证$config
+0

std策略嗨,哟,我们有表单生成器返回当前对象($ this),从而启用链接。但我们现在希望能够通过配置来调用整个事物,例如我发布的数组。 – John

+0

我误解了,编辑我的答案。 – GentlemanMax

+0

啊哈..当然!由于每个func都会返回,所以可以再次调用它。完美的感谢很多:) – John