Welcome Guest, Not a member yet? Register   Sign In
index vs. __construct in controller?
#11

[eluser]davidbehler[/eluser]
index function is the default function that's called if no other function was submitted via the url.

Example:
http://example.com/controller/function will call controller->function
http://example.com/controller2/function3 will call controller2->function3
http://example.com/controller3 will call controller3->index


The constructor (__constructor in php5 and a function with the name of the class in php4) are executed after the object with your controller class was created and before the actual function/method that was provided via the url (or if none was provided the index function) are called.

From the User Guide:
index function
Quote:The "index" function is always loaded by default if the second segment of the URI is empty.
Class constructor:
Quote:Constructors are useful if you need to set some default values, or run a default process when your class is instantiated. Constructors can't return a value, but they can do some default work.
#12

[eluser]ndchris[/eluser]
[quote author="waldmeister" date="1278338014"]
Class constructor:
Quote:Constructors are useful if you need to set some default values, or run a default process when your class is instantiated. Constructors can't return a value, but they can do some default work.
[/quote]

As waldmeister wrote, you could use the constructor to do some default work.

Like anything you have to do for every method your controller provides.
Like loading models, libraries or config files, which you'll need for every method in the controller. Or fetching some data, or handle sessiondata, etc..
So you don't need to do that explicitly in each method.
#13

[eluser]skaterdav85[/eluser]
thanks waidmeister and ndchris for clearing that up and providing the resources!
#14

[eluser]TheIgniter[/eluser]
%-P congrat
#15

[eluser]minerbog[/eluser]
I know I'm late on this but I always use the __construct to load my models and set any default variables.

Gav
#16

[eluser]JasonS[/eluser]
I know this has been answered but there is a more obvious answer.

The __construct function is called every time the class is instantiated. If you used it for the index controller it would also be run by default before every other controller. This is why it CANNOT be used.

To be honest the index controller makes sense. index.ext is the default file run in a directory. Makes sense to have it as the default function to be called in a class if no other is specified.

The __construct function can be used like minerbog said. To load resource's that all/majority of your controller's require.




Theme © iAndrew 2016 - Forum software by © MyBB