How to set dynamic route to use slug in CodeIgniter?

前端 未结 6 1764
心在旅途
心在旅途 2020-12-17 04:00

Let\'s say that I have a controller named

pages

and there is a method

slug_on_the_fly

public functi

6条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-17 04:12

    You could use database driven routes.

    Add the table blog_slugs to your MySQL database:

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

    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'. EXT );
    $db =& DB();
    $query = $db->get( 'blog_slugs' );
    $result = $query->result();
    foreach( $result as $row )
    {
        $route[ $row->slug ] = 'pages/slug_on_the_fly/$1;
    }
    

    All you would have to do then is to create a record when you create a blog entry and you're done:

    INSERT INTO `blog_slugs` (`slug`) VALUES ('name-of-the-article');
    

提交回复
热议问题