我试图理解依赖注入,理论上,我理解它,但是,我想做一个例子来帮助我。但是,我得到了以下错误
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类的UserService是一个有效的UserModel对象(很明显,它输出了一个数组)。
我遗漏了什么?有什么事情我没解释清楚吗?
哦,这是composer.json文件
{
"require": {
"pimple/pimple": "~3.0"
},
"autoload": {
"psr-4": {
"Main\\" : "./"
}
}
}我创建了一个gitHub链接,这样项目就可以签出并运行,而不必复制所有内容(https://github.com/gitKearney/pimple-example)。
解决方案
问题是我在这一行里多了一个新的
$myUserService = new $container['UserService'];太明显了,我看不见
发布于 2017-08-30 23:00:22
$container['UserService']已经是一个UserService对象。检查您的服务定义:
$container['UserService'] = function ($c) {
return new UserService($c['UserModel']);
};这将$container['UserService']在被调用时设置为return new UserService($c['UserModel']),对吗?
您的代码基本上如下:
$o1 = new UserService($c['UserModel']);
$o2 = new $o2;发布于 2017-08-31 17:03:50
您可以使用依赖注入容器将自己从操作对象依赖关系的痛苦中解脱出来。创建一个新的UserService是不必要的(如果它真的是一个服务)。在这种情况下,您只需在$container中定义一次,并在需要时使用它。
因此,您不必创建一个新的UserService对象并调用其方法parseGet() (您在代码中所做的),您可以这样做:
$myResult = $container['UserService']->parseGet();当您定义如下内容时:
$container['UserService'] = function ($c) {
return new UserService($c['UserModel']);
};--当您尝试访问$ UserService‘UserService’时,您正在告诉Pimple如何处理UserService的创建
这就是为什么将依赖项定义为函数的原因。
这可能与你的问题Why use a closure for assignment instead of directly assigning a value to a key?有关
https://stackoverflow.com/questions/45970659
复制相似问题