Welcome Guest, Not a member yet? Register   Sign In
How do I create object definitions that I can reach from within CI?
#1

[eluser]Starovich[/eluser]
Hello! I have been using CI for a while (MVC approach) but never felt the need for objects until now.

I would need to be able to do something like this from all controllers:

Code:
$myDog = new Dog('Fido');
$myDog->getName();

In my current project I extend Controller with my own MY_Controller and I'd need to use these objects there also.

My question is basically: Where do I put the code for my objects (Dog class definitions etc) to be able to reach them from MY_Controller and controllers/libraries in CI?

Thank you for your time.
#2

[eluser]mikelexp[/eluser]
Models maybe?

$this->load->model("dog");
$this->dog->getName();
#3

[eluser]Starovich[/eluser]
[quote author="mikelexp" date="1299421299"]Models maybe?

$this->load->model("dog");
$this->dog->getName();[/quote]

This doesn't work because I can only access static methods using that approach. For example, how would I create another Dog object if I wanted two of them?
ie:
Code:
$myDog = new Dog('Fido');
$anotherDog = new Dog('Digby');
#4

[eluser]Edmundas KondraĊĦovas[/eluser]
Can you specify what exactly are you trying to accomplish?
#5

[eluser]Starovich[/eluser]
[quote author="Edmundas KondraĊĦovas" date="1299439339"]Can you specify what exactly are you trying to accomplish?[/quote]

I need to be able to create custom objects inside my controllers and libraries, like I specified in the first post. the "Dog" class is an example, what I really need to do isn't really in the scope of the question.

I just want to know how people do to use objects (OOP) inside their CodeIgniter projects.
#6

[eluser]WanWizard[/eluser]
That is not a problem, you just have to either load your class manually (using require_once), or setup an autoloader.

Or misuse the models:
Code:
// load the model class
$this->load->model('dog');

// don't need the CI singleton
unset($this->dog);

// create a dog object, the class is still loaded!
$mydog = new Dog();
#7

[eluser]Starovich[/eluser]
Thanks Wan!

Is there any best practices for where I should put my object definition classes using require_once?

I'd rather not use models (although interesting implementation!) as I want to have a clear structure for my software (ie models handle database interactions, period).
#8

[eluser]Phil Sturgeon[/eluser]
[quote author="Starovich" date="1299445535"]Thanks Wan!

Is there any best practices for where I should put my object definition classes using require_once?

I'd rather not use models (although interesting implementation!) as I want to have a clear structure for my software (ie models handle database interactions, period).[/quote]

Libraries work in the exact same way. You can put your files in application/libraries and use:

Code:
require_once APPATH.'libraries/dog.php';
$dog = new Dog();




Theme © iAndrew 2016 - Forum software by © MyBB