php - Laravel SOLID 使用存储库模式

标签 php laravel

我想(此刻很累)遵循 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/

相关文章:

laravel - 如何对部分Elasticsearch查询进行全文搜索匹配

php - 在 Laravel 中,如何在一秒钟内发出并发请求时避免重复记录

javascript - 自动更新 slider jquery内的div内容

PHP、Mysqli、SQL查询获取值并显示其他

php - 无法在xampp中显示图像

installation - Laravel 4 中的 session ID 太长或包含非法字符

Laravel - Cockroach DB - 自动增量正在生成 UUID

javascript - 当我通过 php 包含 datepicker js 和 css 文件时,包含不起作用,但如果我将所有代码放在单个 php 页面中,则可以工作

php - 处理订单邮件模板中基于产品类别的条件显示

php - 在 Laravel 中使用 Eloquent 访问特定列