Laravel 多个数据库的资源控制器和模型相同

Laravel resource controller and model the same for multiple databases

有什么方法可以对多个数据库使用相同的控制器和模型?

例如,我有一个 Product 模型和一个 ProductController(带有 index,show,store,update,destroy 的 CRUD 资源控制器)。数据库、模型和控制器是相同的。

我发现更改连接的唯一方法是在模型中 protected $connection = 'connection_name'; 但是我需要为每个模型复制 ProductController。

我正在考虑将 ProductController 设为 BaseProductController 并为每个数据库扩展它,但我不知道如何设置连接。

您可以使用 resolving 挂钩

在您的产品模型上使用依赖注入

在服务提供商中:

use App\Product;

$this->app->resolving(Product::class, function ($product, $app) {
    $request = $app['request'];
    if ($request->isConnection1()) {
        $product->setConnection('connection1');
    }
    elseif ($request->isConnection2()) {
        $product->setConnection('connection2');
    }
});

我的例子显然行不通,因为我不知道你的语境,但它给你指明了思路。

另一种方法是在 ProductController 周围的路由中添加一个中间件,它设置数据库默认连接(未指定时由您的模型使用)

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Database\ConnectionResolverInterface as DatabaseManager;

class SwitchConnection
{
    protected $dbManager;

    public function __construct(DatabaseManager $dbManager)
    {
        $this->dbManager = $dbManager;
    }

    public function handle($request, Closure $next, string $connection)
    {
        $this->dbManager->setDefaultConnection($connection);
        return $next($request);
    }
}

顺便说一句,如果您将此中间件别名为switch.connection并将switch.connection:connection1添加到路由的中间件,它会自动切换,因此您可以使用相同的控制器。