2013-02-18 117 views

回答

12

我會試圖擴展CI_Loader核心類。 (見extending Core Class

class MY_Loader extends CI_Loader { 

    function __construct() 
    { 
     parent::__construct(); 
    } 

    /** 
    * Returns true if the model with the given name is loaded; false otherwise. 
    * 
    * @param string name for the model 
    * @return bool 
    */ 
    public function is_model_loaded($name) 
    { 
     return in_array($name, $this->_ci_models, TRUE); 
    } 
} 

你會檢查有以下一個給定的模型:

$this->load->is_model_loaded('foobar'); 

That strategy已被使用的CI_Loader類。

此解決方案支持CI的模型命名功能,其中模型可以具有與模型類本身不同的名稱。 class_exists解決方案不支持該功能,但如果您不重命名模型,應該可以正常工作。

注意:如果您更改了subclass_prefix配置,它可能不再是MY_

4

編輯:

您可以使用log_message()函數。

在模型的構造將這個(父::模型())

log_message ("debug", "model is loaded"); 

不要忘記設置日誌配置調試模式在config.php文件

$config['log_threshold'] = 2; 

並將系統/日誌目錄權限設置爲可寫(默認情況下,CI將在此創建日誌文件)

或將日誌目錄設置爲另一個目錄

$config['log_path'] = 'another/directory/logs/'; 

CI會在目錄中創建日誌文件。根據需要監視日誌文件。您可以獲取調試消息,以查看您的模型是否已加載或未加載到日誌文件中。

+1

這隻會讓我知道,如果該文件存在,我想知道如果第一個模型已經在控制器中動態加載或如果已通過自動加載自動加載 – Xecure 2013-02-19 01:33:06

4

Riffing過什麼馬克西姆·莫蘭& Tomexsans寫了,這是我的解決方案:

<?php 
class MY_Loader extends CI_Loader { 
    /** 
    * Model Loader 
    * 
    * Overwrites the default behaviour 
    * 
    * @param string the name of the class 
    * @param string name for the model 
    * @param bool database connection 
    * @return void 
    */ 
    function model ($model, $name = '', $db_conn = FALSE) { 
     if (is_array($model) || !class_exists($model)) { 
      parent::model($model, $name, $db_conn); 
     } 
    } 
} 
?> 

這樣,你永遠不要需要(有意識)檢查模型加載與否是否:)

+0

我遇到我多次加載類的情況,並沒有拋出任何錯誤,但它使用了PHP內存限制,這解決了我的問題,無需修改任何其他代碼,所以非常感謝! – Sam 2015-04-25 13:15:50

4

最簡單的解決方案是使用PHP函數class_exists

http://php.net/manual/en/function.class-exists.php

例如。如果你想檢查是否已經定義了Post_model。

$this->load->model('post_model'); 

/* 

    a lot of code 

*/ 

if (class_exists("Post_model")) { 
    // yes 
} 
else { 
    // no 
} 

最簡單的是最好的..

相關問題