Hey there Ignited fellows'!
As of my understanding each CodeIgniter model should essentially have one corresponding Entity if any.
And in your model you should define it in:
PHP Code:
$this->returnType = 'App\Entity\Book';
Further more each database table should have its corresponding Model
in which you describe that it is connected to that table and fill it up with necessary logic / methods.
All above goes for the authors table, model and entity aswell.
Now when your books have authors then of course you might want to fetch the author data.
Say you have fetched a book by it's id.
PHP Code:
$entity = $this->find(1);
In order to preserve books entity key correlation to its table keys we should not pollute books
entity with authors data, instead, we're going to make a method to retrieve our related author on demand:
PHP Code:
<?php
namespace App\Entity\Book;
# Author is a sub-entity of any book.
use App\Models;
class Book
{
# ...
public function getAuthor() : null|Models\Author
{
# Check if current entity has been loaded.
if ($this->author_id)
{
# Assuming you have a model Author with constructor
# that's taking in first argument as int|object to instantiate local entity.
return new Models\Author($this->author_id);
# Or if you go very CI native you could instead do it like this:
$author = new Models\Author();
$author->entity = $author->find($this->author_id);
# Either way we're returning current entity's submodule.
return $author;
}
# Nothing found.
return null;
}
# ...
}
In reality when you are fetching ~10,000 books which in total maybe have 700 authors then
it is very bad practice to instantiate entirely new model for each and every author.
This is something I have talked about before on this forum. What I have done to avoid
it on my end (in my projects) is a global helper
similar to service() but instead of sharing the
very same instance globally trough out the project I create a table in memory which is keyed
by given arguments and when same class with same construction arguments is requested
it will actually return a reference to already created class within memory. But that's another story.
Now say in the book model you would like to access its authors data? You do it like this:
PHP Code:
$author_entity = $entity->getAuthor()->entity;
And the benefit of having Entities to children entire models is access to their methods:
PHP Code:
# I'm currently programming Books model and here's the logic where
# I would like to remove the author of this book for ever.
$entity->getAuthor()->delete();