php - 检测到服务的循环参考
问题描述
我有一个简单的类,如下所示:
<?php
namespace App\Algorithm;
use App\Dao\MatchDao;
use App\Service\MatchService;
class Calculator {
private $users;
private $matchDao;
function __construct(MatchService $matchService, MatchDao $matchDao) {
$this->users = $matchService->users;
$this->matchDao = $matchDao;
}
public function hourlyRate() {
$query = $this->matchDao->getSingleColumn('Payment', 'hourly_rate', 32);
var_dump($query);
}
}
但我收到以下错误消息:
检测到服务“App\Algorithm\Calculator”的循环引用,路径:“App\Algorithm\Calculator -> App\Service\MatchService -> App\Algorithm\Calculator”。
匹配服务.php
<?php
namespace App\Service;
use App\Algorithm\Calculator;
use App\Algorithm\Collection;
class MatchService {
public $users;
private $collection;
private $calculator;
function __construct(Collection $collection, Calculator $calculator) {
$this->collection = $collection;
$this->calculator = $calculator;
}
public function getMatch($data) {
$this->users = $this->collection->getAllUsers($data);
$this->calculator->hourlyRate();
return 1;
}
}
问题是MatchService
,但我到底做错了什么?
解决方案
正如一些人指出的那样,循环依赖来自于您试图将 Calculator 注入 MatchService 并同时将 MatchService 注入 Calculator 的事实。在创建另一个之前无法创建一个。
再深入一点,Calculator 似乎正在使用 MatchService 来获取用户列表。作为第二个问题,计算器试图在 MatchService 生成用户之前获取用户。
这是一种可能的重构:
class Calculator
{
private $matchDao;
public function __construct(MatchDao $matchDao)
{
$this->matchDao = $matchDao;
}
public function getHourlyRate($users) // Added argument
{
$query = $this->matchDao->getSingleColumn('Payment', 'hourly_rate', 32);
}
}
class MatchService
{
private $collection;
private $calculator;
public function __construct(Collection $collection, Calculator $calculator)
{
$this->calculator = $calculator;
$this->collection = $collection;
}
public function getMatch($data)
{
$users = $this->collection->getAllUsers($data);
$this->calculator->getHourlyRate($users);
}
}
从 Calculator 的构造函数中删除 MatchService 解决了循环依赖问题。将 $users 传递给 getHourlyRate 解决了在用户可用之前尝试获取用户的问题。
这当然只是一种可能的解决方案。从您发布的代码中不清楚 Calculator 是否真的需要 $users 。
推荐阅读
- jquery - BxSlider 没有在谷歌浏览器中显示图像
- python - 如何从其他 2 个列表中创建元素列表
- macos - MacOS的TTrayIcon?
- flutter - 如何捕捉颤动的 video_player 插件错误?
- excel - 如何在列中查找多个值并返回结果?我尝试使用数组公式,但它导致 Excel 渲染速度太慢
- spring - 当我使用 modelAttribute="student" 时,如何修复“HTTP 状态 500 – 内部服务器错误”
- java - Spring Data REDIS - 具有奇怪前缀的哈希键,并且 HSCAN 无法正确返回结果
- java - 将大型机签名字符转换为Java中相应整数值的最佳方法是什么
- c# - 如何使序列化数据紧凑?
- syntax-highlighting - nano 可以通过 shebang 检测没有扩展名的文件类型以进行正确的语法突出显示吗?