【问题标题】:Called controller can't access anything被调用的控制器不能访问任何东西
【发布时间】:2018-05-20 17:12:50
【问题描述】:

在 codeigniter 中我有我的主控制器:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Main extends CI_Controller
{
    public function index()
    {
        $this->load->library('../controllers/forum');
        $obj = new $this->forum();
        $obj->test();
    }
}

以及我尝试访问的控制器:

<?php
defined('BASEPATH') OR exit('No direct script access allowed');
class Forum extends CI_Controller
{
    function __construct()
    {
        echo "testing1";
        $this->load->library('session');
        parent::__construct();
        $this->load->database();
        $this->load->model('model_forum');
    }

    public function index(){

    }

    public function test(){
        echo "testing2";
        $this->data['forums'] = $this->model_forum->getForums();
        $this->load->view('homepage', $this->data);
    }
}

我的 model_forum.php 文件一切正常,因为如果我将所有代码放在主控制器中,它就可以工作。但如果我试图访问论坛控制器,没有任何效果,只有“testing1”回声通过。错误图片:

有人知道我做错了什么吗?我是 PHP 和 codeigniter 的新手,所以我有点挣扎。提前致谢。

【问题讨论】:

  • 请复制/粘贴错误消息的实际文本。如果不明显,您图片中的文字无法被本网站的搜索引擎索引。
  • 检查 codeigniter 路由。
  • 使用 $obj = new forum();然后 $obj = new $this->forum();

标签: php html xampp codeigniter-3 controllers


【解决方案1】:

您不能从 CI 中的控制器加载控制器 - 除非您使用 HMVC 或其他东西。

您应该考虑一下您的架构。如果您需要从另一个控制器调用控制器方法,那么您可能应该将该代码抽象到帮助程序或库中,并从两个控制器中调用它。

更新

再次阅读您的问题后,我意识到您的最终目标不一定是 HMVC,而是 URI 操作。如果我错了,请纠正我,但您似乎正在尝试使用第一部分作为方法名称来完成 URL,并完全省略控制器名称。

如果是这种情况,您可以通过获取creative with your routes 获得更简洁的解决方案。

举一个非常基本的例子,假设您有两个控制器,controller1controller2Controller1 有一个方法method_1 - 并且controller2 有一个方法method_2

你可以这样设置路线:

$route['method_1'] = "controller1/method_1";
$route['method_2'] = "controller2/method_2";

然后,您可以使用http://example.com/method_1 之类的URL 调用方法1,使用http://example.com/method_2 调用方法2。

尽管这是一个硬编码的、非常基本的示例 - 但如果您需要做的只是从 URL 中删除控制器,它可以让您到达您需要的位置。


你也可以选择remapping your controllers

来自文档:“如果您的控制器包含名为 _remap() 的函数,则无论您的 URI 包含什么,它都会被调用。”:

public function _remap($method)
{
    if ($method == 'some_method')
    {
        $this->$method();
    }
    else
    {
        $this->default_method();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-18
    • 2014-06-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-20
    相关资源
    最近更新 更多