CodeIgniter - where and when should I call $this->load->database() - php

I'm new to CodeIgniter and currently in my project I have several Models, loaded by several Controllers, which need to work with the database.
My question is - can I call $this->load->database() in just one place for the entire project, or should I do it in each method in my Models?
Thanks

In your autoload.php which is located in /application/config/autoload.php in which you see
$autoload['libraries'] array just add
$autoload['libraries'] = array('session', 'database','other_libraries');
If your project scope involves the database interaction you should use the autoload while including in each function would be a headache for you
Hope it makes sense

You have three choices (that I can think of).
If you require it almost everywhere in your project, use the
/application/config/autoload.php file, in which you'll find the
following statement:
$autoload['libraries'] = array();
which you can change to
$autoload['libraries'] = array('database');
This is the easiest method, but it does add overhead since the database class will be loaded even when you do not require it.
If you find that you need to use it for almost every method in a particular model you can call $this->load->database(); in the constructor of that particular model, for example:
class Forums_model extends CI_Model{
function __construct()
{
// Call the parent constructor
parent::__construct();
$this->load->database();
}
function get_records()
{
$this->db->get('table');
//this now works in every method in this model
}
}
which will make the database class available to every method in that model. This is a more efficient option than the second and not as tedious as the third, probably making it the most balanced option.
You can also, of course, choose to load it in every method that requires it using $this->load->database(); This adds the least overhead, theoretically making it the most efficient. However, doing this is very tedious.
All three will work, it's your choice whether you want it to be easy, or efficient. (My personal recommendation is choice 2)

If only some of your pages require database connectivity you can manually connect to your database by adding this line of code
$this->load->database();
in any function where it is needed, or in your class constructor to make the database available globally in that class.
The "auto connect" feature will load and instantiate the database class with every page.just
add the word 'database' to the library array, as indicated in the following file:
application/config/autoload.php
http://ellislab.com/codeigniter/user-guide/database/connecting.html

I know this is not the best of all methods, but since you are beginner.. you just call load data base $this->load->database() in that method just above the code where your database related query begins.. just suppose $this ->load->database(); is exactly the same thing for you as you were using include_once('connection.php') this script in you simple php script (without CI).

Related

Do the best way to load model in codeigniter?

I written code using Codeigniter, I want to increase for load time when I open my page for first time. Actually when I written code I load all the model in my contruct like this:
public function __construct(){
parent::__construct();
$this->load->model('Fa_promo');
$this->load->model('Fa_project');
$this->load->model('Fa_inbox');
$this->load->model('Fa_quotes');
$this->data['keywords']=$this->Configuration->get_keyword();
$this->data['about'] = $this->Fa_menu->get__content_from__slug('about');
$this->data['menu']=$this->Fa_menu->list_menu_level1();
$this->Configuration->update_hits();
}
My question, how to do the best way to load the model to increase performance between above or like this?
public function __construct(){
parent::__construct();
}
public function a(){
$this->load->model('Fa_promo');
$this->Fa_promo->load();
}
public function (){
$this->load->model('Fa_project');
$this->Fa_project->load();
}
Thanks for your help :)
It will be faster to load them individually in each function as you can limit the number of calls made to load a model, but the difference is likely to be minimal
If you load them all in the constructor, then you can use them at any point in the controller from one load, which might be a little slower, but the benefit is they are loaded and ready. It could use more memory than needed for a single given function though.
If you want to save code for loading the models, you could always do the following in the constructor:
$this->load->model(['Fa_promo', 'Fa_project', 'Fa_inbox', 'Fa_quotes]);
This will load all of the models in one go. There's no real time benefit of this as passing an array causes the loader to call itself for each item, so it's the same as you currently have.
The codeigniter docs say: Your models will typically be loaded and called from within your controller methods.
The first approach has a great advantage: you can reuse it in all controller methods and don't have to type in each method over and over again.
concerning performance: I think it doesn't make any difference, the functions in the model might slow down things

Does loading unneed models in controller constructor affect performance in CodeIgniter 2?

Which one is better performance-wise? Loading all the models used in the controller in constructor or loading the model only in the needed function? Or is there any difference? If the model is needed only in one of the functions of a big controller, does it affect the performance if its loaded in the constructor?
class myController extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('loginmodel');
}
public function useLoginModel(){
$this->load->model('loginmodel');
$this->loginmodel->login();
}
}
If you only use it in that one function, then it is probably faster to load it only there. But this decreases mantainability. You always have to recheck if the model was loaded every time you want to use it somewhere. So I would stick with loading everything in the constructor (depends on the number of models obviously).
There is a simple rule for optimizations: If it isn't slow, don't optimize it. You gain very little from the above change, but encounter a severe hit in mantainability (or as symfony calls it "Developer Experience")
You can add it in autoload.php inside config folder.
$autoload['model'] = array('loginmodel');
Hope it helps.

The management of files and folders in codeIgniter can be made from controller or model?

I want to verify if file/folder exists on my CI system (not system folder), can i do it from controller or I need create a method on my model to do it?
It's basically a matter of choice. You can define your function in both your model and controller. But if you want to use it over and over from different controllers, then better define a new model and put that function in it. I'd define model which is to be used by many controllers that is having some common-general methods. Just to keep things apart and maintaining them later. Helpers are also a way to keep things separate.
You have got many way for this :
You can create an helper and put your function like verify()
You can create a private function into your controller like
private function _verify() { }
enjoy !
Best to add this function in a codeigniter helper or in a library class(if you are fan of OOP). Load this automatically with autoload.php and call from wherever you need it.

OOP PHP problem getting 2 classes to work with the same parent

I'm fairly new to OOP PHP and am having trouble with getting a couple of classes to work nicely together. I'm using a database abstract class to do all the grunt work of talking to the database and that is all fine, and I can extend it with another class with the methods to make specific actions. The database class has an include_once to read in the config settings for the database.
Where I am confused is if I need to use a 2nd class to access the database on the same page, I need to reference a 2nd config file that has the same settings.
Example: I have a products class for a site I'm building and it is working fine. I wanted to use a 2nd class to control the actual shopping cart side of things, but when I try and extend the database class with the Cart class the page fails unless I override which config file it needs to reference.
Why do I need separate config files for each class and is there a way around this? It seems silly that I should need as many config files as there are classes that interact with the database.
Thanks for your help.
Jon
* Extra Info *
Sorry guys, Everything is in the same database. Here is some sample code.
All config files are like this:
$DB_HOST = "localhost";
$DB_USER = "abcdef";
$DB_PASS = "123456";
$DB_DATABASE = "newdb_name";
then I override the config file which it needs to pull in but doing this in the sub classes:
function __construct()
{
$this->conffile = "db_conf1.php";
parent::__construct();
}
and change the $this->conffile for each new sub class.
I'm using a database abstract class to do all the grunt work of talking to the database and that is all fine, and I can extend it with another class with the methods to make specific actions. The database class has an include_once to read in the config settings for the database.
This is a bad design. If you need to use two of these classes together in the same script, you're going to end up w--
Where I am confused is if I need to use a 2nd class to access the database on the same page
Phew, you got it already.
You generally only want one database connection per page. This generally means only one database object. You have two good options in PHP to deal with this.
The first has a fancy name: "Dependency Injection." In DI, your objects require some external resource to work. They receive this resource during construction.
In other words, you pass your database object in the constructor.
class Foo {
protected $db;
public function __construct($other, $args, $db) {
$this->db = $db;
}
}
This way, you still get the convenience of referencing the database from within your object without having to make it too intermingled.
The other option also has a fancy name: the "Registry Pattern." Registries act as gateways to "well-known" classes and instances. They're basically look-up tables, allowing you to make your program depend on data that will be present in the Registry rather than hard-coding class names or using globals.
Or, in other words, it's just a global hash with a special name.
Doing it right requires a class. This blog post from 2009 is an interesting starting point because it deals exactly with the problem of what to do with a database adapter. I'll omit example code here, as the blog post does a decent job of explaining itself.
There is a third option, of course, and it's the worst, yet most common in PHP land: assigning the database object to a global, then referencing the global as needed. It's quick, it's dirty, it usually works... but can make maintenance difficult, and can make automated testing impossible to do correctly. Don't do it.
You should remove the dependency on the config file from the database class and pass the variables you need into the database constructor e.g.,
class Database {
public function __construct($host, $user, $pass, $dbname, $port) {
// create connection
}
//...
}
Put the info for both your databases into one config file and create your database objects like this:
include_once 'config.php';
$db1 = new Database($host1, $user1, $pass1, $dbname1, $port1);
$db2 = new Database($host2, $user2, $pass2, $dbname2, $port2);

Where should i set my db object in my model ? (MVC)

I would like to know where is the best place to set my db object with my model.
Should I hard coded it since my model should be designed for one project, so i set it inside my constructor or wherever i do initialization ?
or
Should I pass my db object to my constructor when instancing my object ?
What is the best way, i mean from experimented users, and efficient that'll give me more confort to use ?
Couple of things:
Most PHP projects that utilize a database connection represent that database using a Singleton pattern, if you aren't sure what this is, read up on it.
Typically I define my database connections in a configuration file which can easily be changed between environments (development, stage, production).
I'll then instantiate my database connection in a bootstrap file using the aforementioned Singleton pattern and configuration file.
My models will typically completely abstract the database/table data store, for each model I'll do something like this:
bootstrap.php
$config = load_config_data(ENVIRONMENT);
Db::setDefaultAdapter($config['database']);
Model/Table/User.php
class Table_User extends Db_Table
{
// Table name
protected $_name = 'user';
/* Do a bunch of database specific stuff */
}
Model/User.php
class User extends Model
{
public function updateUsername($userid, $username)
{
// Uses default adapter, Singleton pattern!
$table = Db::loadTable('user');
$table->update(
array('username'=>$username),
Db::quoteInto('userid = ?', $userid)
);
}
}
This is pretty much an introduction to the Model in the Zend Framework MVC, I would check it out for some ideas on how to organize your code (or save yourself some trouble and actually use the framework.)
For testability, you should pass it into the constructor rather than hard coding it. This helps you to write unit test because you can mock your DB object.
I would not hard code it, even if the code is never used for another project simply moving from a test database to a live database may require locating and changing the code in the model class. That would be far better placed in some kind of configuration file.
Personally, I would have the db object defined in whatever you use as a bootstrap - and then have the model(s) use that single object.

Categories