Trang chủ > PHP, Thiết kế Web, Zend framework > zend rewrite router với class Zend_Controller_Router_Route_Regex

zend rewrite router với class Zend_Controller_Router_Route_Regex

Zend framework cho phép Developer customize lại URL hay cọn gọi là rewrite rout. Ở đây nhantam tôi giới thiệu giải pháp rewrite URL sử dụng class Zend_Controller_Router_Route_Regex.

Ví dụ:
Để tạo một url: http://www.myweb.com/san-pham-123-ten-san-pham.html

Bước 1:
Tạo một file routers.ini và lưu tại thư mục /application/configs/routers.ini
Nội dung file routers.ini như  sau:

[sanpham]
routes.product.type = “Zend_Controller_Router_Route_Regex”
routes.product.route = “san-pham-(\d+)-(.*).html”
routes.product.defaults.module = “default”
routes.product.defaults.controller = “product”
routes.product.defaults.action = “index”
routes.product.map.1 = “id”
routes.product.map.2 = “title”

Chú thích cho đoạn code router trên các bạn xem thêm tại trang chủ document của zend


Bước 2
:

bắt và thực thi router trên ở file /application/Bootstrap.php

protected function _initFrontController()
{

$config = new Zend_Config_Ini(APPLICATION_PATH.’/configs/routers.ini‘,  ’sanpham‘);
$router = new Zend_Controller_Router_Rewrite();
$router = $router->addConfig($config,  ’routes’);
$front->setRouter($router);
return $front;

}

Bước 3:

Tạo controllers product /application/default/controllers/Product.php

chú ý: default là tên module do các bạn quy định

class ProductController extends Zend_Controller_Action
{

function indexAction()
{
$id = $this->_getParam(‘id’);  //output = 123
$title = $this->_getParam(‘title’); //output = ten-san-pham

//truy van CSDL để lấy ra sản phẩm có $id = 123

}

}

Chú ý:
- Có thể làm bước nào trước tùy ý
- Nếu ứng dụng không phải multi modules thì các bạn lưu ý đường dẫn default tại bước 3.

Chúc các bạn thành công.

nhantam
PHP Developer

About these ads
  1. Chưa có phản hồi.
  1. No trackbacks yet.

Gửi phản hồi

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Thay đổi )

Twitter picture

You are commenting using your Twitter account. Log Out / Thay đổi )

Facebook photo

You are commenting using your Facebook account. Log Out / Thay đổi )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: