CodeIgniter - 动态生成路由

时间:2011-04-28 23:33:34

标签: php codeigniter

我有一个带有动态导航菜单的网站。我将控制器(葡萄牙语)名称与英语翻译一起保存在数据库中。

我想知道是否可以在运行时影响'route'数组,因此它会创建这些路由并在加载页面时对其进行缓存。

我希望我很清楚,谢谢你的帮助

5 个答案:

答案 0 :(得分:3)

答案 1 :(得分:3)

请记住,routes文件只是一个包含数组的PHP文件,所以如果你想让你的“黑客”T恤,你可以轻松做一些有点脏的事。

让您的CMS /应用程序/ web-app / fridge-monitoring-system /具有在数据库中创建和存储记录的界面。然后,无论何时保存,都将此内容抛出到application / cache / routes.php中。

最后你只需要你的主要routes.php包含缓存版本,你就可以了。

答案 2 :(得分:2)

您需要以下内容。

这样的一个控制器会将你的路由保存到应用程序/缓存文件夹中名为“routes.php”的文件中:

public function save_routes()
        {

            // this simply returns all the pages from my database
            $routes = $this->Pages_model->get_all($this->siteid);

            // write out the PHP array to the file with help from the file helper
            if (!empty($routes)) {
                // for every page in the database, get the route using the recursive function - _get_route()
                foreach ($routes->result_array() as $route) {
                    $data[] = '$route["' . $this->_get_route($route['pageid']) . '"] = "' . "pages/index/{$route['pageid']}" . '";';
                }

                $output = "<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');\n";

                $output .= implode("\n", $data);

                $this->load->helper('file');
                write_file(APPPATH . "cache/routes.php", $output);
            }
        }

这是您需要的第二个功能。这个和前一个都将进入处理您的页面的应用程序控制器:

// Credit to http://acairns.co.uk for this simple function he shared with me
// this will return our route based on the 'url' field of the database
// it will also check for parent pages for hierarchical urls
        private function _get_route($id)
        {
            // get the page from the db using it's id
            $page = $this->Pages_model->get_page($id);

            // if this page has a parent, prefix it with the URL of the parent -- RECURSIVE
            if ($page["parentid"] != 0)
                $prefix = $this->_get_route($page["parentid"]) . "/" . $page['page_name'];
            else
                $prefix = $page['page_name'];

            return $prefix;
        }

在你的Pages_model中,你需要一些东西:

function get_page($pageid) {
        $this->db->select('*')
            ->from('pages')
            ->where('pageid', $pageid);

        $query = $this->db->get();

        $row = $query->row_array();
        $num = $query->num_rows();

        if ($num < 1)
        {
            return NULL;

        } else {
            return $row;
        }
    }

而且:

function get_all($siteid) {
        $this->db->select('*')
            ->from('pages')
            ->where('siteid', $siteid)
            ->order_by('rank');
        ;

        $query = $this->db->get();

        $row = $query->row_array();
        $num = $query->num_rows();

        if ($num < 1)
        {
            return NULL;

        } else {
            return $query;
        }
    }

每次创建页面时,您都需要执行此行,因此我建议在完成所有脏工作后将其放在控制器的末尾:

$this->save_routes();

所有这一切将使你成为一个甜蜜的路线文件,每当事情发生变化时都会不断更新。

答案 3 :(得分:2)

你可以这样做:

创建一个名为Routes

的表
--
-- Table structure for table `Routes`
--

CREATE TABLE IF NOT EXISTS `Routes` (
`idRoutes` int(11) NOT NULL AUTO_INCREMENT,
`Order` int(11) NOT NULL,
`Url` varchar(250) NOT NULL,
`Url_Variable` varchar(20) NOT NULL,
`Class` text NOT NULL,
`Method` text NOT NULL,
`Variable` text NOT NULL,
`Date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
   PRIMARY KEY (`idRoutes`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=67 ;

在config目录中创建一个名为pdo_db_connect.php的文件

将其置于内部并相应更改。

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

function pdo_connect(){

try{

    // Include database info
    include 'database.php';

if(!isset($db)){
    echo 'Database connection not available!';
        exit;
}   
        $dbdriver   = $db['default']['dbdriver'];//'mysql'; 
        $hostname   = $db['default']['hostname'];//'localhost';
        $database   = $db['default']['database'];//'config';
        $username   = $db['default']['username'];//'root';
        $password   = $db['default']['password'];//'password';

    //to connect
    $DB = new PDO($dbdriver.':host='.$hostname.'; dbname='.$database, $username, $password);
    return $DB;

}catch(PDOException $e) {
    echo 'Please contact Admin: '.$e->getMessage();
}

}

现在,您可以在路线文件中执行此操作:

<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
    // Include our PDO Connection
    include('application/config/pdo_db_connect.php');

    class dynamic_route{

        public $pdo_db = FALSE;

        public function __construct(){

        }
        private function query_routes(){
            try{

            $routes_query = $this->pdo_db->query('SELECT * FROM Routes ORDER BY `Order` ASC');

            if($routes_query){
                $return_data = array(); 
                foreach($routes_query as $row) {
                    $return_data[] = $row; 
                }
                return $return_data;

            }

            }catch(PDOException $e) {
                echo 'Please contact Admin: '.$e->getMessage();
            }

        }
        private function filter_route_data($data){

            $r_data = array();
            foreach($data as $row){
                $return_data = new stdClass;

                if(empty($row['Url_Variable']) ){
                    $return_data->url = $row['Url'];
                }else{
                    $return_data->url = $row['Url'].'/'.$row['Url_Variable'];
                }

                if(empty($row['Method']) && empty($row['Variable']) ){
                    $return_data->route = $row['Class'];

                }elseif(!empty($row['Method']) && empty($row['Variable']) ){
                    $return_data->route = $row['Class'].'/'.$row['Method'];
                }elseif(!empty($row['Method']) && !empty($row['Variable']) ){
                    $return_data->route = $row['Class'].'/'.$row['Method'].'/'.$row['Variable'];
                }

            $r_data[] = $return_data;
            }
            return $r_data;
        }
        public function get_routes(){
            $route_data = $this->query_routes();
            $return_data = $this->filter_route_data($route_data);
            return $return_data;
        }       

    }

    $dynamic_route = new dynamic_route;
    // Give dynamic route database connection
    $dynamic_route->pdo_db = pdo_connect();
    // Get the route data
    $route_data = $dynamic_route->get_routes();
    //Iterate over the routes
    foreach($route_data as $row){
        $route[$row->url] = $row->route;
    }

答案 4 :(得分:0)

不过于复杂的东西,它保持了网址友好:

在routes.php里面:

// Routes from the database
require_once (BASEPATH .'database/DB.php');
$db =& DB();

// slug will be something like
// 'this-is-a-post'
// 'this-is-another-post'
$sql = "SELECT id, slug FROM items";
$query = $db->query($sql);

$result = $query->result();
foreach( $result as $row )
{
    // first is if multiple pages
    $route["$row->slug/(:num)"] = "item/index/$row->id";
    $route["$row->slug"] = "item/index/$row->id";
}

这假设是&#39; id&#39;作为主键和那个&#39; slug&#39;将是独一无二的

在您的控制器中,您可以通过以下方式获取ID:

    $id = $this->uri->rsegment(3);