dimanche 3 juillet 2022

many dependencies in switch context in strategy design pattern

i used strategy design pattern and i have a problem with many dependencies while instantiating in passed cases in switch . is there any a clean solution for not passing these dependencies?

this my credit service:

class CreditService
{
    public function addCredit($transaction)
    {
        $creditContext = new CreditContext();
        $creditStrategy = $creditContext->setStrategy($transaction->transaction_type);
        $creditStrategy->add($transaction->id);
    }
}

and this is my CreditContext with many dependencies in EmployerTransactionService and in TransactionService

class CreditContext
{
    /**
     * @param $strategy
     * @return InvoiceStrategy|UserStrategy
     * @throws \Exception
     */
    public function setStrategy($strategy)
    {
        switch ($strategy) {
            case User::class:
                return new UserStrategy(
                    new EmployerTransactionService(new TransactionService(dependencies..),dependencies..);
            case Proposal::class:
            case Milestone::class:
                return new InvoiceStrategy(
                    new TransactionService(
                        new PaymentService(new PaymentRepository(), new CreditRepository(), new TransactionRepository()),
                        new TransactionRepository(),
                        new CreditRepository(),
                        new IncomeReportService(new IncomeReportRepository()),
                        new CreditService())
                );
            default:
                throw new \Exception('not found strategy');
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire