I'm facing a development choice.
I am developing a book system in PHP. A book has a title and a owner.
In my database, I have a table tblUser with keys: user_id and user_name and a table tblBook with keys book_id, book_title and user_id (which is a Foreign key).
I have two table abstractions: UserModel and BookModel.
models/user.php
<?php
class UserModel {
public $user_id;
public $user_name;
private $_table = 'tblUser';
public function getUser($user_id) {
$database = Database::getInstance();
$sql = "SELECT user_id, user_name FROM {$this->_table} WHERE user_id=:user_id";
$stmt = $database->getConnection()->prepare($sql);
$stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
$stmt->execute();
$data = $stmt->fetch();
return $data;
}
?>
models/book.php
<?php
class BookModel {
public $book_id;
public $book_title;
public $user_id;
private $_table = 'tblBook';
public function getBook($book_id) {
$database = Database::getInstance();
$sql = "SELECT book_id, book_title, user_id FROM {$this->_table} WHERE book_id=:book_id";
$stmt = $database->getConnection()->prepare($sql);
$stmt->bindParam(':book_id', $book_id, PDO::PARAM_INT);
$stmt->execute();
$data = $stmt->fetch();
return $data;
}
public function getOwnername1() {
$database = Database::getInstance();
$sql = "SELECT user_name FROM tblUser WHERE user_id=:user_id";
$stmt = $database->getConnection()->prepare($sql);
$stmt->bindParam(':user_id', $this->user_id, PDO::PARAM_INT);
$stmt->execute();
$data = $stmt->fetch();
return $data['user_name'];
}
public function getOwnername2() {
$user = new UserModel();
$user->getUser($this->user_id);
return $user->user_name;
}
public function getBooks() {
...
}
?>
Actually, from a view ViewBook, I want to list my books and their owner.
<?php
$bookmodel = new BookModel();
$books = $bookmodel->getBooks();
?>
<table>
<thead>
<tr>
<th>Title</th><th>Owner name</th>
</tr>
</thead>
<tbody>
<?php foreach ($books as $book): ?>
<tr>
<td><?php echo $book->book_title; ?></td><td><?php echo $book->getOwnername1(); ?></td>
</tr>
<?php endif; ?>
</tbody>
</table>
Nom my question what would be the best development choice to retrieve the owner name. In my example, I used a method getOwnername1(). I also created a method getOwnername2() which calls a method from another model. Is it clean to do it (in a MVC development)? so if it is clean maybe it is preferable to use getOwnername2()? I also thought to use a SQL join query in the BookModel::getBook($book_id) and add $user_name as attribute to the BookModel class. Maybe this is preferable? I'm trying to do the best choice to have a clean code and respectful with coding standards in MVC delopment.