CodeIgniter Forums

Full Version: Autoload config and models trick
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
1: If config exists, load it!
2: If table exists, load model!
Code:
if(is_file($file = APPPATH.'config/'.$this->router->class.'.php') !== false)
{
$this->config->load($this->router->class);
}
if($this->db->table_exists($this->router->class))
{
$this->load->models(array($this->router->class.'_model' => $this->router->class));
}
If you're adding fwrite a model in MY_Model if class exists as table, you've dynamic models loaded for each table!
Your code indicates you are using some sort of third-party loader (since $this->load->models() is not part of the CI loader), and you would have to connect to the database before deciding to load the model, where many people might prefer not to connect to the database until they've decided to load a model.
(03-27-2015, 07:49 AM)mwhitney Wrote: [ -> ]Your code indicates you are using some sort of third-party loader (since $this->load->models() is not part of the CI loader), and you would have to connect to the database before deciding to load the model, where many people might prefer not to connect to the database until they've decided to load a model.

Code:
load->models(model) is checking if is_file(model), if not and table does exist; create model file and load->model(model).
About deciding to load or not, that's different per application, right?!
It might be different per page in some applications, it really just depends on what you are doing. Personally, I use the database for almost every page which goes through CI in my main site, but there are certainly areas in which I've looked at the possibility of using more aggressive caching for some of the database content to prevent the need to access the database on some of the site's more static pages.
The database does NOT have to be preloaded prior to loading a model. If you want to wait to load the database until needed, just make sure you pass in TRUE as the third parameter to $this->load->model() and it will auto-connect at that point.