gpt4 book ai didi

php - Laravel SOLID 使用存储库模式

转载 作者:可可西里 更新时间:2023-11-01 13:17:13 24 4
gpt4 key购买 nike

我想(此刻很累)遵循 SOLID 原则,但我的思想要爆炸了。

为了遵循 SOLID 原则,我阅读了很多关于 Laravel 中的 Repository Pattern 的文章。我的问题与 this question 非常相似.但是我不明白如何才能不违反工厂模式

中的 Open/Closed Principal

我正在开发一个双因素身份验证系统,我有多种方法可以用作 tfa。

现在:

  • 身份验证器应用
  • 短信

让我们跳到代码:

Controller :(无出厂)

public function index(Request $request)
{
// Violate the OCP. I'm modyfing the class.
switch ($request->method) {
case 'authenticator':
$tfaMethod = new Authenticator;
break;
case 'sms':
$tfaMethod = new SMS;
break;
}

return (new TwoFactorMethod)->process($this->currentUser, $tfaMethod);
}

TwoFactorMethod 类:

public function process($user, MethodInterface $method)
{
return $method->process($user);
}

每个方法都有自己的类。没关系。但是,如果我想添加一个新方法,例如:E-mail,我将使用 switch case 打破类中的 OCP。

我怎样才能“修复”?还是我这边的误会?

谢谢!

最佳答案

您可以使用 TfaMethodRegisty,可能是这样的:

class TfaMethodRegistry
{
protected $methods = [];


public function register($name, $class)
{
$this->methods[$name] = $class;
}


public function get($name)
{
return $this->methods[$name];
}
}

然后您将其填充到您的 AppServiceProvider 中:

public function register()
{
$this->app->bind('App\TfaMethodRegistry', function ($app) {
$registry new TfaMethodRegistry;

$registry->register('sms', new Sms);
$registry->register('authenticator', new Authenticator);

return $registry;
});
}

然后你可以让 Laravel IoC-Container 注入(inject)你的 Controller 或任何你需要的地方:

public function index(Request $request, TfaMethodRegistry $registry)
{
$tfaMethod = $registry->get($request->method);

return (new TwoFactorMethod)->process($this->currentUser, $tfaMethod);
}

所以基本上您将可用方法视为配置,但也可以在运行时添加更多方法而无需编辑任何内容。

只是一个小提示:不要对此过于疯狂,也不要对整个 SOLID 事物过于虔诚。通常情况下,KISS比 SOLID 好多了 :)

关于php - Laravel SOLID 使用存储库模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46544936/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com