Rez*_*ati 7 php symfony symfony4
我有一个简单的类,如下所示:
<?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);
}
}
Run Code Online (Sandbox Code Playgroud)
但我收到以下错误消息:
检测到服务“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;
}
}
Run Code Online (Sandbox Code Playgroud)
问题是MatchService,但我到底做错了什么?
正如一些人指出的那样,循环依赖来自这样一个事实:您试图将 Calculator 注入到 MatchService 中,同时将 MatchService 注入到 Calculator 中。无法在创建另一个之前先创建一个。
更深入地观察,计算器似乎正在使用 MatchService 来获取用户列表。第二个问题是,Calculator 试图在 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);
}
}
Run Code Online (Sandbox Code Playgroud)
从计算器的构造函数中删除 MatchService 可以解决循环依赖问题。将 $users 传递给 getHourlyRate 解决了在用户可用之前尝试获取用户的问题。
这当然只是一种可能的解决方案。从您发布的代码中不清楚计算器是否真的需要 $users 。
| 归档时间: |
|
| 查看次数: |
11219 次 |
| 最近记录: |