2
votes

I have an action in a controller and it must works like a "factory widget":

public function actionRenderWidget($widget)
{
    $widgetClass = 'My'.$widget.'Widget';
    return $widgetClass::widget();
}

What is the correct way to implement something similar?

2

2 Answers

3
votes

You should simply use class name with namespace (no need to use call_user_func()), e.g. :

$widgetClass = 'app\widgets\My'.$widget.'Widget';
return $widgetClass::widget();

Read more about Dynamically accessing namespaced elements.

0
votes
//example
$className = 'yii\jui\DatePicker';

return call_user_func($className .'::widget');

OR

$config = [];
$widget = Yii::createObject($className, $config);
return call_user_func([$widget, 'widget']);