Codeigniter: how can i tell if a model is already loaded? Codeigniter: how can i tell if a model is already loaded? codeigniter codeigniter

Codeigniter: how can i tell if a model is already loaded?


I would be tempted to extend the CI_Loader core class. (See 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);    }}

You would be checking for a given model with the following:

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

That strategy is already being used by the CI_Loader class.

This solution supports the model naming feature of CI, where models can have a different name than the model class itself. The class_exists solution wouldn't support that feature, but should work fine if you aren't renaming models.

Note: If you changed your subclass_prefix configuration, it might not be MY_ anymore.


The simplest solution is to use PHP function class_exists

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

For example. if you want to check if Post_model has been defined or not.

$this->load->model('post_model');/*     a lot of code*/if ( class_exists("Post_model") ) {    // yes}else {    // no}

The simplest is the best..


Edited:

You can use the log_message() function.

Put this in your model’s constructor (parent::Model())

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

don’t forget to set the log config to debug mode in the config.php file

$config['log_threshold'] = 2; 

And set the system/logs directory permission to writable (by default CI will create the log files here)

or set the logs directory in another dir

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

CI will then create the log file in the directory. monitor the log files as you like. You can get the debug message to see if your model is already loaded or not in the log files.