Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

main class and controller loader

I'm trying to learn OOP and just for testing I want to create a main class with different methods. In this case, I want to "load" a controller like CodeIgniter:

$app->load->controller('test')

load() is a method of Main() but what about controller() ?

This is what I have so far, but obviously it is not working. I can't understand how to pass the controller name to the Load/controller class

class Main {
    public function load()
    {
        $loader = new Load();
        $loader->controller('index');
    }
}

class Load {
    public function controller($class)
    {
        $class = ucfirst($class);
        $class = new $class();
        $class->index();    
    }
}

class Test {
    function index()
    {
        echo 'class: test - method: index';
    }
}

$main = new Main;
$controller = $main->load->controller('test');
like image 997
handsome Avatar asked Mar 12 '26 07:03

handsome


1 Answers

You may try this

class Main {

    public function load()
    {
        //include "Load.php";
        return new Load();
    }

}

class Load {

    public function controller($class = '')
    {
        if( file_exists( $class . '.php') ) {
            include $class . '.php';
            $class = ucfirst($class);
            return new $class;
        }
    }

}

$main = new Main;
$controller = $main->load()->controller('testClass');
$controller->index(); // Assume testClass has an index method

DEMO.

like image 185
The Alpha Avatar answered Mar 13 '26 22:03

The Alpha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!