CodeIgniter Forums
Confused About Objects and Classes - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forum-20.html)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forum-23.html)
+--- Thread: Confused About Objects and Classes (/thread-33883.html)



Confused About Objects and Classes - El Forum - 09-11-2010

[eluser]Adolfo Reyes[/eluser]
Hello,

I'm fairly new to CodeIgniter and have a question. I'm a bit confused about Classes, Libraries and Objects.

Does CodeIgniter replace the normal PHP way of usings objects i.e. $var = new car() with libraries i.e. $this->load->library([some_library]); $this->some_library->some_function(); ?

If both are valid, is there a difference? If so, what are the differences and when I do use one over the other?


Thanks in advance


Confused About Objects and Classes - El Forum - 09-12-2010

[eluser]WanWizard[/eluser]
From a technical point of view there is no difference.

Code:
require_once( APPPATH . 'libraries/mylib.php');
$this->mylib = new mylib();

is the same as
Code:
$this->load->library('mylib');

The difference is that all CI classes are loaded as singletons. Everytime you use 'new', a new object is created. $this->load will only create the object once, after that the same object is reused every time you call it. Also, because the CI concept is that all objects are accessable via $this, the loader will take care that newly loaded objects are assigned to the already loaded objects. So if you load a new library somewhere, it will be automatically assigned to your controller and to all already loaded models.

For libraries this works fine, as they only contain the reusable methods for your application.

For models, it depends.

In the CI way of doing things, these are singletons as well, and model methods are supposed to return data collections (array or a array of objects) that can be processed in the controller and/or passed on to the view.
This doesn't work when you want or need objects representing your data. In most cases, this can be addressed by using an ORM library, for example Datamapper DMZ (use the search).