Disable old-style constructors (PHP4-) - php

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

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.

php class inheritance - is it necessary to run constructor on parent(s)

For my latest website I'm trying to use OOP. I'm using the project to develop my understanding of this technique. Previously I would 'include' a functions folder that contains various php files labelled things like image.upload.functions.php and general.error.handling.functions.php etc.
However, this time I'm using classes wherever possible.
I have just read that in order to use a parents methods (in an extended class) you must run the parents constructor however I haven't done this and my project seems to work ok.
So.. I have a class called Form Validation
I have another class called Process Login that extends Form Validation.
My Form Validation class does things like test a password strength to make sure it is strong enough, check whether a user is in the database etc.
I extend Form Validation with a Registration class and a Forgotten Passowrd class.
Should I be putting:
parent::_construct();
..in the constructor of each of the extended classes?
Could someone explain 'simply' the reasons why we do OR do not do this? And whether it's something I should be doing?
Many thanks :-)
Here's the link to official documentaion: constructors and destructors
And here's the quote:
Note: Parent constructors are not called implicitly if the child class defines a constructor. In order to run a parent constructor, a call to parent::__construct() within the child constructor is required. If the child does not define a constructor then it may be inherited from the parent class just like a normal class method (if it was not declared as private).
Calling parent constructor is NOT necessary. And, in general, it is not called implicitly, if You have defined constructor in Your own child class. But, if in the parent constructor You have a nice piece of logic or functionality, that You don't want to lose, then call parent's constructor from the child's one.
You call parent::__construct() (watch that there are two underscores) if you want to reuse the functionality of the constructor from the class you're extending.
The reuse of code is a main reason for inheritance in OOP. So if there is any algorithm in your parent class that you want to use, you have to call parent::__construct().
If you're extending the parent's constructor, you also have to call it before (or after) your own additions, e.g. like this
class A extends B {
public __constructor() {
parent::__construct();
// Your own code
}
}
If you don't want to use any of your parents' constructor functions, you don't inherit from that parent constructor - but I assume that in most cases you want to.

Need advice with design - changing static into normal methods

My whole project is basically divided into two parts:
core
helper classes
User creates his custom classes and uses methods from helper classes in there like:
\Project\System\Helpers\Class::foo();
So every public method in each helper class is declared as static. I've came up with an idea to change this, make all user custom classes inherit one special class:
class SingleBeingInheritedClass {
public function helper($class)
{
return new \Project\System\Helpers\$class; // it's just to show the idea
}
}
so that instead of calling static function, user could write:
$this->helper('class')->foo();
The problem is I use some of these helper classes inside a couple of core classes. And I don't want core classes to inherit anything related to helpers.
In these core classes I also don't want to make the code longer and initialize objects in every method using these helpers.
How should I handle this? Or maybe static methods aren't that bad here?
You wrote:
I also don't want to make the code longer and initialize objects in
every method using these helpers.
I you would like to avoid instantiating objects, then you shall stick to static methods. In my projects I use static methods for helpers, for the exact same reason.
These helper classes are then used as 'function libraries'. In this case, class is more like a namespace for the helper functions, not something which gets instantiated.

CodeIgniter Controller Constructor

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.

How does CodeIgniters dynamic loading class work?

I am trying to build my own simple MVC framework, mainly for educational purposes than anything else, I have used CodeIgniter in the past which has provided most of the inspiration for the features I would like to incorporate into my framework.
I would like to build a loader class like CodeIgniters, but I can't understand how CI loads the classes as if they are properties of the calling class i.e
class Random_Controller{
function __construct(){
$this->load->helper('some_class');
$this->some_class->do_something();
/*
How does CI load some_class as if it were a property of Random_Controller?
I can understand using something like $$class_name = new $class_name();
Or $$this->class_name = new $class_name();
But how can the dynamically named object be used with $this->?
*/
}
}
Hopefully that makes sense...
I am always surprised at how simple things appear with the right explanation. One more question though.
If $load is a reference to an instance of load class, and a record of all loaded classes is kept in an array, we are essentially doing:
$this->loaded_classes[$key]->do_something()?
So how does CI resolve the array to a variable name? I have seen some PHP magic methods that are called when variables do not exist or methods do not exist, would this be done in conjuction with these magic methods? In other words if the $this->some_class property does not exist we search for an element in the array with that key?
If that makes sense..
Uhm, well, let's start with this: the CI_Controller super class; it's the one all controllers extends, and acts as the CI superobject all the $this refer to.
CI_Controller acts as a singleton, and during initializing it calls a function, load_class() (you can find in core/common.php) which works as an autoloader : inside a static array ($_classes) it assignes as index the class name, and as value the class instance:
$_classes[$class] = new $name();
Then the companion is_loaded() function (in the same file) registers in an array all the function loaded, and is used to check later if the class has already been instantiated or not.
Ci_Controller assigns then to its $load property an instance of the Loader class (core/loader.php, by using the above mechanism)
$this->load =& load_class('Loader', 'core');
which, in turn, is responsibile for loading all other resources using its own methods: helper(),library(),model() and so on. Have a look at the source for all details, hope you got the picture though
To clarify as per your comment:
$load = new Loader();
$load->helper('helper');
would be the same as:
$this->load->helper('helper'),
as $this->load contains an instance (by reference) of the Loader class.
Then how the helper(),library(),etc methods of the Loader class work would be too much to write here, and beside you can open up the Loader.php file and have a look by yourself.

Categories