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

查看:66
本文介绍了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)
    {
        //
    });

});

推荐答案

最好的方法是在应用于路由组的before过滤器中.

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天全站免登陆