Laravel4 中的多租户 [英] Multi-tenant in Laravel4

查看:23
本文介绍了Laravel4 中的多租户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个多租户应用程序,使用子域来分隔用户.例如.myapp.com

I'm building a multi-tenant app, using the subdomain to separate the users. e.g. .myapp.com

我也想给每个租户自己的数据库.

I want to give each tenant their own database too.

如何检测子域并动态设置数据库?

How can I detect the subdomain and set the database dynamically?

另外,下面的代码来自官方文档,向我们展示了在设置路由时如何获取子域.但是我们如何将子域值传递给控制器​​函数呢?

Also, the code below is from the official documentation and shows us how we can get the subdomain when setting up a route. But how do we pass the subdomain value to a controller function?

Route::group(array('domain' => '{account}.myapp.com'), function()
{

    Route::get('user/{id}', function($account, $id)
    {
        //
    });

});

推荐答案

实现这一点的最佳方法是在应用到路由组的前置过滤器中.

The best way to achieve this would be in a before filter that you apply to the route group.

Route::group(['domain' => '{account}.myapp.com', 'before' => 'database.setup'], function()
{
    // Your routes...
}

这个前置过滤器得到一个 $route 参数和一个 $request 参数给它,所以我们可以使用 $request 来获取主持人.

This before filters gets a $route parameter and a $request parameter given to it, so we can use $request to get the host.

Route::filter('database.setup', function($route, $request)
{
    $account = $request->getHost();
}

然后您可以使用该帐户在过滤器中使用 Config::set 调整默认数据库连接.也许您需要先使用默认连接来获取用户数据库详细信息.

You could then use the account to adjust the default database connection using Config::set in the filter. Perhaps you need to use the default connection first up to fetch the users database details.

$details = DB::details()->where('account', '=', $account)->first();

// Make sure you got some database details.

Config::set('database.connections.account', ['driver' => 'mysql', 'host' => $details->host, 'database' => $details->database, 'username' => $details->username, 'password' => $details->password]);

Config::set('database.connections.default', 'account');

在运行时创建一个新的数据库连接,然后将默认连接设置为新创建的连接.当然,您可以保留默认设置,只需将所有模型上的连接设置为 account.

During runtime you create a new database connection and then set the default connection to that newly created connection. Of course, you could leave the default as is and simply set the connection on all your models to account.

这应该会给你一些想法.请注意,此代码均未经过测试.

This should give you some ideas. Please note that none of this code was tested.

此外,控制器上的每个方法都将接收域作为第一个参数.因此,如果您期望其他参数,请务必进行调整.

Also, each method on your controllers will receive the domain as the first parameter. So be sure to adjust for that if you're expecting other parameters.

这篇关于Laravel4 中的多租户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆