@Chiang
2020-08-23T10:52:14.000000Z
字数 2043
阅读 767
widget() begin() end() 方法2020-08 Yii2.0
/*** Creates a widget instance and runs it.* The widget rendering result is returned by this method.* @param array $config name-value pairs that will be used to initialize the object properties* @return string the rendering result of the widget.* @throws \Exception*/public static function widget($config = []){ob_start();ob_implicit_flush(false);try {/* @var $widget Widget */$config['class'] = get_called_class();$widget = Yii::createObject($config);$out = '';if ($widget->beforeRun()) {$result = $widget->run();$out = $widget->afterRun($result);}} catch (\Exception $e) {// close the output buffer opened above if it has not been closed alreadyif (ob_get_level() > 0) {ob_end_clean();}throw $e;}return ob_get_clean() . $out;}
/*** Begins a widget.* This method creates an instance of the calling class. It will apply the configuration* to the created instance. A matching [[end()]] call should be called later.* As some widgets may use output buffering, the [[end()]] call should be made in the same view* to avoid breaking the nesting of output buffers.* @param array $config name-value pairs that will be used to initialize the object properties* @return static the newly created widget instance* @see end()*/public static function begin($config = []){$config['class'] = get_called_class();/* @var $widget Widget */$widget = Yii::createObject($config);self::$stack[] = $widget;return $widget;}
/*** Ends a widget.* Note that the rendering result of the widget is directly echoed out.* @return static the widget instance that is ended.* @throws InvalidCallException if [[begin()]] and [[end()]] calls are not properly nested* @see begin()*/public static function end(){if (!empty(self::$stack)) {$widget = array_pop(self::$stack);if (get_class($widget) === get_called_class()) {/* @var $widget Widget */if ($widget->beforeRun()) {$result = $widget->run();$result = $widget->afterRun($result);echo $result;}return $widget;}throw new InvalidCallException('Expecting end() of ' . get_class($widget) . ', found ' . get_called_class());}throw new InvalidCallException('Unexpected ' . get_called_class() . '::end() call. A matching begin() is not found.');}
参考资料:
Widgets
源码文件
ob_implicit_flush
