douqiang6448 2012-08-22 15:54
浏览 42
已采纳

Zend框架数据访问层(DAL)

Looking through several tutorials and books regarding data access in Zend Framework, it seems as if most people do data access within their models (Active Record Pattern) or even controllers. I strongly disagree with that. Therefore I want to have a Data Access Layer (DAL) so that my domain layer remains portable by not having any "ZF stuff" in it. I have searched around but have not really found exactly what I wanted. Heads up: I am new to ZF.

DAL structure

So, the first problem is where to place the Data Access Layer. While it could certainly be placed within the library folder and adding a namespace to the autoloader, that does not seem logical as it is specific to my application (so the applications folder is suitable). I am using a modular structure. I am thinking of using the below structure:

/application/modules/default/dal/

However, I am not sure how include this folder so that I can access the classes within the controllers (without using includes/requires). If anyone knows how to accomplish this, that would be super! Any other ideas are of course also welcome.

The idea is to have my controllers interact with the Data Access Objects (DAO). Then the DAOs use models that can then be returned to the controllers. By doing this, I can leave my models intact.

Implementation

In other languages, I have previously implemented DAOs per model, e.g. DAL_User. This resulted in an awful lot of DAO classes. Is there a smarter way to do this (using a single class does not seem easy with foreign keys)?

I would also appreciate suggestions on how to implement my DAO classes in ZF. I have not spent an awful lot of time reading about all of the components available for database interaction, so any ideas are very welcome. I suspect that there is something smarter than standard PDO available (which probably uses PDO internally, though). Name drops would be sufficient.

Sorry for the many questions. I just need a push in the right direction.

  • 写回答

2条回答 默认 最新

  • duanluan8390 2012-08-23 06:40
    关注

    Well, the first thing you have to take into account when dealing with the Data Access Layer, is that this layer also have sub-layers, it's unusual to find folders called "dal" in modern frameworks (I'm taking as basis both Zend Framework and Symfony).

    Second, about ActiveRecord, you must be aware that by default Zend Frameworks doesn't implement it. Most of the tutorials take the easiest path to teach new concepts. With simple examples, the amount of business logic is minimal, so instead of adding another layer of complexity (mapping between database and model's objects) they compose the domain layer (model) with two basic patterns: Table Data Gateway and Row Data Gateway. Which is enough information for a beginner to start.

    After analyzing it, you will see some similarity between ActiveRecord and Row Data Gateway patterns. The main difference is that ActiveRecord objects (persistable entities) carries business logic and Row Data Gateway only represents a row in the database. If you add business logic on a object representing a database row, then it will become an ActiveRecord object.

    Additionally, following the Zend Framework Quick Start, on the domain model section, you will realize that there's a third component, which uses the Data Mapper Pattern.

    So, if the main purpose of your DAL is to map data between business objects (model) and your storage, the responsibility of this task is delegated to the Data Mappers as follows:

    class Application_Model_GuestbookMapper
    {
    
        public function save(Application_Model_Guestbook $guestbook);
    
        public function find($id);
    
        public function fetchAll();
    
    }
    

    Those methods will interact with the Database Abstraction Layer and populate the domain objects with the data. Something along this lines:

    public function find($id, Application_Model_Guestbook $guestbook)
    {
    
        $result = $this->getDbTable()->find($id);
    
        if (0 == count($result)) {
    
            return;
    
        }
    
        $row = $result->current();
    
        $guestbook->setId($row->id)
    
                  ->setEmail($row->email)
    
                  ->setComment($row->comment)
    
                  ->setCreated($row->created);
    
    }
    

    As you can see, the Data Mappers interacts with a Zend_Db_Table instance, which uses the Table Data Gateway Pattern. On the other hand, the $this->getDbTable->find() returns instances of the Zend_Db_Table_Row, which implements the Row Data Gateway Pattern (it's an object representing a database row).

    Tip: The domain object itself, the guestbook entity, was not created by the find() method on the DataMapper, instead, the idea is that object creation is a task of factories and you must inject the dependency in order to achieve the so called Dependency Inversion Principle (DIP) (part of the SOLID principles). But that's another subject, out of the scope of the question. I suggest you to access the following link http://youtu.be/RlfLCWKxHJ0

    The mapping stuff begins here:

    $guestbook->setId($row->id)
              ->setEmail($row->email)
              ->setComment($row->comment)
              ->setCreated($row->created);
    

    So far, I think I have answered your main question, your structure will be as following:

    application/models/DbTable/Guestbook.php
    application/models/Guestbook.php
    application/models/GuestbookMapper.php
    

    So, as in the ZF Quick Start:

    class GuestbookController extends Zend_Controller_Action
    {
    
        public function indexAction()
    
        {
            $guestbook = new Application_Model_GuestbookMapper();
    
            $this->view->entries = $guestbook->fetchAll();
    
        }
    
    }
    

    Maybe you want to have a separated folder for the data mappers. Just change:

    application/models/GuestbookMapper.php
    

    to

    application/models/DataMapper/GuestbookMapper.php
    

    The class name will be

    class Application_Model_DataMapper_GuestbookMapper
    

    I've seen that you want to separate your domain model objects into modules. It's possible too, all you need is to follow the ZF's directory and namespace guidelines for modules.

    Final tip: I've spent a lot of time coding my own data mappers for finally realize that it's nightmare to maintain the object mapping when your application grows with a lot of correlated entities. (i.e Account objects that contain references to users objects, users that contain roles, and so on) It's not so easy to write the mapping stuff at this point. So I strongly recommend you, if you really want a true object-relational mapper, to first study how legacy frameworks perform such tasks and perhaps use it. So, take some spare time with Doctrine 2, which is the one of the best so far (IMO) using the DataMapper pattern.

    That's it. You still can use your /dal directory for storing the DataMappers, just register the namespace, so that the auto loader can find it.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看