MVC 设置中的依赖注入示例,如下所示:
索引.php
$container = new Container();
include_file('container.php');
容器.php
container.add("database.driver", "mysql");
container.add("database.name","app");
...
$container.add(new Database($container->get('database.driver', "database.name")), 'database');
$container.add(new Dao($container->get('database')), 'dao');
$container.add(new Service($container->get('dao')));
$container.add(new Controller($container->get('service')), 'controller');
$container.add(new FrontController(),'frontController');
index.php 在这里继续:
$frontController = $container->get('frontController');
$controllerClass = $frontController->getController($_SERVER['request_uri']);
$controllerAction = $frontController->getAction($_SERVER['request_uri']);
$controller = $container->get('controller');
$controller->$action();
有了它,控制器依赖于一个服务层对象,该对象依赖于一个依赖于数据库对象的 dao(数据访问对象)对象,该对象依赖于数据库驱动程序、名称等