CodeIgniter Forums
Autoload config and models trick - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5)
+--- Forum: Best Practices (https://forum.codeigniter.com/forumdisplay.php?fid=12)
+--- Thread: Autoload config and models trick (/showthread.php?tid=1634)



Autoload config and models trick - Everterstraat - 03-27-2015

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!


RE: Autoload config and models trick - mwhitney - 03-27-2015

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.


RE: Autoload config and models trick - Everterstraat - 04-19-2015

(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?!


RE: Autoload config and models trick - mwhitney - 04-20-2015

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.


RE: Autoload config and models trick - kilishan - 04-20-2015

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.