Welcome Guest, Not a member yet? Register   Sign In
External classes and using objects in CI
#1

[eluser]Goric[/eluser]
Hi.
I've got a question. Is there any way to declare a class and then use it in Model or Controller? I know about libraries, but I need to create more than one instance of this class. I mean, I need to do something like this in my app:
Code:
<?php
class AClass {

    public function __constructor()
    {
        do_something();
    }
}

class ExampleModel extends Model {

    public function __contructor()
    {
        parent::Model();
        $instance = new AClass();
    }
}

Is something like that possible in Code Igniter?
#2

[eluser]davidbehler[/eluser]
You can use "normal" PHP...no need for something fancy Big Grin

Place the file with your AClass declaration inside your application folder...in application/libraries or where else suits you best.
Code:
<?php
  include(APPPATH.'libraries/your_file_with_the_class_declaration.php');

  class ExampleModel extends Model {
    public function __contructor()
    {
        parent::Model();
        $instance = new AClass();
    }
}
   }
<?

Or you could just use your example and put the additional declaration inside your model file.

Both is untested but should work.

As far as I know there is no CI-way to do this.
#3

[eluser]Goric[/eluser]
Thanks, I didn't know that you can just put a declaration into a model file just like that.
#4

[eluser]davidbehler[/eluser]
All CI does with a model file is include it and create an object of the class inside the file with the name of the file.

You can do whatever else you want in such files...the same for libraries, controllers.
#5

[eluser]Goric[/eluser]
It means that if I use my ExampleModel you presented in your post in a controller, the AClass will be automatically included?
#6

[eluser]davidbehler[/eluser]
Yes, but no instance will be created. You would have to do that yourself as you did in your first post in the constructor of your model.




Theme © iAndrew 2016 - Forum software by © MyBB