2009年1月30日星期五

Re: [fw-mvc] Separating Models from DB Access

I would recommend using a DAO (Data Access Object)...
More or less you create an interface 

interface IUserDAO {
   public load($id);
   public save(User $user);
}

the load method should return a Transfer Object which in PHP land usually just means an associative array but could also be a Zend_Db_Row, and your User entity object should consume that array to load itself. 

normally you would use a factory or DI container for this, but in your controller you would do:
 $dao = ZendDbTableUserDAO($user_table);

$user = new User($dao->load(1));

The issue is not about not letting your controller access the data...its about separating the data access from the model. The model should only know about its own business logic, and know nothing about persistence (loading and saving itself). This is part of the Single Responsibility Principal, I think.

The DAO hides and abstracts away the data access from the model and your controller. You controller is only talking to an interface, and that interface could make straight sql queries, call database abstraction tool like Zend_DB, call a Zend_DB_Table, load an XML file, talk to a webservice, or whatever you want.

When you're done, you can either pass the model itself back into DAO or a Transfer Object back and that will handle saving it to the database

Hope this helps!



On Fri, Jan 30, 2009 at 6:04 AM, Jack Sleight <jack.sleight@gmail.com> wrote:
Hi,
I'm currently building a new ZF based app, and on the advice of many articles I've read, and my own opinion, want to separate the "model" classes from the DB access classes. My problem is, for all the articles advising this is the way to do it, I've yet to find an example implementation or any advice on how to implement it in the real world with ZF.

As far as I understand it, the DB layer should be hidden under the model layer, so at no point should the controller be accessing the Table or Row classes.
For example, say I have these classes:

User - This is the user object

User_Table extends Zend_Db_Table
User_Table_Row extends Zend_Db_Table_Row

So, say we're in a controller and have some data for a new user, creating that user would be a case of:

$user = new User($properties);

But what about looking up an existing user? Which of these is right?:

$user = new User($id);

$user = User::find($id);

$users = new Users();
$user = $users->find($id);

And getting a collection of multiple users? I want an array of User objects returned, not User_Table_Row objects, where should these come from and how should they be created internally by the model.

Sorry for all the questions, I just really want to do this the best way,
Thanks,
--
Jack


没有评论: