【发布时间】:2018-02-08 18:32:49
【问题描述】:
我正在尝试理解依赖注入,理论上我明白了,但是,我想举一个例子来帮助我。但是,我收到以下错误
PHP Fatal error: Uncaught ArgumentCountError: Too few arguments to function Main\Services\UserService::__construct(), 0 passed
in ...
这是我的“主”文件,我将其命名为 index.php
<?php
#index.php
require_once 'vendor/autoload.php';
use Main\Controllers\UserController;
use Main\Services\UserService;
use Main\Models\UserModel;
use Pimple\Container;
$container = new Container;
$container['UserModel'] = function($c) {
return new UserModel();
};
$container['UserService'] = function ($c) {
return new UserService($c['UserModel']);
};
$container['UserController'] = function ($c) {
echo "creating a new UserController\n";
$aUserService = $c['UserService'];
return new UserController($aUserService);
};
$myUserService = new $container['UserService'];
$myResult = $myUserService->parseGet();
echo $myResult, PHP_EOL;
这是传递给服务的模型
<?php
# Models/UserModel.php
namespace Main\Models;
class UserModel
{
private $record;
public function getRecord()
{
return [
'first_name' => 'Bob',
'last_name' => 'Jones',
'email' => 'bj@example.com',
'date_joined' => '11-12-2014',
];
}
}
还有,这里是服务,它将模型作为构造函数参数
<?php
namespace Main\Services;
use Main\Models\UserModel;
class UserService
{
private $userModel;
public function __construct(UserModel $userModel)
{
echo "verifying that the userModel passed in was a valid UserModel\n";
$this->userModel = $userModel;
print_r($this->userModel->getRecord());
}
public function parseGet()
{
$retVal = $this->userModel->getRecord();
return json_encode($retVal);
}
}
所以,理论上,Pimple 应该能够实例化一个 UserService 对象。我什至验证了传递给 UserService 类的 UserModel 是一个有效的 UserModel 对象(很明显它打印出一个数组)
我错过了什么?有什么我没有解释的吗?
哦,这是 composer.json 文件
{
"require": {
"pimple/pimple": "~3.0"
},
"autoload": {
"psr-4": {
"Main\\" : "./"
}
}
}
我创建了一个 gitHub 链接,因此可以签出并运行该项目,而无需复制所有内容 (https://github.com/gitKearney/pimple-example)
解决方案
问题是我在行中有一个额外的 new
$myUserService = new $container['UserService'];
太明显了,我看不到
【问题讨论】:
-
将复制案例添加到 Github 的工作做得很好,顺便说一句。能够获取您的代码并运行它真的很有帮助。
-
当然!有什么可以帮到你的
标签: php dependency-injection psr-4 pimple