Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Extracting array with class as value

I'm developing an MVC framework and I have a problem with making a flexible code/Structure in declaring helper classes

class Controller {
    public $helper = [];

    public function load_helper($helper)    {
        require_once(DIR_HELPER . $helper . '.php');
        $lc_helper = StrToLower($helper);
        $helper_arr[$lc_helper] = new $helper;  
        $this->helper[$lc_helper] = $helper_arr[$lc_helper];    
    }
}

//I'm calling the function in my controllers like this

Class Home Extends Controller   {

    $this->load_helper('Form');

    $this->helper['form']-><class function>;
}

I want to call the function like this:

$this->form-><class function>;

I can't use extract for public functions but I've seen frameworks that can do it.

I hope someone has an idea and that someone can understand my question, thanks in advance.

like image 479
mendz Avatar asked May 04 '15 03:05

mendz


1 Answers

Take a look at the magic __get method. From the documentation:

Overloading in PHP provides means to dynamically "create" properties and methods. These dynamic entities are processed via magic methods one can establish in a class for various action types.

The overloading methods are invoked when interacting with properties or methods that have not been declared or are not visible in the current scope. The rest of this section will use the terms "inaccessible properties" and "inaccessible methods" to refer to this combination of declaration and visibility.

This could be implemented for example this way:

class Controller {
    public $helper = [];

    public function load_helper($helper)    {
        require_once(DIR_HELPER . $helper . '.php');
        $lc_helper = StrToLower($helper);
        $helper_arr[$lc_helper] = new $helper;  
        $this->helper[$lc_helper] = $helper_arr[$lc_helper];    
    }

    public function __get($property) {
        //Load helper if not exists
        if (!isset($this->helper[$property])) {
            $this->load_helper($property);
        }

        //Return the helper
        return $this->helper[$property];
    }
}

Side note:

Controller::$helper and Controller::load_helper() in my understanding should be private or protected instead of public.

like image 63
Christian Gollhardt Avatar answered Sep 23 '22 03:09

Christian Gollhardt