CodeIgniter routes.php use db database

如果想在ci的routes.php使用db的資料來控制 那這是一個方法 當然我覺得應該有更好的處理方式 像是 ci的hooks 不過經過簡單的研究後 還是覺得這方式最直觀(難度較低)

Database Table
Add the table `app_routes` to your MySQL database:

CREATE TABLE IF NOT EXISTS `app_routes` (
  `id` bigint(20) NOT NULL auto_increment,
  `slug` varchar(192) collate utf8_unicode_ci NOT NULL,
  `controller` varchar(64) collate utf8_unicode_ci NOT NULL,
  PRIMARY KEY  (`id`),
  KEY `slug` (`slug`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1;

PHP Code
Replace the code in application/config/routes.php with the one below:

$route[ 'default_controller' ]  = 'main';
$route[ '404_override' ]        = 'error404';
 
require_once( BASEPATH .'database/DB.php');
$db =& DB();
$query = $db->get( 'app_routes' );
$result = $query->result();
foreach( $result as $row )
{
    $route[ $row->slug ]                 = $row->controller;
    $route[ $row->slug.'/:any' ]         = $row->controller;
    $route[ $row->controller ]           = 'error404';
    $route[ $row->controller.'/:any' ]   = 'error404';
}

CodeIgniter is simple yet elegant, open source PHP framework developed by EllisLab. They also built the well-known ExpressionEngine by using CodeIgniter as a base. So that…

內容出處: Database-driven Routing in CodeIgniter — Osvaldas Valutis

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *