簡體   English   中英

為什么在CodeIgniter中調用兩個控制器方法?

[英]Why are two controller methods being called in CodeIgniter?

我是否不應該將Index用作CodeIgniter中控制器類的名稱? 我有一個Index控制器,並且看到它的方法被多次調用。 更具體地說,無論我是否正在訪問應該路由到那里的路徑,我總是看到其index方法首先被調用。

在application / controllers / index.php中

class Index extends CI_Controller
{
    public function index()
    {
        echo "index";
    }
    public function blah()
    {
        echo "blah";
    }
}

當我訪問index/blah ,我看到indexblah打印出來。 當我訪問index/index ,看到indexindex 如果我將控制器重命名為其他名稱(例如Foo),則沒有問題。 那是顯而易見的解決方法,但是誰能告訴我為什么會這樣嗎? 我是否應該將此錯誤報告給CodeIgniter?

(注意:我沒有在configs/routes.phpconfigs/routes.php路由;我的index.php在CodeIgniter樹之外)

誰能告訴我為什么會這樣?

實例化控制器的get時,將調用構造函數的index

比較構造函數和析構函數文檔

為了向后兼容,如果PHP 5找不到給定類的__construct()函數,它將按該類的名稱搜索舊式的構造函數。 [由我突出顯示]

在您的情況下,Controller沒有任何__construct()函數,但是具有與class: index相同名稱的函數。 當Codeigniter解析並加載然后實例化Index控制器時,就會調用它。

您可以通過將構造函數添加到Controller中來解決此問題:

class Index extends CI_Controller
{
    public function __construct() {}
    public function index()
    {
        echo "index";
    }
    public function blah()
    {
        echo "blah";
    }
}

更改之后,不會再發生。

我是否應該將此錯誤報告給CodeIgniter?

不,實際上並不需要將其報告為錯誤,這是語言的工作方式,並且由於Codeigniter支持PHP 4,它必須保持向后兼容,並且需要提供PHP 4構造函數。 (注意:Codeigniter項目文檔,他們需要服務器支持PHP 5.1.6或更高版本,但是實際代碼具有內置的PHP 4兼容性,我在這里指的是代碼庫,而不是文檔。)

為了進一步闡明問題所在,在PHP4中,構造函數是一個與類同名的函數。

class MyClass
{
    public function MyClass()
    {
        // as a constructor, this function is called every 
        // time a new "MyClass" object is created
    }
}

現在為PHP5版本(從2.0.x版本開始,現在有哪個codeigniter作為系統要求)

class MyClass
{
    public function __construct()
    {
        // as a constructor, this function is called every 
        // time a new "MyClass" object is created
    }
}

因此,要回答解決該問題的問題...

我是否不應該將Index用作CodeIgniter中控制器類的名稱?

我相信最好不要選擇Index作為控制器名稱,因為index()函數在codeigniter中具有保留用途。 這可能會導致問題,具體取決於您的PHP配置。

這是使用Codeigniter3的另一種解決方案

require_once 'Base.php';
        class Index extends Base
    {
        public function __construct()
        {
        parent::index();
        $classname=$this->router->fetch_class();
    $actioname=$this->router->fetch_method();

    if($actioname=='index' || $actioname == '')
    {
        $this->viewall();
    }
}
}

並且viewall()具有以下內容

$this->siteinfo['site_title'].=' | Welcome';
$this->load->view('templates/header', $this->siteinfo);
$this->load->view('templates/menu', $this->siteinfo);
$this->load->view('index/viewall', $data);
$this->load->view('templates/footer', $this->siteinfo);

Base控制器負責整個應用程序的所有庫和輔助程序加載,這就是為什么默認類中需要它的原因

基本上從我對CodeIgniter的簡短了解來看,將默認操作作為索引是錯誤的。 我通過打印$ this-> router-> fetch_method();的結果發現了這一點。 在我的索引類的Construct()中。 CodeIgniter的默認操作是index,您只能在application / config / routes.php中設置默認控制器,而不能設置默認操作。

因此,我的建議是,不要將index()用作默認操作,尤其是當您使用index作為默認控制器時

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM