Home > Enterprise >  many dependencies in switch context in strategy design pattern
many dependencies in switch context in strategy design pattern

Time:07-04

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');
        }
    }
}

CodePudding user response:

You have to use Dependency Injection Container which is the solution to all your problems

Your final code ultimately will be look like this

class CreditContext
{
    protected $strategies = [
        User::class,
        Proposal::class,
        Milestone::class
    ];

    public function make($type)
    {
        if (in_array($type, $this->strategies, true)) {
            $container = Container::getInstance();

            return $container->get($this->strategies[$type]);
        }

        throw new RuntimeException('Strategy not found');
    }
}
  • Related