Welcome Guest, Not a member yet? Register   Sign In
constructor - why, where, when??
#1

[eluser]boony[/eluser]
Hi Igniters,

I've now spent the last 3-4 days immersed in CI and for the most have figured out the basics. Essentially I'm reasonably happy with the framework and will definitely employ it in my future application development work.

However, I'm still coming to grips with the whole OOP thing and am currently learning PHP OOP and MVC in my Diploma of Web Dev. So there are obviously a lot of things that I need to learn to bring everything together.

In respect of CI I have one major question (well one of many but this one is the most prominent at the moment :question: ) that is currently mystifying me. I can't seem to get the notion of the constructor and when and where to use it. I notice in some of the examples that parent::constructor is used ie in controllers and models but isn't used in others. I also noticed that sometimes loading of helpers & classes can be declared in the constructor method and at other times in the methods themselves.

I've had a look around but haven't (as yet) found a satisfactory answer as to when a constructor should be created and where it should be placed and what else should be included in the constructor method. Finally, do we use the class name or the __constuct call or are they interchangeable????

A pointer in the right direction would be greatly appreciated as I think this is still the missing link in the whole thing for me at the moment :gulp:

Thanks
boony
#2

[eluser]pistolPete[/eluser]
[quote author="boony" date="1234675662"]... when a constructor should be created and where it should be placed and what else should be included in the constructor method.[/quote]

From http://php.net/manual/en/language.oop.constructor.php
Quote:Constructors are functions in a class that are automatically called when you create a new instance of a class with new.
You need to create a class specific constructor if you need additional functionality in it which the parent's constructor does not provide.

Have a look at a CI example:

Let's say you want to extend CI's Controller class which checks if a user is permitted to access a specific page/functionality of your application:
Code:
class AuthController extends Controller
{
    private test;

    public function __construct()
    {
        // call the parent's constructor
        parent::Controller();
        
        // now add all the tasks which should be executed
        // everytime a new AuthController object is created
        
        // initialise member variables
        test = 0;

        // load some libraries
        $this->load->library('layout');
        $this->load->library('login');
        $this->load->library("validation");
        // load models
        $this->load->model('admin/crudmodel');
        
        // call functions
        $this->auth();
    }
    
    
    private function auth()
    {
        // some code to check if user  
        // is allowed to access this controller
        if (no)
        {
            redirect('home');
        }
    }
}

If you need some libraries / models etc. in many / all of your controller's function, load them in the constructor in order to avoid code reduplication.
You also see, if you need something (here the access control) to be done before any other class function is getting executed, put it in the constructor.

[quote author="boony" date="1234675662"]Finally, do we use the class name or the __constuct call or are they interchangeable????[/quote]
This depends on the PHP version you are using. In PHP4 you can only call the class_name() constructor, in PHP5 you can call both, although __construct() is the preferred one.
Have a look at: Constructors and Destructors
#3

[eluser]Colin Williams[/eluser]
Quote:Finally, do we use the class name or the __constuct call or are they interchangeable????

It differs between version of PHP. In PHP 4 you did the class name, in PHP 5 you do __construct(), but you can still do class name to be backwards compatible.

Constructors serve the purpose of getting the class ready. Bootstrapping if you will. You can think of it as the first thing that gets done every time that class is instantiated.

Quote:I notice in some of the examples that parent::constructor is used ie in controllers and models but isn’t used in others

When you are extending a class, which is common to do with Controller and Models (well, pretty much necessary), the classes you extend have their own constructors defined for the class. When your extension creates it's own constructor, it overrides the parent class. So any functionality performed by the parent class' constructor is lost--functionality that is necessary. The way to resolve it is to make a static class function call to the parents constructor, to restore all the necessary functionality--to force it to run anyway.

The only time you won't see it used is when the extension doesn't provide its own constructor, which might be a rare case.
#4

[eluser]Colin Williams[/eluser]
Haha.. it figures that pistolPete fired his out there a few seconds quicker...
#5

[eluser]boony[/eluser]
OK,

Thanks, that seems to be a bit clearer. I'm guessing, to be on the safe side, that it may be advisable to use a constuctor method in all controllers and models that I create, this way I can safely add specific methods to the subclass (or not as the case may be) and be sure that the method will work.

From what pistolPete posted I get the idea that all library-helper classes, as well as the model, should be loaded into the constructor methods and not into the individual methods that I create within the controller. From this I take it that any library class eg $this->load->library('table') will be available globally if placed in the constructor but will only be available to when a specific function is called if it is placed within that method. Is this correct??

Finally, what about the call to the view? Is that also always called in the constructor?? Or only called in the method the builds the view?

Hope I'm not asking the bleeding obvious, but these things seem to be very important and it I would like to make sure that I get the syntax correct to save future head banging (a thing I seem to do a lot of :-)

Boony
#6

[eluser]Colin Williams[/eluser]
Have you watched any CI screencasts or tutorials? Might help to see some of this stuff demonstrated. And the user guide covers a lot of this pretty well.
#7

[eluser]boony[/eluser]
Yep, I blame total incompetence on my part.

watched the videos and looked at all the user guide and as many tutorials that I could find (still looking for more :red: ) but it is more the placement of things.

The reason I'm banging on about this is that some of my tests didn't return the expected results and trial and error has generally ended with the incorrect call to load functions and the passing of data between the controller and model and views (well apart from idiot syntax, ridiculous function construction and general incompetence :-S ). So I'm trying to develop a standardised work flow and want to make sure that the basic files (MV&C) contain the bare minimum coding to enable quick application development, a goal we all aspire to I guess!
#8

[eluser]Unknown[/eluser]
Hi, as I walked through the user guide, I see only a few lines to describe the constructor named in the PHP5 manner. In fact, most examples still using the PHP4 implementation (i.e. having a function name same as the class name.)

For newcomers and new developers using PHP5, the constructor is supposed to be

__construct()

also the user guide didn't mention enough to use the PHP5's style of essential call to the inherited class's constructor using,

parent::__construct()

I hope my observation is reasonable and could be considered as a need to make an immediate supplementary note to the user guide.

As the previous replies stated, the __construct in PHP5 is the preferred practice. Please help CI developer to have a more concrete and clear in this issue.

I personally think the constructor and destructor are both critical for any Object-Oriented design/implementation. The naming and implementation difference between PHP4 and PHP5 had been a long discussion. The rationale using __construct instead of the same function name as class name was welcomed by many developers.

Hope we share our views. :-)
#9

[eluser]jedd[/eluser]
[quote author="boony" date="1234679784"]OK,
Thanks, that seems to be a bit clearer. I'm guessing, to be on the safe side, that it may be advisable to use a constuctor method in all controllers and models that I create, this way I can safely add specific methods to the subclass (or not as the case may be) and be sure that the method will work.
[/quote]

It's safe to say that, for the moment, all the classes you make will include a constructor (even if its empty other than the parent:: line). This assumption is based on the idea that you are most likely to be creating Controller and Model classes only (views don't the issue), at least in the short term.

Quote:From what pistolPete posted I get the idea that all library-helper classes, as well as the model, should be loaded into the constructor methods and not into the individual methods that I create within the controller.

I don't think that's what he was saying. If all the methods - think of them as functions that are grouped together to work on the object's data - have similar requirements (and really, they should if you design things right) then it's *probably* sensible to have the libraries and helpers called in the constructor (because all this object's methods will make use of them).

BUT if one of your methods in a class does something special that needs a library or helper that none of the other methods do, then it's good practice to make that lib/help load call in the method itself. Better performance for starters.

Note that I'm about 27 minutes ahead of you with this stuff .. so keep reading through the user_guide, particularly going over the M, V, and C pages - as well as the CI wiki. Read everything carefully, as very important ideas are often slipped in where you don't expect them. Wink

Quote:From this I take it that any library class eg $this->load->library('table') will be available globally if placed in the constructor but will only be available to when a specific function is called if it is placed within that method. Is this correct??

Globally is a very strong word. But no. Not global.

They'll be available within the class, yes. To all methods within that class, to really spell it out.

Quote:Finally, what about the call to the view? Is that also always called in the constructor?? Or only called in the method the builds the view?

No .. calls to views are typically done within your methods within the Controller object. You *might* want to call a frequently used common view to construct some HTML from your constructor - but for now I'd suggest you don't.

Quote:Hope I'm not asking the bleeding obvious, but these things seem to be very important and it I would like to make sure that I get the syntax correct to save future head banging (a thing I seem to do a lot of :-)

Future head-banging is guaranteed. Don't fight it.
#10

[eluser]jedd[/eluser]
[quote author="jedd" date="1235946881"]
If all the methods - think of them as functions that are grouped together to work on the object's data - have similar requirements (and really, they should if you design things right) then it's *probably* sensible to have the libraries and helpers called in the constructor (because all this object's methods will make use of them).[/quote]

Having said that .. if you are frequently using certainly libraries, you'll find it easier to autoload them by editing your config/autoload.php - specifically the line that starts with $autoload['libraries'] = ...

I expect most Igniters autoload database for starters.




Theme © iAndrew 2016 - Forum software by © MyBB