策略设计模式中开关上下文中的许多依赖项
我使用了策略设计模式,并且在Switch中通过的案例实例化时有许多依赖项问题。是否有干净的解决方案不通过这些依赖性?
这是我的信用服务:
class CreditService
{
public function addCredit($transaction)
{
$creditContext = new CreditContext();
$creditStrategy = $creditContext->setStrategy($transaction->transaction_type);
$creditStrategy->add($transaction->id);
}
}
这是我的CreditContext,在sumpleerertransactionservice
和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');
}
}
}
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');
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您必须使用依赖项注入容器这是解决所有问题的解决方案,
最终您的最终代码最终是看起来像这样
You have to use Dependency Injection Container which is the solution to all your problems
Your final code ultimately will be look like this