Answer the question
In order to leave comments, you need to log in
Calling methods from view is shit code?
Hello.
There is a certain object, users are attached to this object, let's say this object is a task, and users are performers.
In view, in addition to the content of the task itself, it is necessary to display all users who are attached to this task.
Calling a function from a view is normal, or is it necessary to prepare an array of users in advance and simply loop it into the view?
<?php foreach ($model->relUsers as $t) : ?>
<span><?= User::getById($t,'name') ?></span>
<?php endforeach; ?>
Answer the question
In order to leave comments, you need to log in
Functions are different.
Key concepts:
1. Idempotency.
1. Pure function.
1. Side effects.
1. Determinacy
So, in view, ideally, only pure functions should be called or, at worst, functions without side effects.
In your request to the database, this is a side effect, it is better to do this in the controller, and pass data to the view.
But in fact, your code is also an anti-pattern, the so-called `select N + 1` problem. Loop requests are evil. You are not using the database or the capabilities of your ORM (if that is the one).
The error is that $model->relUsers
it must be a relationship that returns an array of models. And then everything will be fine:
<?php foreach ($model->relUsers as $t) : ?>
<span><?= $t->username ?></span>
<?php endforeach; ?>
Normally, if necessary, for example, the same twig allows the addition of user-defined functions.
In your example, I would just prepare the desired array and output it
It will be correct to make a relay, something like $task->executors.
Surely you are using an intermediate table (I understand that relUsers is it). In this case, the relay must be done using the via method.
And I would not do relaying for intermediate tables (relUsers), since this is a purely technical necessity for linking these two entities in relational databases.
Sets of elements are prepared in the controller and passed to the view, where they are only iterated.
<?php foreach ($model->relUsers as $t) : ?>
<span><?= User::getById($t,'name') ?></span>
<?php endforeach; ?>
View - that's why it's called view (display), which should only display.
You need to receive data in the controller.
The maximum amount that is possible in the view - conditions, such as if the array with data is empty, display an error, otherwise the data
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question