【发布时间】:2023-03-25 09:52:01
【问题描述】:
我创建了一个名为 CMS 的 Zend Framework 2 小模块,用于在我的站点中编写简单的文章。下面的这个模块使用 Zend Db 和 TableGateway 类来从数据库中获取数据。
我已经阅读了很多关于创建模块策略的网站和书籍,我更喜欢使用这些文件结构的简短快速的方法:
.
├── Module.php
├── config
│ └── module.config.php
├── data
│ └── data.sql
├── src
│ └── Cms
│ ├── Controller
│ │ ├── IndexController.php
│ │ ├── PageAdminController.php
│ │ └── PageCategoryAdminController.php
│ ├── Form
│ │ ├── Element
│ │ │ ├── PageCategories.php
│ │ │ └── ParentPages.php
│ │ ├── PageCategoryFilter.php
│ │ ├── PageCategoryForm.php
│ │ ├── PageFilter.php
│ │ └── PageForm.php
│ ├── Hydrator
│ │ └── Strategy
│ │ └── DateTimeStrategy.php
│ ├── Model
│ │ ├── Page.php
│ │ ├── PageCategory.php
│ │ ├── PageCategoryTable.php
│ │ ├── PageTable.php
│ │ └── UrlRewrites.php
│ └── View
│ └── Helper
│ ├── Extract.php
│ └── Tags.php
└── view
└── cms
├── index
│ ├── index.phtml
│ ├── notfound.phtml
│ └── page.phtml
├── page-admin
│ ├── edit.phtml
│ └── index.phtml
├── page-category-admin
│ ├── edit.phtml
│ └── index.phtml
└── partial
└── tags.phtml
TableGateway 方法
这个文件结构允许我在module.php中声明Page和PageTable类,并调用ServiceLocator以这种方式从数据库中读取和写入记录:
$pageTable = $this->getServiceLocator()->get('PageTable');
在这种情况下,我可以使用这个类在 PageTable 类中编写 CRUD 方法。
注入服务方法
然后我看到有一种服务方式可以执行相同的操作,其中 CRUD 操作位于调用 TableGateway 类的 Service 类 中 并通过 Factory 类 将 Service 注入到 Controller 的 __construct 方法中。
服务 > TableGateway > 工厂 > 控制器
为什么我要选择Service策略而不是简单的TableGateway?
【问题讨论】:
标签: php design-patterns zend-framework2