0

I have following classes:

class Author {
    public $id;
    public $name;
}

class Article {
    protected $author; // Author
    protected $title;  // String
    public function __construct(Author $author, string $title)
        $this->author = $author;
        $this->title = $title;
    }
}

The requirement is to implement these functionalities

  1. Each Author represents a list of articles
  2. Changing the Author of an Article

I first thought of having a class:

class ArticleList {
    public $author; // Author
    private $articles = [];
    public function addArticle(Article $article) {
        $this->articles[] = $article;
    }
}

But this seems to be wrong, isn't?, because each Article already have Author, a bit confusing to me, help is appreciated.

Thanks in advance!

AamirR
  • 11,672
  • 4
  • 59
  • 73

1 Answers1

1

Updating an author is simple, just add a method setAuthor(Author $author) to the Article class:

public function setAuthor(Author $author) {
    $this->author = $author;
}

You actually dont need the author information inside your ArticleList class. Its enough to give only the Article object to the addArticle method, since you can get the author name by the article itself.


This following code is for all authors not just a single one!

class ArticleList {
    public $author;
    private $articles = [];
    public function addArticle(Article $article) {
        $this->articles[$article->author->name] = $article;
    }

    public function getArticleByAuthor($author) {
        if ($author instanceof Author) {
            $author = $author->name;
        }

        return (isset($this->articles[$author])) ?
            $this->articles[$author] : null;
    }
}

This method will return all articles by the given Author (you can either give the authors name or an instance of the Author class as parameter) or null if none were found.

Manuel Mannhardt
  • 2,191
  • 1
  • 17
  • 23
  • Firstly, thanks for response, `ArticleList` should contain articles for one author, so `getArticleByAuthor` will not work as suggested, can you suggest something? – AamirR Sep 19 '17 at 10:54
  • So you create a new List for each author? Then you can take the ArticleList class which you posted. Just assign it to the author object and you be good (at $author->articles) for example. If you change the author on one article it will be update in the list as well, since [passed (and assigned) by reference](https://stackoverflow.com/questions/2715026/are-php5-objects-passed-by-reference) – Manuel Mannhardt Sep 19 '17 at 10:58
  • Good :) And thanks for the accepting! Also it would not hurt if you post your solution at the bottom of your answer for further searchers :) – Manuel Mannhardt Sep 19 '17 at 14:15