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条)

报告相同问题?

悬赏问题

  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题
  • ¥20 yolov5自定义Prune报错,如何解决?