Skip to content

Instantly share code, notes, and snippets.

@samdark
Last active May 5, 2021 10:41
Show Gist options
  • Save samdark/17b63972691bd3a3721c0b11361de920 to your computer and use it in GitHub Desktop.
Save samdark/17b63972691bd3a3721c0b11361de920 to your computer and use it in GitHub Desktop.
Views as classes

Views as classes, proposal by @roxblnfk

Idea is to have view templates as classes, not as separate template files. It could be additional to commonly used pattern.

Benefits

  • A class can be a generator that may be helpful for HTTP chunked responses with huge pages.
  • Each view class can require its own dependencies.
    • No need to inject anything globally via config.
    • No need to have vardoc at the beginning of each file.
  • Each class can hold data and metadata.

Drawbacks

  • Syntax isn't good (need to verifiy that).
  • Business logic in such class-views isn't as obvious evil as in view templates. People may get confused.
  • Not sure how to deal with themes.
  • Not sure how to deal with view translations.

Possible implementation

Introduce TemplateInterface with default implementation that uses template files:

$template = (new Template('filename', [data => data]));
$view->render($template);

Then there will be a way to implement another template transparently.

@roxblnfk
Copy link

roxblnfk commented May 5, 2021

Addititional benefit:

  • better navigation to the rendering template

Possible implementation

$view->render(Template::class, ['data' => $data]);

// render() fuction:
// if ($template instanceof TemplateInterface) {
//     $injector->make($template)->invoke('render', ...)
// } else {
//     // classic view
// }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment