AamirR
AamirR

Reputation: 12218

php structuring classes properly to provide the required functionalities

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!

Upvotes: 0

Views: 29

Answers (1)

Manuel Mannhardt
Manuel Mannhardt

Reputation: 2201

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.

Upvotes: 1

Related Questions