是的,你可以在香草做到这一点(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);
此函数的功能等同于你的链接功能。
请注意一些注意事项。
- 上述函数假定
$config
中包含的所有方法都返回$this
。如果你愿意,你可以添加一些验证逻辑来说明那些没有的方法。
- 这个函数可以让你调用
Form
中的任何公共方法,在执行函数之前你可能想添加一些逻辑来验证$config
。
你正在使用什么框架? –
您可能想要查看**服务管理器**及其各种实现(symfony等)的概念。其中一部分正是你打算做的。 – Calimero
@AlivetoDie我们没有框架,不幸的是不能切换到一个框架。 @ Calimero好吧,将调查,认为可能是抽象这种事情在PHP – John