Welcome Guest, Not a member yet? Register   Sign In
Confused About Objects and Classes
#1

[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
#2

[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).




Theme © iAndrew 2016 - Forum software by © MyBB