douba9425 2017-09-19 10:25 采纳率: 100%
浏览 26
已采纳

php正确构造类以提供所需的功能

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!

  • 写回答

1条回答 默认 最新

  • douyan1944 2017-09-19 10:50
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题