V
V
Vlad2021-03-29 13:59:43
PHP
Vlad, 2021-03-29 13:59:43

MVC | Where to get the name of the category, users?

I'm making a mvc oop blog, and I ran into a question
. There is a post that displays a cateria and an author. The database contains category_id and author_id The
question is how to properly organize the receipt of the name of the category and author, having their id?
Initially, there was an idea to pass the model object (category, user) to the view, and already there to execute the necessary methods (getCategoryName or getUserName). But then I learned that this is a bad practice, and it is necessary to pretend to be as simple as possible, submitting ready-made data there.
Now I have come to this decision.
In the controller for each post, add the following elements:

$postList = Post::getPostList(); // модель возвращает список постов
foreach($postList as $post) {
    $post['category_name'] = Category::getCategoryName($post['category_id']);
    $post['author_name'] = User::getCategoryName($post['author_id']);
}
$view->render($postList); // передаю посты в вид

Is it possible to do so?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2021-03-29
@Vlad200293

For starters, if you want to use OOP, stop using associative arrays.
The mapper / ar / request takes the data from the database from you, respectively, and it must take care of the rest of the data.
Example (pseudocode):

Option 1

$postList = Post::getPostList([
    'join' => [
        'category',
        'author',
    ],
]);
foreach($postList as $post) {
    // то есть маппер у вас уже эти данные получил и перед отдачей объектов инициализировал их
    $post->getCategoryName();
    $post->getAuthorName();
}
$view->render($postList);

Or like this:
Option 2

$postList = Post::getPostList();

$postIds = array_column($postList, 'id');
$categoryNames = Category::getNamesWherePostId($postIds);
$authorNames = User::getNamesWherePostId($postIds);

foreach($postList as $post) {
    $post['category_name'] = $categoryNames[$post->categoryId] ?? null;
    $post['author_name'] = $authorNames[$post->authorId] ?? null;
}
$view->render($postList);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question