【问题标题】:php structuring classes properly to provide the required functionalitiesphp 正确构造类以提供所需的功能
【发布时间】:2017-09-19 10:25:01
【问题描述】:

我有以下课程:

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;
    }
}

要求是实现这些功能

  1. 每个Author 代表一个文章列表
  2. 更改AuthorArticle

我首先想到要上课:

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

但这似乎是错误的,不是吗?因为每个Article 已经有Author,我有点困惑,感谢帮助。

提前致谢!

【问题讨论】:

    标签: php design-patterns


    【解决方案1】:

    更新作者很简单,只需在Article类中添加一个方法setAuthor(Author $author)即可:

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

    您实际上不需要 ArticleList 类中的作者信息。只需将 Article 对象提供给 addArticle 方法就足够了,因为您可以通过文章本身获取作者姓名。


    以下代码适用于所有作者,而不仅仅是一个!

    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;
        }
    }
    

    此方法将返回给定作者的所有文章(您可以提供作者姓名或 Author 类的实例作为参数),如果没有找到,则返回 null。

    【讨论】:

    • 首先,感谢您的回复,ArticleList 应该包含一个作者的文章,所以getArticleByAuthor 不会按建议的那样工作,您能提出一些建议吗?
    • 所以你为每个作者创建一个新列表?然后您可以使用您发布的 ArticleList 课程。只需将其分配给作者对象,例如,您就可以(在 $author->articles 中)。如果您更改一篇文章的作者,它也会在列表中更新,因为passed (and assigned) by reference
    • 好 :) 感谢您的接受!如果您将解决方案发布在答案的底部以供更多搜索者使用,也不会受到伤害:)
    猜你喜欢
    • 1970-01-01
    • 2023-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多