[关闭]
@Chiang 2020-08-23T18:52:14.000000Z 字数 2043 阅读 565

yii2 Widgets 下的widget() begin() end() 方法

2020-08 Yii2.0


widget()

  1. /**
  2. * Creates a widget instance and runs it.
  3. * The widget rendering result is returned by this method.
  4. * @param array $config name-value pairs that will be used to initialize the object properties
  5. * @return string the rendering result of the widget.
  6. * @throws \Exception
  7. */
  8. public static function widget($config = [])
  9. {
  10. ob_start();
  11. ob_implicit_flush(false);
  12. try {
  13. /* @var $widget Widget */
  14. $config['class'] = get_called_class();
  15. $widget = Yii::createObject($config);
  16. $out = '';
  17. if ($widget->beforeRun()) {
  18. $result = $widget->run();
  19. $out = $widget->afterRun($result);
  20. }
  21. } catch (\Exception $e) {
  22. // close the output buffer opened above if it has not been closed already
  23. if (ob_get_level() > 0) {
  24. ob_end_clean();
  25. }
  26. throw $e;
  27. }
  28. return ob_get_clean() . $out;
  29. }

begin()

  1. /**
  2. * Begins a widget.
  3. * This method creates an instance of the calling class. It will apply the configuration
  4. * to the created instance. A matching [[end()]] call should be called later.
  5. * As some widgets may use output buffering, the [[end()]] call should be made in the same view
  6. * to avoid breaking the nesting of output buffers.
  7. * @param array $config name-value pairs that will be used to initialize the object properties
  8. * @return static the newly created widget instance
  9. * @see end()
  10. */
  11. public static function begin($config = [])
  12. {
  13. $config['class'] = get_called_class();
  14. /* @var $widget Widget */
  15. $widget = Yii::createObject($config);
  16. self::$stack[] = $widget;
  17. return $widget;
  18. }

end()

  1. /**
  2. * Ends a widget.
  3. * Note that the rendering result of the widget is directly echoed out.
  4. * @return static the widget instance that is ended.
  5. * @throws InvalidCallException if [[begin()]] and [[end()]] calls are not properly nested
  6. * @see begin()
  7. */
  8. public static function end()
  9. {
  10. if (!empty(self::$stack)) {
  11. $widget = array_pop(self::$stack);
  12. if (get_class($widget) === get_called_class()) {
  13. /* @var $widget Widget */
  14. if ($widget->beforeRun()) {
  15. $result = $widget->run();
  16. $result = $widget->afterRun($result);
  17. echo $result;
  18. }
  19. return $widget;
  20. }
  21. throw new InvalidCallException('Expecting end() of ' . get_class($widget) . ', found ' . get_called_class());
  22. }
  23. throw new InvalidCallException('Unexpected ' . get_called_class() . '::end() call. A matching begin() is not found.');
  24. }

参考资料:
Widgets
源码文件
ob_implicit_flush

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注