Handling items in the collection pattern by a data mapper

后端 未结 1 543
时光说笑
时光说笑 2021-01-14 04:25

My question is related to the update section of @tereško\'s answer in \"Who should handle the conditions in complex queries, the data mapper or the service layer?\" Below is

相关标签:
1条回答
  • 2021-01-14 05:20

    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.

    0 讨论(0)
提交回复
热议问题