Codeigniter - 路由访问模型和数据库

Codeigniter - Access Models And Database on Routing

我打算在 codeigniter 3.0.3 中创建一个项目,我想使用如下所示的路由。

1) 。 www.mydomain.com/categoryNamehere
2) 。 www.mydomain.com/postNameHere

我的数据库中有一个单独的 table 来保存类别名称及其唯一 ID。
我想要的是当用户点击 link 比如 www.mydomain.com/xxxxx
1.first 检查类别 table (xxxxx)
2. 如果没有匹配将它 (xxxxx) 发送到 post 控制器。
我如何在 Codeigniter 3.0.3 上实现它?
我尝试在 config / routing.php 中访问我的模型,并且我还尝试直接在路由页面中执行 mysql 代码(活动记录)。

要实施提议的 url 结构,我们必须创建一个中央调度程序,它将

  1. 分析所请求的URL。
  2. 将查询数据库以查找并显示类别。
  3. 如果找不到类别,它将尝试查找并显示文本 post。

听起来像是控制器的工作。但是我们如何制作一个响应每个请求的控制器呢?借助通配符路由!

application/config/routes.php

$route['.*'] = 'default_controller';

现在每个请求,无论 URI 是什么,都将被路由到 Default_controller.php

但是我们如何在不知道调用什么方法的情况下编写控制器呢?有一种方法:内置控制器服务方法 _remap.

来自 the docs

If your controller contains a method named _remap(), it will always get called regardless of what your URI contains.

所以我让自己幻想并为你创造了一个概念Default_controller:

application/controllers/Default_controller.php

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

class Default_controller extends CI_Controller {

    // Pseudocode ensues 
    public function _remap()
    {
        // www.mydomain.com/(someTextHere)
        $slug = $this->uri->segment(1);

        $result = $this->load_data($slug);

        echo $result;
    }

    private function load_data($slug)
    {
        // Trying to find a category
        $category = $this->category_model->find($slug);
        if($category !== false)
        {
            // Presumably loads view into buffer
            // and returns it to the calling method
            return $this->load_category($category);
        }

        Trying to find post
        $post = $this->post_model->find($slug);
        if($post !== false)
        {
            return $this->load_post($post);
        }

        // Neither category nor post found
        show_404();
    }

    private function load_category($category)
    {
        // http://www.codeigniter.com/user_guide/general/views.html#returning-views-as-data
        return $this->load->view("category", array("category" => $category), true);
    }
}

注意:在新下载的 Codeigniter 3.0.3

上测试了这个答案