Zend Framework 2 建立自己的 Module (3)

繼 前一篇文章  我們初步建立了 Module 與設定,接下來要介紹 Routing 與 Controllers

Routing and controllers

依照官方的文件,我們列出下列的表格,分別去描述 Page 名稱與敘述頁面 (Page) 所要做什麼事情

[table]

(Page)頁面名稱,(Description)描述

Home,顯示專輯列表並且有edit與delete做為可以編輯與刪除的動作

Add new album,提供一個表單(form)做為一個新增專輯

Edit album,提供一個表單(form)可以編輯專輯

Delete album,處理刪除(delete)專輯

[/table]

從上面得知,我們有四個頁面,那每個頁面有相對應的動作,我們把每個動作寫在同一個 Controller (控制器)中,在 Controller 類別中,建立四個方法分別去對應上面表格中的四個動作。

[table]

Page,Controller,Action

Home,AlbumController,index

Add new album,AlbumController,add

Edit album,AlbumController,edit

Delete album,AlbumController,delete

[/table]

編輯 /path/to/project-name/module/Album/config/module.config.php

從 code 得知,我們加入了一個 Controller 名字叫做:AlbumController 與一段 code 做為:router 路由網址,而下列的表格為路由網址:

[table]

URL,Page,Action

/album,Home (list of albums),index

/album/add,Add new album,add

/album/edit/2,Edit album with an id of 2,edit

/album/delete/4,Delete album with an id of 4,delete

[/table]

Create the controller

一般來說 Controller 的命名為:{Controller name}Controller

/path/to/project-name/module/Album/src/Album/Controller

網址對應的動作為:

[table]

URL,Method called

http://zf2-tutorial.localhost/album,Album\Controller\AlbumController::indexAction
http://zf2-tutorial.localhost/album/add,Album\Controller\AlbumController::addAction
http://zf2-tutorial.localhost/album/edit,Album\Controller\AlbumController::editAction
http://zf2-tutorial.localhost/album/delete,Album\Controller\AlbumController::deleteAction

[/table]

Initialise the view scripts 初始化視圖(樣版)腳本

  • /path/to/project-name/module/Album/view/album/album/index.phtml
  • /path/to/project-name/module/Album/view/album/album/add.phtml
  • /path/to/project-name/module/Album/view/album/album/edit.phtml
  • /path/to/project-name/module/Album/view/album/album/delete.phtml

修改 /path/to/project-name/module/Album/config/module.config.php

下一篇則會介紹:建置資料庫與模型 (Model) 的關係