主类和控制器加载器

时间:2013-05-27 19:45:36

标签: php oop controllers

我正在尝试学习OOP而且只是为了测试我想用不同的方法创建一个主类。在这种情况下,我想“加载”像CodeIgniter这样的控制器:

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

load()Main()的一种方法,但controller()呢?

这是我到目前为止所做的,但显然它不起作用。我无法理解如何将控制器名称传递给Load / controller类

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');

2 个答案:

答案 0 :(得分:4)

你可以试试这个

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.

答案 1 :(得分:0)

class Main 
{
    public function load()
    {
        $loader = new Load();
        $loader->controller('index');
    }
}
class Load 
{
    public function controller($class)
    {
        $test=new Test();
        $test->index();    
    }
}
class Test 
{
    function index()
    {
        echo "Hello";
    }
}
$main = new Main();
$main->load('test');