由于我试图在phpunit的帮助下在Fatfree框架中编写单元测试,因此我遇到了依赖注入的问题。我试图将sql对象传递给调用类的构造函数,使其工作我调整了路由逻辑,如下所示:
routes.php文件
<?php
return array(
"/index/something" => array(
'class' => 'IndexController',
'action' => 'index',
'method' => 'GET',
'requireDependency'=> 0,
'mapper' => ''
),
"/@action/@name" => array (
'class' => "RandomController",
'action' => 'index',
'method' => 'GET',
'requireDependency'=> 1,
'mapper' => 'environment')
);
的index.php
<?php
require('vendor/autoload.php');
// Retrieve instance of the framework
$f3=require('lib/base.php');
// Initialize
$f3->config('config/config.ini');
$configs = require 'config/routes.php';
/**
* Dependency Injection for SQLMapper
*/
foreach ($configs as $url => $customParams) {
$f3->mset(
array(
'class' => $customParams['class'],
'action'=> $customParams['action'],
'mapper'=> $customParams['mapper'],
'requireDependency' => $customParams['requireDependency']
)
);
$methodandUrl = $customParams['method']." ".$url;
$f3->route(
$methodandUrl,
function ($f3, $params) {
$sqlMapper = "";
$class = $f3->get('class');
$hasDependency = $f3->get('requireDependency');
if($hasDependency) {
$dependency = new DependencyController();
$sqlMapper = $dependency->returnSQLMapper($f3);
}
if(!empty($sqlMapper))
$object = new $class($f3, $sqlMapper);
else
$object = new $class($f3);
if(empty ($params['action']))
$action = $f3->get('action');
else
$action = $params['action'];
call_user_func(array($object, $action), $f3);
});
}
// Execute application
$f3->run();
IndexController.php
<?php
class IndexController {
protected $db = "";
public function index($f3) {
$view=new View;
echo $view->render('index.htm');
}
}
RandomController.php
class RandomController {
protected $className, $dp;
public function __construct($f3,$dependency) {
$this->className = $f3->get("PARAMS.name");
$this->dp = $dependency;
}
public function index($f3) {
$view=new View;
$f3->set('name', $this->className);
echo $view->render('template.htm');
}
}
所以当我运行“index / something”时,它应该调用我的索引函数,但是它调用了RandomController索引函数。我不确定我哪里出错了,有人能帮助我吗?
更新
或者还有其他方法可以进行依赖注入吗?
答案 0 :(得分:1)
我弄明白了这个问题,
$f3->mset(
array(
'class' => $customParams['class'],
'action'=> $customParams['action'],
'mapper'=> $customParams['mapper'],
'requireDependency' => $customParams['requireDependency']
)
);
当我在循环中设置它时,它总是调用最后一个路径,因为它用于覆盖前一个路径。所以我把它移到了循环中,如下所示
$f3->set('url', $configs);
这将保存整个routes.php,并且还会更改
$urls = $f3->get('url');
foreach($urls as $url => $config){
if($f3->build($url) == $params[0]){
$f3->mset(array(
'class' => $config['class'],
'action' => $config['action'],
'requireDependency' => $config['requireDependency'],
'mapper' => $config['mapper']
));
break;
}
}
因此,该类并未完全映射到输入的URL。