Event before/after Widget render (use case for widget-level output caching behavior)

I have a lot of fragment cache for widgets in the view level.




if ($this->beginCache($id)){

    echo app\MyWidget::widget([]);

    $this->endCache();

}

I’m wondering if we can have beforeRender and afterRender widget, so that the output caching can be done in the Widget level instead of View level.

Something similar like PageCache but for widget level.

I know I can always use something like this


class BookList extends Widget {

     public $authorId;

     public function run(){

        if ($this->getView()->beginCache($authorId)){

            $this->getView()->endCache();

        }

     }

}

But I think something like this is much more convenient


class MyWidget extends Widget {

    public function behaviors(){

         return [

            ['class' => WidgetOutputCache::class]

         ]

    }

}

This way if I want to change a cache strategy, I can just replace the WidgetCache to something other instead of updating all lines before the $this->getView()->beginCache(). Or I can easily change the cache object (memcached, filecache, etc).

The only use case I can find is only widget-level output caching, but I’m sure this can be convenient for a lot of stuffs.

why make things harder? widget is finished portion of data

I don’t understand. What do you mean by that?