Data Mapper pattern: where to put a checkLogin method for a User Model?

I'm trying to implement the data mapper pattern for a User Class.

If I understood correctly, the business class User shouldn't call any persistence methods, instead, it's dropped into the Data Mapper class (UserMapper) and the mapper interfaces with the database, ideally using a table gateway class.

I have some questions:

  • Where would I put a checkLogin method? User or UserMapper? I need to check the login status of current visitor by his cookie. Since User cant reference the database and session data is stored there I have to use the mapper class right?

  • Where do I put the validation rules? I wanted to put them in the User class so that when I instantiate it, I would get an exception if the data is wrong. However I would need validation rules on the mapper for methods like checkLogin() and others. Maybe I shouldn't instantiate new User() directly, instead, I should create a new user from the data mapper where the validation rules would also be stored. What do you think?

  • It seems that this way, I end up with a very small model class and a bigger data mapper class. But since most of my application is database interaction I suppose this isn't that bad. Is it a code smell or not?

  • Thanks.


    I think you are missing a component in application. Apart from User and UserDataMapper, you still need another layer that performs the business logic validation. Let's call this UserBusiness.

    The cookie/session check can be done in UserBusiness, after the details for the User are retrieved from the UserDataMapper. The UserDataMapper is going to return a User object that will have all the details like login, sessionId, etc. So UserBusiness can validate it using these details.

    You need validation in UserBusiness as well as User and UserDataMapper. The reason for this is that you are validating different things. The validation rules in UserBusiness will be more business specific, is the username confining to the app rules (greater than 8 characters can be a rule for instance). User can validate if a field is null when it is not supposed to be null. UserDataMapper can validate that the username is unique or some such data rule. You don't have necessarily limit validation rules to one class.

    A bloated data layer is not unusual but it is also not a good idea if it doesn't need to be bloated. The data layer should only handle validation, retrieval and processing related to the database. Doing anything more would be a smell in most cases.

    链接地址: http://www.djcxy.com/p/9622.html

    上一篇: 在Javascript中使用时区和夏令时

    下一篇: 数据映射器模式:在哪里放置用户模型的checkLogin方法?