Question on Entity class in Novice to Ninja 6th edition

@TomB In the Entity class you created in the book you coauthored with Kevin Yank , I discovered that when you created the Author class on page 555 of the book, instead of creating a function to get all authors, you created a function that retrieve jokes based on authors and in the joke entity class, you created a function that retrieves all authors based on their jokes and from it I could deduce from it that the entity class should be used to create an inverse class.

Now, supposing am creating a forum site and I have 2 classes, one called POST or THREAD class and the other called COMMENT class, does that mean now that to retrieve all comments of a post or thread, I have to do that in the POST/THREAD class and to retrieve a post for all comments, I have to do that in the COMMENT class?

The reason why I asked the question is because, I thought, each class should be concern with its own model i.e. a POST/THREAD class should just retrieve post alone and so also with the comment class.

If it should be inverse, like I deduce from your example in the book, how then are we going to code a class like the PROFILE class which will in itself contain other classes like the POST/THREAD class, the COMMENT class, the STATUS class, the VOTES class etc.

I hope you get my question and I eagerly await your answer.

Thanks

Hi jaquarpow.

A class represents a single object. Each instance of the Author class represents a single author. It would not make sense to have a getAuthors method inside the Author class because each $author instance represents a single author. You’d need an existing author instance to get the others. Each author has a list of related jokes so you can use:

//Fetch all the jokes by the author represented by $author
$jokes = $author->getJokes();

Using the code in the book it allows you to do this:

$authorsTable = new \Ninja\DatabaseTable($pdo, 'author', 'id', 'Ijdb\Entity\Author');

//Find all the records from the `author` table
$authors = $authorsTable->findAll();

//Loop over each one, each `$author` will be an instance of the `Author` class
foreach ($authors as $author) {
    //Print the name of the author, e.g. "Kevin" or "Tom", will change on each iteration
    echo $author->name;
    //Get the jokes  for this specific author, e.g. jokes by Tom or jokes by Kevin
     $authorsJokes = $author->getJokes();
    
    //loop over all the jokes by the current author
    foreach ($authorsJokes as $joke) { }
}

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.