CodeIgniter - 动态页面 - 默认控制器URL

时间:2012-06-08 16:19:03

标签: codeigniter codeigniter-2 php

修改

我在routes.php中的解决方案:

$route['news'] = 'news_controller';
$route['gallery'] = 'gallery_controller';
$route['(:any)'] = 'sites/$1';

并在我的网站控制器中:

function index($site_id = '') {
  //sanitize $site_id.
  $this->site = $this->sites_model->get_site($site_id);
  //etc.
}

THX到YAN

问题:

所以我用CodeIgniter写了一个小CMS。管理员可以创建网站。当网址的网段与数据库中的网段相似时,网站会自动打开。例如,mysite.com/sites/about将调用“关于”网站。这很好。

现在我的网址出现了问题。我想要这个网址

http://www.mysite.com/sites/about

转向:

http://www.mysite.com/about

问题是,我不能使用routes.php并为每个站点设置通配符。 (因为它们是动态的,我不知道客户会创建哪个网站 - 我不想编辑他将创建的每个网站的routes.php文件 - 这应该自动完成)

问题是我有其他修复控制器,如新闻,画廊或联系人: mysite.com/news,mysite.com/gallery,......他们工作正常

所以这是我的站点控制器:

class Sites extends Public_Controller {

public $site;
public $url_segment;

public function _remap($method)
{
    $this->url_segment = $this->uri->segment(2);

    $this->load->model('sites_model');
    $this->site = $this->sites_model->get_site($this->url_segment);

    if($this->site !== FALSE)
    {
        $this->show_site($this->site);
    }
    else
    {
        show_404($this->url_segment);
    }
}

public function show_site($data)
{
    $this->template->set('site', FALSE);
    $this->template->set('site_title', $data['name']);
    $this->template->set('content',$data['content']);
    $this->template->load('public/template','sites/sites_view', $data);
}}

这是检查数据库的Site_model ...如果url_segment符合数据库中的标题:

class Sites_model extends CI_Model {

public function get_site($site_url)
{
    if($site_url != ""){
        $this->db->where('name', $site_url);
        $query = $this->db->get('sites', 1);

        if($query->num_rows() > 0){
            return $query->row_array();
        }
        else
        {
            return FALSE;
        }
    }else{
        return FALSE;
    }
} }

我认为我需要检查控制器是否存在(网址的第一段),而不是调用网站控制器并检查网站是否在数据库中,当这是错误时,请调用404。

有关如何解决这个问题的任何建议吗?

顺便说一下:sry for my english

关于GN

2 个答案:

答案 0 :(得分:2)

您可以通过以下方式处理routes.php,只需保留(:any)值:

$route['news'] = 'news_controller';
$route['gallery'] = 'gallery_controller';
$route['(:any)'] = 'sites/$1';

在您的站点控制器中使用URL中的数据路由到特定站点。

function index($site_id = '') {
    //sanitize $site_id.
    $this->site = $this->sites_model->get_site($site_id);
    //etc.
}

答案 1 :(得分:1)

我无法理解问题的全部意图,但是,据我所知,你不需要添加:

if ($this->uri->segment(1) != 'sites')
     ... // handle malformed URL