-1

Question:

// TODO: add $name to $models array in Controller class

How to add $name from function model() in Load class to $models array in Controller class ?

Note: I have Load and Controller classes in separated files.

PHP:

<?php

class Controller {

    public $models = array();
    public $load;

    //TODO: for each model create instance
    // public $name;

    public function __construct() {
        $this->load = new Load();

        // TODO: for each model create instance
        // $this->name = new Name();
    }

}

class Load {

    public function model($name) {
        require(APP_DIR . 'models/' . strtolower($name) . '.php');
        $model = new $name;
        // TODO: add $name to $models array in Controller class
        return $model;
    }

}

Edit:

My Goal: If I load model in Controller as this: $this->load->model('model_name'); then I want to have instance of that loaded model as $this->model_name->method();

Damien Overeem
  • 4,487
  • 4
  • 36
  • 55
Ing. Michal Hudak
  • 5,338
  • 11
  • 60
  • 91

1 Answers1

0

Since you are not using any local properties in the Load class, you could make the model method static:

public static function model($name) {
    require(APP_DIR . 'models/' . strtolower($name) . '.php');
    $model = new $name;
    // TODO: add $name to $models array in Controller class
    return $model;
}

You can then call that method from your Controller class as follows:

$model = Load::model($name);



Update:

You commented:

If I load model somewhere I want to create instance in Controller so I can then use model as $this->model_name->method();

You can use the magic method __get (documentation) to access your model in such a way.

Add the following method to your Controller class:

public function __get($model) {
    return Load::model($model);
}

After adding this function $this->model_name->somemethod() will work in your Controller.

Obviously this needs some fine tuning, but it will do what you want.

Damien Overeem
  • 4,487
  • 4
  • 36
  • 55
  • 1
    If I load model in Controller as this: `$this->load->model('model_name');` then I want to have instance of that loaded model as `$this->model_name->method();` – Ing. Michal Hudak Nov 14 '13 at 14:21
  • See updated answers. Magic method __get will do this for you. Just find tune it to your wishes. You could ofcourse do the loads earlier and store them in in a array property, and then adjust the __get method to return models from that array only if they exist. – Damien Overeem Nov 14 '13 at 14:26
  • 1
    Is this good example what I am trying to achieve ? [http://stackoverflow.com/a/3652341/1183662](http://stackoverflow.com/a/3652341/1183662) – Ing. Michal Hudak Nov 14 '13 at 14:43
  • You can use `class_exists` before doing the require yes. Otherwise you would require it even if it was already loaded. – Damien Overeem Nov 14 '13 at 18:05