Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filters in DDD Repository

There is Campaign Entity and for that, I have CampaignRepository which have this functions

  1. public IList FindAll();
  2. public Campaign FindByCampaignNumber(string number);

But now i want this criterias -:

  1. Find campaigns that are created today.
  2. Find campaigns that are created in this month
  3. Find top 5 latest campaigns.
  4. Find campaigns that are created in this year.

So for all these campaigns filters,

Do i create separate function for each of them in repository ?

and implement like this way.

Getall campaigns and then filter required campaigns, but i do not want all campaigns. While searching in google i find this solution's

1: http://russelleast.wordpress.com/2008/09/20/implementing-the-repository-and-finder-patterns/

Is there any method i can avoid multiple functions or do i go ahead and create seperate functions for each of this filter ?

like image 879
kamal Avatar asked Feb 03 '23 15:02

kamal


1 Answers

Have you considered implementing Specification pattern in your application? Maybe it looks like an overkill, but it may prove useful if your app will have some complex user filter options.

class CampaignSpecification
{
    public CampaignSpecification Number(string number);
    public CampaignSpecification DateBetween(DateTime from, date to);
    public CampaignSpecification Year(DateTime year);
} //I have omitted all the AND/OR stuff it can be easily implemented with any SQL like query language

Here is an example how loading from the repository may look like

var  campaignList = CampaignRepository.load(
            new CampaignSpec()
                .Number("2")
                .Year(DateTime.Now);

Also I'd like to add that it depends much on what kind of data access solution you are using, it makes implementing easier when you know what kind of API you will be using(Criteria API, SQL or whatever) so you can tweak your Specification interface to make its implementation simpler.

UPDATE: if you are implementing specifications in .NET using linq and nHibernate please check out http://linqspecs.codeplex.com/

like image 138
Boris Treukhov Avatar answered Feb 14 '23 12:02

Boris Treukhov