首页 > 解决方案 > 检测到服务的循环参考

问题描述

我有一个简单的类,如下所示:

<?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,但我到底做错了什么?

标签: phpsymfonysymfony4

解决方案


正如一些人指出的那样,循环依赖来自于您试图将 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 。


推荐阅读