2011年1月8日 星期六

Zend_Controller_Router_Route render page with url parameter by queried from db

Zend Framework裡的Zend_Controller_Router_Route裡有相當多的功能可以根據url參數render某個module, controller及action. 倘若今日希望url後的第一個參數到DB取得資料再決定導入哪個
module, controller及action,作法如下:

application.ini:

resources.db.adapter = "PDO_MySQL"
resources.db.params.host = your db server ip
resources.db.params.username = your db server account
resources.db.params.password = your db server password
resources.db.params.dbname = db name

Bootstrap.php:

$front = Zend_Controller_Front::getInstance();

$router = $front->getRouter();
$name = substr($_SERVER['REQUEST_URI'], 1);    #note 1
$number = strpos($name, '/');
if($number !== false){
  $name = substr($name, 0, $number)
}

$application = new Zend_Application(APPLICATION_ENV, APPLICATION_PATH . '/configs/application.ini');
$app = $application->getOptions();
$db = new Zend_Db_Adapter_Mysqli(
      array(
            'host'     =>    $app['resources']['db']['params']['host'],
            'username' =>    $app['resources']['db']['params']['username'],
            'password' =>    $app['resources']['db']['params']['password'],
            'dbname'   =>    $app['resources']['db']['params']['dbname']
      )

);


$sql = 'select {fields} from {table} where {field} = ?';
$stmt = new Zend_Db_Statement_Mysqli($db, $sql);
$stmt->;execute(array($name));
$row = $stmt->fetch();


$route = new Zend_Controller_Router_Route(
         ':param/*',     #note 2
         array(
              'module'     => {module you want to redirect},
              'controller' => {controller you want to redirect},
              'action'     => {action you want to redirect},
              {variable}   => {variable value}
              )
         );

$router->addRoute('number', $route);

note 1:
 $_SERVER['REQUEST_URI']會取得hostname以後之參數, e.g. http://www.blogger.com/post-edit.g?blogID=!@#?% 會回傳 '/post-edit.g?blogID=!@#?%'
若有在該參數後再加上其它參數的需求,所以才會用strpos檢查url是否有多個參數, e.g. http://www.blogger.com/pattern/type/1,所以在note 2處需要該設定方式


note 2:
':param/*'  :param即為所需決定render哪一個頁面的參數,而之後的*字號則可輸入可不輸入, e.g. /pattern, /pattern/, /pattern/type/1都會render到同一個module, controller, action內。若需要在該action內取得此param值, 使用$this->getRequest()->getParam('param');即可。

沒有留言:

張貼留言