CodeIgniter Controller Constructor - php

I'm very new to codeigniter ,
I wanted to know what is the meaning of a constructor in a controller . I saw the following code in a codeigniter tutorial -
class upload extends CI_Controller {
function __construct() {
parent::__construct();
$this->load->helper(form);
}
// rest of the class...
My question is when is the constructor invoked - is it called every time the controller serves a request (e.g the controller class is instantiated for each request it receives?)

Well, that's a more general PHP question. Anyway, yes, the magic method __construct() is called (automatically) upon each instantiation of the class, as you can see in the manual: http://www.php.net/manual/en/language.oop5.decon.php
Usually, in CI is not necessary to call a constructor, unless you actually want one. In the example you posted, the code loads the helper on every instantiation of the class - which is the same as loading the helper in every method, just saves a lot of typing and ensures it's not forgotten. You can alternatively put the library/helper/model you want to have alywas loaded in the respective autoload array in config/autoload.php (check "autoloading" in CI's manual)
Once you define a constructor in your child Controller you're compelled to call the parent constructor (of the mail CI_Controller class), because there is where the main CI object is created and all the classes are loaded, and you need those in your child controller too; if fail to do so your child class will construct separately and won't inherit.
I hope I made myself clear, english is not my mothertongue :)

the constructor is magic Literally its called a magic method.
what makes the constructor cool is that it will do things for you BEFORE any of the methods. So if you have an admin class, and someone should be logged in in order to access it - you can check for login in the constructor and bounce them out if they are not authorized.
in the constructor you can load the models, libraries, helpers, etc that your class needs, and they will be available for any method in the class.
you can load in variables that are used by methods. this is really useful for models.

Don't use _construct() function in latest apache & codeigniter
Use helperlin in index() function

That's a general question. Constructor is a function that is automatically called when instantiated. this function helps us to intialize the things that we are going to need frequently in our code like when we have to load the models of helpers like form e.t.c.
$this->load->model('Model_name');
now when you write this line in your constructor you don't need to load this model again and again in your methods of that class.

Related

yii2 - can someone explain the meaning of parent::init(); statement

I have looked online for the meaning of parent::init(); . All I was able to find was that init() is to initialize some settings which want to be present every time the application runs.
Can anyone please explain the meaning of parent::init() in exact sense, like significance of both the words?
Thanks in advance.( I am sorry if its too simple! )
When we use parent::init(), we are just calling the parent method (in this case init()) inside a method of the current class.
About parent::
For example, let's say we have a class called MyClass. This class have a awesome method that runs alot of things:
class MyClass
{
public function runStuffs()
{
// trigger events, configure external stuff, adding default values to properties.
}
}
Now, after some time, we decided to create a new Class that extends from the first one. And we called MySecondClass:
class MySecondClass extends MyClass
{
}
It already have the method runStuffs(), but, for this second class, we need to do more things in this method, but maintaining what it have.
Sure we could rewrite the whole method and just copy and paste what we have in MyClass and add the new content. But this isn't elegant or even a good practice. what if later on We change the method in MyClass, you probably would like that MysecondClass have that changes too.
So, to solve that problem, we can call the parent method before write your new content:
class MySecondClass extends MyClass
{
public function runStuffs()
{
parent::runStuffs();
// do more things!
}
}
Now MySecondClass->runStuffs() will always do what its parent do and, after that, more stuff.
About the init() method.
init() is a method used in almost all classes from Yii2 framework (since most of then extends from yii\base\Object at some point) and works just like the __constructor() method (native from PHP). But there is some differences, you can read more here.
Actually the init() method is called inside the __constructor(), and the framework encorage us to use init() instead of __construct() whenever is possible.
Now if both are pretty much the same thing, why do they create this method? There is an answer for that here. (take a look at qiang's answer, from the dev team):
One of the reasons for init() is about life cycles of an object (or a component to be exact).
With an init() method, it is possible to configure an object after it is instantiated while before fully initialized. For example, an application component could be configured using app config. If you override its init() method, you will be sure that the configuration is applied and you can safely to check if everything is ready. Similar thing happens to a widget and other configurable components.
Even if init() is called within constructor rather than by another object, it has meaning. For example, in CApplication, there are preInit() and init(). They set up the life cycles of an application and may be overridden so that the customization only occurs at expected life cycles.
Conclusion
So, when you use a init() method and calls parent::init() you are just saying you want to add more things to that method without removing what it already was doing.
The parent::init(); Method is useful to execute a code before every controller and action,
With an init() method, it is possible to configure an object after it is instantiated while before fully initialized.
For example, an application component could be configured using app config.
If you override its init() method, you will be sure that the configuration is applied and you can safely to check if everything is ready.
Similar thing happens to a widget and other configurable components.
In Yii, init() method means that an object is already fully configured and some additional initialization work should be done in this method.
For More Information check this link :
https://stackoverflow.com/questions/27180059/execute-my-code-before-any-action-of-any-controller
Execute my code before any action of any controller
might be helpful to you.

Disable old-style constructors (PHP4-)

I am working on an MVC framework in PHP.
I have several controller classes called "index" with methods called "index" within them. The classes do not have __construct() methods.
Inevitably, this is resulting in PHP calling the "index" method as the constructor instead, using the old PHP4 convention of the constructor being the method with the same name as the class.
Is there any way to disable this behaviour or do I have to define an empty __construct() to prevent it? (Or just change my own coding style so I don't have methods with the same name as their classes.)
I want PHP5 to stop parsing for the PHP4 constructors essentially.
Ilmiont
I have been down the same road with MVC frameworks before and I have never heard of an index() function being called like this. Upon instanciation it will call the __constructor if present or do nothing. When calling your controller you should be geting the class and method name and checking if they exist and if they do then instantiate it. However if you have the same general setup as me you should have a registry storing all of your variables being passed to the controller when you create an instance, then when/if the view is called from index it should pass the altered registry to the view

How to load function from library on page load using codeigniter

I am doing my project using codeigniter
I want load a function when the page loads. i tried to give the function in __construct() but i need to call the function at every page.
So i want to call the function which is in library without calling from __construct()
Can anyone give me the solution for my problem
Take a look into the hooks. You can configure a function or a method of a class to be executed in various places in the life cycle of every request, depending in your needs.
If you need the controller instance for your functionality (the $this in most contexts) you probably need the post_controller_constructor one, and use the get_instance() to get a hold of the controller instance inside of the hook, to load in libraries or call models and such.
An other way could be that you extend the CI_Controller class with a MY_Controller class, place it under application/core/MY_Controller.php and move your code inside that classes __construct and use the MY_Controller as the base class of your regular controllers, as described the Creating Core System Classes page.
Add a library in autoload, then in that library file use __construct to call your function.

create construct in class inherited by model or controller

I'm a java programmer and now I want to learn CodeIgniter framework to apply to my php application. I saw many examples on the web and I have a question. When I create a model or a controller, I have to inherit from CI_Model and CI_Controller but my question is: do I have to always create the construct in every model o controller? So I mean I have to put in every class
function __construct()
{
parent::__constuct();
}
If you don't override the __construct, it is not necessary. But if you override it, you need to call parent::__constuct();, php will not call the parent constructor automatically.
The answer is no.
I don't know how is it in java. But in php if no construct method is found in the child class it will call the parent one

Zend: Execute something before a controller is executed

In my Zend framework project I want to check whether a cookie is set. If it is the case I want to use the cookie contents to login a user.
Since it is neccessary for me to do this automatic login before any controller is called I tried to put it in the Bootstrap. There I want to check the database if the user information is valid. Unfortunately at this point the default database adapter is not yet initialized.
So my question is the following: Where do I put those stuff that should be executed before any controller is called and after all initializing/bootstrapping stuff is done?
I'have not a great experience with Zend Framework but I think you should create a custom generic controller for example GenericController that extends the Zend_Controller_Action and put your code in the preDispatch() function. All your controllers will then a subclass of your custom controller, for example:
class GenericController extends Zend_Controller_Action{
function preDispatch(){
parent::preDispatch();
// put your code here
}
}
class FooController extends GenericController{
...
}
Use the methods:
init()
// and
preDispatch()
implement them in your class, init runs at creation, predispatch runs right before your action method iirc
api
On that page I linked above it states
Note: Usage of init() vs. preDispatch()
In the previous section, we introduced the init() method, and in this section, the preDispatch() method. What is the difference between them, and what actions would you take in each?
The init() method is primarily intended for extending the constructor. Typically, your constructor should simply set object state, and not perform much logic. This might include initializing resources used in the controller (such as models, configuration objects, etc.), or assigning values retrieved from the front controller, bootstrap, or a registry.
The preDispatch() method can also be used to set object or environmental (e.g., view, action helper, etc.) state, but its primary purpose is to make decisions about whether or not the requested action should be dispatched. If not, you should then _forward() to another action, or throw an exception.
Note: _forward() actually will not work correctly when executed from init(), which is a formalization of the intentions of the two methods.

Categories