If I give the same name to a function in the Model of Codeigniter, that function gets called automatically when I load the model.
//controller
$this->load->model('my_model');
//model
class My_model extends CI_model {
function my_model {
}
}
In this case I don't have to call my model function like this
$this->my_model->my_model();
because loading the model calls the function as well.
Can somebody explain this behaviour? I haven't found anything in docs regarding this.
This is a common concept in Object-Orientated programming. The function is acting as a Constructor. The constructor is called when an instance of the object is created.
In PHP using the __construct() method is the advised way to declare a constructor for the class. However, in PHP 4, a constructor was declared using the class name, so:
For backwards compatibility, if PHP 5 cannot find a __construct()
function for a given class, and the class did not inherit one from a
parent class, it will search for the old-style constructor function,
by the name of the class.
In CodeIgniter, a model is a class. As you don't have a __construct() method in your class, PHP is treating your my_model function as the constructor for the class (as it is the same as the class name).
You may want to the following method to your model. This will stop my_model being treating as a constructor.
function __construct()
{
// Call the Model constructor
parent::__construct();
}
I'd personally avoid calling a method the same name as the class in PHP, as it can lead to this confusion! PHP's docs have some useful information on constructors.
Related
I currently have an abstract class which i am extending to other controllers. I have a abstract function within the abstract class which takes the value and places it in the __construct.
abstract class Controller extends BaseController {
abstract public function something();
public function __construct(Request $request) {
if (!is_null($this->something())){
$this->global_constructor_usse = $this->something();
}
}
}
My problem is that, on controllers that don't require this abstract function, I am having to place in the empty function.
class ControllerExample extends Controller {
public function something(){
return 'somethinghere';
}
}
Is there anyway to making the abstract function optional, or have a default value?
class EmptyControllerExample extends Controller {
public function something(){}
}
It is not possible to have a abstract method optional, as it is implied in PHP that all abstract methods must have an implementation.
There are legit use cases for optional abstract methods, yes: event handlers, metadata describers, etc. Unfortunately, you'll need to use regular, non-abstract methods with an empty body, and indicate in PHPDoc that they will do nothing unless extended.
Be wary, though: this can very quickly turn into code smell by diffusing a class responsability with their children. If you're dealing with generic events, you can look into Laravel's own event system, or the Observer pattern instead.
Abstract functions in a parent class, should only be used if its required by your application to implement the following method in all controllers who inherits from it, clearly it is not the case.
In this case i would make a trait. Here you create a trait which can be implemented by the classes who needs it. Notice the use keyword usage, use somethingTrait;
trait SomethingTrait
{
public function something()
{
echo "something called";
}
}
class Controller
{
use SomethingTrait;
public function run()
{
$this->something();
}
}
phpfiddle link
Another aproach could be doing a class inheritance structure, if the controllers you want to implement the methods has something in common. Where you would implement your special method in CrmController, where you still would be able to create shared methods in the abstract controller.
AbstractController
|
CrmController
|
CompanyController
For your question, 'Is there anyway to making the abstract function optional or have a default value?' No, and you are down the wrong path if you are trying to make abstract function optional. Hope my suggestions can help.
Here is the constructor invocation. There is nothing is passed or no function is called in constructor. why it is called?
class admin_login_model extends CI_Model {
function __construct() {
parent::__construct();
}
on controller
class admin_login extends CI_Controller {
function __construct() {
parent::__construct();
// if(!$this->session->userdata('validated')) redirect('admin/admin_login');
}
}
checking every page user session exist or not .like this .if you use the constructor .when every page calling constructor execute first and give out put true. then go to the function so that there we checking user session exist or not like this checking
See the "extends" keyword on all your controller and model classes. It's basic OOP or object oriented programming. Extends means the class you create uses functionallity and attributes declared in the extended class. But to do so, the extended class must also be instantiated. Is that understandable? It's a basic pattern of OOP.
https://en.m.wikipedia.org/wiki/Inheritance_(object-oriented_programming)
I am trying to understand one PHP OOP concept, lets say i have two classes A and B. B extends A there fore A is Base/Parent class. If class A has a __construct class B will automatically inherit it...?
Example:
class Car
{
public $model;
public $price;
public function __construct()
{
$this->model = 'BMW';
$this->price = '29,00,00';
}
}
class Engine extends Car
{
parent::__construct();
}
By parent::__construct(); class Engine will execute Car __construct(); automatically?
But I always though if I inherit from parent class the __construct will be executed automatically anyway why would I add this parent::__construct()?
When one class extends another, it inherits all its methods. Yes, that includes the constructor. You can simply do class Engine extends Car {}, and Engine will have a constructor and all other properties and methods defined in Car (unless they're private, which we'll ignore here).
If you define a method of the same name as already exists in Car in Engine, you're overriding that method implementation. That's exactly what it sounds like: instead of Car's implementation, Engine's method is called.
why would I add this parent::__construct()?
If you're overriding a method, yet you also want to call the parent's implementation. E.g.:
class Engine extends Car {
public function __construct() {
parent::__construct();
echo 'Something extra';
}
}
Overriding a constructor in a child class is exactly that, overriding... you're setting a new constructor for the child to replace the parent constructor because you want it to do something different, and generally you won't want it to call the parent constructor as well..... that's why you need to explicitly call the parent constructor from the child constructor if you want them both to be executed.
If you don't create a child constructor, then you're not overriding the parent constructor, so the parent constructor will then be executed
I'm stuck into a problem with traits I can't solve on my own.
I have classes extending an abstract class (in my case these are several controller classes and an abstract class Controller, the used framework won't be important here, since this is a general PHP question…) that uses traits. I'd like to override a method defined in one of the traits. This only works as long as I define the method in my sub-classes but not in my abstract class.
So, this one works perfectly:
class MyController extends Controller
{
use AnyTrait;
public function anyMethodFromAnyTrait()
{
// override AnyTrait::anyMethodFromAnyTrait()
}
}
I also know how to call the anyMethodFromAnyTrait method from AnyTrait by using as.
class MyController extends Controller
{
use AnyTrait { AnyTrait::anyMethodFromAnyTrait as method }
public function anyMethodFromAnyTrait()
{
// invoke AnyTrait::anyMethodFromAnyTrait()
$this->method();
}
}
Both work like a charm.
But my problem is a bit different.
When using the trait and defining the method in my abstract class I am not able to override the trait's method.
Assume the following controller class:
class MyController extends Controller
{
public function anyAction()
{
// let's see what happens…
$this->anyMethodFromAnyTrait();
}
}
…and the abstract one that's extended by MyController:
abstract class Controller
{
use AnyTrait
public function anyMethodFromAnyTrait()
{
// do something different than AnyTrait
}
}
…And this is what's not working at all. Whenever I call $this->anyMethodFromAnyTrait() within MyController the trait's method as implememented in AnyTrait will be invoked. The same named method in my abstract Controller will be ignored.
Therefore I only can override a trait's method in a concrete sub-class but not in an abstract class that is extended by that sub-class.
So the method definitions in traits get a higher priority by PHP than the same method definitions in abstract classes.
Do you know any workaround for that behaviour?
One workaround would be to use the traits ONLY in the subclasses.
PHP always prefers the trait methods over the "local" ones.
The reason why it works in subclasses is, that the trait method of the superclass is extended, not the trait usage itself.
I call a CodeIgniter controller method -imgupload- from jquery ajax. This controller extends my custom front controller.
class newad extends My_Controller{
public function __construct() {
parent::__construct();
}
public function imageupload() {
$this->load->library("uploadhandler");
}
The imgupload method calls the uploadhandler class which extends from newad.
class uploadhandler extends newad {
The functionality of that class works properly, except for one thing, I cant access the properties of the My_Controller class, even though they are declared protected.
The inheritance chain looks like this: My_Controller->newad->uploadhandler.
Any idea why I cant access those properties?
In short the answer is you do not need to extend Controller class here. You can just pass the value to your library as a parameter.
$params = array('user_ud' => $this->userID, 'otehr' => 'other');
$this->load->library('uploadhandler', $params);
//Now from your library
class uploadhandler{
public function __construct($params)
{
// Do something with $params
}
//.. Your code...//
}
Now about your question:
The functionality of that class works properly, except for one thing, I cant access the properties of the My_Controller class, even though they are declared protected. The inheritance chain looks like this: My_Controller->newad->uploadhandler. Any idea why I cant access those properties?
As inheritance chain are ok, you can access property of My_Controller from your library but not the value of the Current controller, because these two are different object.
So here is my answer how can we access the value? One way I have already mentioned. That will be enough if you need to share some property with the library. But what if you need to access all the Controller instance. There is a function to get the reference of controller instance get_instance(). You can use this function anywhere and get access of all public property controller. If you need to access any private property of controller the define a geter function to access that.
Explanation
First of all you need to learn basic about OOP. Learn about Class, Object, Inheritance..
When I said property of My_controller is different from the same property the you accessed from uploadhandler, it may confused you if you are not familiar with class and object. Here is two instance(object) of different class.
For short let say you have some classes like: Vehicle, Car, Machine and Person. All they have common attributes say name, weight ..
So, can we just inherit Any of these class from other??
Simple answer is no. We can't(!) define a Person class extending from Others. So how can we decide which incoherence would legal. If you can say Foo is a Bar you can write Foo class extending from Bar. Now from your case, It is obvious uploadhandler is not a controller. So Never Extend a anything from something that is not something.
NB: The answer is generic. If you need any specific clarification, just ask, I can update my answer