Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

in Zend, Why do We use DB Model class and Mapper class as two separate?

I am working on the zend project, I am referring on other zend project to create the new Zend Project.But I don't like to blindly follow that project without understanding. In the Zend Directory structure, In Model class there are mainly two type of classes I see, like as in

- models
   - DbTables
        - Blog.php  //Extends Zend_Db_Table_Abstract
   - Blog.php       // Contains methods like validate() and save()
   - BlogMapper.php // Also Contains methods like validate(Blog b) & save(Blog b)

Why this specific structure is followed? Is this is to separate Object class and Database model class?

Please explain.

like image 490
Rajan Rawal Avatar asked Feb 17 '12 14:02

Rajan Rawal


1 Answers

DataMapper is a design pattern from Patterns of Enterprise Application Architecture.

The Data Mapper is a layer of software that separates the in-memory objects from the database. Its responsibility is to transfer data between the two and also to isolate them from each other. With Data Mapper the in-memory objects needn't know even that there's a database present; they need no SQL interface code, and certainly no knowledge of the database schema.

How you store data in a relational database is usually different from how you would structure objects in memory. For instance, an object will have an array with other objects, while in a database, your table will have a foreign key to another table instead. Because of the object-relational impedance mismatch, you use a mediating layer between the domain object and the database. This way, you can evolve both without affecting the other.

Separating the Mapping responsibility in its own layer is also more closely following the Single Responsibility Principle. Your objects dont need to know about the DB logic and vice versa. This gives you greater flexibility when writing your code.

When you dont want to use a Domain Model, you usually dont need DataMapper. If your database tables are simple, you might be better off with a TableModule and TableDataGateway or even just ActiveRecord.

For various other patterns see my answer to

  • ORM/DAO/DataMapper/ActiveRecord/TableGateway differences? and
  • http://martinfowler.com/eaaCatalog/index.html
like image 117
Gordon Avatar answered Nov 10 '22 21:11

Gordon