yiisoft / view

Yii view rendering library
https://www.yiiframework.com/
BSD 3-Clause "New" or "Revised" License
56 stars 44 forks source link

Add simple view context class `ViewContext` and methods `View::withContextPath()` and `WebView::withContextPath()` #193

Closed vjik closed 2 years ago

vjik commented 2 years ago
Q A
Is bugfix?
New feature? ✔️
Breaks BC?
Fixed issues -

For example, this class convient use in widgets:

final class SidebarMenu extends Widget
{
    public function __construct(
        private View $view
    ) {
        $this->view = $this->view->withContext(new ViewContext(__DIR__));
    }

    protected function run(): string
    {
        return $this->view->render('menu');
    }
}

or so:

final class SidebarMenu extends Widget
{
    public function __construct(
        private View $view
    ) {
        $this->view = $this->view->withContextPath(__DIR__);
    }

    protected function run(): string
    {
        return $this->view->render('menu');
    }
}

This is better, than:

final class SidebarMenu extends Widget implements ViewContextInterface
{
    public function __construct(
        private View $view
    ) {
        $this->view = $this->view->withContext($this);
    }

    protected function run(): string
    {
        return $this->view->render('menu');
    }

    public function getViewPath(): string
    {
        return __DIR__;
    }
}