Small conception of a rendering engine using DTOs and viewfiles

The purpose is to get rid of associative arrays in the rendering engine.

Viewfile example:

<div>
<?php foreach ($buttons as $button): ?>
    <?= render($button); ?>
<?php endforeach; ?>
</div>

View object example:

class ButtonGroup extends BaseRenderable
{
    /** @var Button[] */
    protected $buttons = [];

    /** @var string Optional, defaults to classname */
    protected $viewfile = 'views/buttongroup';
}

Usage example:

$buttonGroup = new ButtonGroup(['buttons' => [$button1, $button2]]);
$renderer = new Renderer();
$renderer->filetype = 'php';
echo $renderer->render($buttonGroup);

That doesn’t contradict current state of things. You can transfer your data in DTOs when passing it to render(). One thing is that storing a view file path in DTO doesn’t look right to me since it is mixing two concerns: data and presentation.

That doesn’t contradict current state of things.

Well, to be possible is not the same thing as being encouraged or enforced. My concept enforces a one-to-one relation between view and object. This is again the discussion of how opinionated a framework should be. I have no good answer. :slight_smile: But overall I’d say that bigger size, longer time, bigger team --> more opinions needed.

You can transfer your data in DTOs when passing it to render()

Yes, true. I’m doing this already with widgets (Yii 1.1). But my implementation above includes a couple of shortcuts, like the render function, and unpacking the object properties directly into the view (although hackish).

One thing is that storing a view file path in DTO doesn’t look right to me since it is mixing two concerns: data and presentation.

Some people complained about too much magic, the class name automatically being the name of the viewfile. I guess the mapping between DTO and viewfile could be put in a separate class injected to the render object, like

$viewfileMappings->addMapping($dto, $viewfileName);
$renderer->addMappings($viewfileMappings);

So that depends on the situation. Every team expands on the framework constraints adding their own. That could be in the team rules book.

About your solution, I don’t see what problem it may solve in my projects so it is not useful for me. But, I know that projects vary and some flavor of projects may have problems to be solved by this solution. That’s the reason for not being too enthusiastic to include it into the framework.

So that depends on the situation. Every team expands on the framework constraints adding their own. That could be in the team rules book.

Yes, good point.

I don’t see what problem it may solve in my projects so it is not useful for me

The problem to solve is the “use associative arrays everywhere”-anti-pattern. Like CMenu in Yii 1. :wink:

That’s the reason for not being too enthusiastic to include it into the framework.

Nah, I wouldn’t include it in any framework. More like a basis for discussion. :slight_smile: