Handling items in the collection pattern by a data mapper

青春壹個敷衍的年華 提交于 2019-12-01 09:13:13

I wouldn't think to actually use a factory object to add the articles. You may see yourself using one to make the instance of Article (in the second example), though. What I went ahead and did was add an addArticles () method to the ArticleCollection instance. This way you can simply call the method on your instance of ArticleCollection from the mapper. ArticleCollectionMapper may look something like:

class ArticleCollectionMapper extends DataMapperAbstract
{
    public function fetch ( ArticleCollection $articles )
    {
        $prepare = $this->connection->prepare( "SELECT ..." );
        $prepare->execute();
        // filter conditions

        $articles->addArticles( $prepare->fetchAll() );
    }
}

You'd need to do some filtering by getting the conditions from the ArticleCollection instance, which is excluded from the snippet above. Then our domain object's addArticles() implementation would look similar following:

class ArticleCollection extends DomainObjectAbstract
{
    protected $collection = array();

    public function addArticles ( Array $articles )
    {
        foreach ( $articles as $article )
        {
            $articleCollectionItem = new Article;
            $articleCollectionItem->setParams( $article );
            // however you prefer filling your list with `Article` instances

            $this->collection[] = $articleCollectionItem;
        }
    }
}

You may also want to add an addArticle() method depending on your needs, and then just replacing what's within the foreach above with a call to addArticle(). Note that the above examples are extremely simplified and code will need to be adapted in order to meet your standards.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!