2016-07-05 169 views
1

我正在处理多租户应用程序,并且我想要做的事情之一是能够在组织/租户访问时动态切换数据库连接该应用程序通过使用其子域来识别租户。我正在使用多数据库方法而不是单数据库方法;到目前为止,我的实现通过在组织注册并为其运行所有必要的迁移时为组织创建数据库来自动配置环境。在Laravel 5上调用成员函数connection()null null

我遇到的问题与将tenant解出IoC容器并将数据库连接设置为默认值有关,因此组织/租户可以访问其数据。这就是我的AppServiceProvider.php类的register()方法是这样的:

/** 
* Register any application services. 
* 
* @return void 
*/ 
public function register() 
{ 
    App::bind('setDbConnection', function($app, $db) { 
     Config::set("database.connections.{$db[0]}", [ 
      'driver' => env('DB_CONNECTION'), 
      'host'  => env('DB_HOST'), 
      'port'  => env('DB_PORT'), 
      'database' => "{$db[0]}", 
      'username' => env('DB_USERNAME'), 
      'password' => env('DB_PASSWORD'), 
      'charset' => 'utf8', 
      'collation' => 'utf8_unicode_ci', 
      'prefix' => '', 
      'strict' => false, 
      'engine' => null, 
     ]); 
    }); 

    App::singleton('tenant', function() { 
     $server = explode('.', Request::getHost()); 

     if (count($server) === 3 && $server !== 'www') { 
      return Organization::where('slug', $server[0])->firstOrFail(); 
     } 
    }); 

    // dd(App::make('tenant')->slug); 

    if (! App::runningInConsole()) { 
     App::make('setDbConnection', [App::make('tenant')->slug]); 
     Config::set('database.default', App::make('tenant')->slug); 
    } 
} 

对于Organization.php模型,我明确地告诉它使用的mysql连接,但我曾评论说出来;这是一流的样子:

namespace App; 

use Illuminate\Database\Eloquent\Model; 

class Organization extends Model 
{ 
    // protected $connection = 'mysql'; 

    protected $fillable = ['name', 'slug']; 
} 

应该发生的是,如果一个组织来的应用程序,例如,samplecompany.example.com我会使用子域名samplecompany来查找组织中,然后切换连接在应用程序的生命周期中尽早使用该数据库,以便租户可以访问其信息。如果我在应用程序的其他地方使用相同的Organization模型,它可以很好地工作,但是当我在AppServiceProvider类的register()方法中使用它时,它根本无法解析连接。该测试中的域名是http://bestfinance.global.dev:8000

以下是完整的堆栈跟踪:

Whoops, looks like something went wrong. 

1/1 FatalThrowableError in Model.php line 3293: 
Call to a member function connection() on null 
1. in Model.php line 3293 
2. at Model::resolveConnection(null) in Model.php line 3259 
3. at Model->getConnection() in Model.php line 1880 
4. at Model->newBaseQueryBuilder() in Model.php line 1853 
5. at Model->newQueryWithoutScopes() in Model.php line 1823 
6. at Model->newQuery() in Model.php line 3503 
7. at Model->__call('where', array('slug', 'bestfinance')) 
8. at call_user_func_array(array(object(Organization), 'where'), array('slug', 'bestfinance')) in Model.php line 3519 
9. at Model::__callStatic('where', array('slug', 'bestfinance')) in AppServiceProvider.php line 52 
10. at AppServiceProvider->App\Providers\{closure}(object(Application), array()) in Container.php line 731 
11. at Container->build(object(Closure), array()) in Container.php line 629 
12. at Container->make('tenant', array()) in Application.php line 697 
13. at Application->make('tenant') in Facade.php line 217 
14. at Facade::__callStatic('make', array('tenant')) in AppServiceProvider.php line 59 
15. at AppServiceProvider->register() in Application.php line 554 
16. at Application->register(object(AppServiceProvider)) in ProviderRepository.php line 74 
17. at ProviderRepository- >load(array('Illuminate\Auth\AuthServiceProvider', 'Illuminate\Broadcasting\BroadcastServiceProvider', 'Illuminate\Bus\BusServiceProvider', 'Illuminate\Cache\CacheServiceProvider', 'Illuminate\Foundation\Providers\ConsoleSupportServiceProvider', 'Illuminate\Cookie\CookieServiceProvider', 'Illuminate\Database\DatabaseServiceProvider', 'Illuminate\Encryption\EncryptionServiceProvider', 'Illuminate\Filesystem\FilesystemServiceProvider', 'Illuminate\Foundation\Providers\FoundationServiceProvider', 'Illuminate\Hashing\HashServiceProvider', 'Illuminate\Mail\MailServiceProvider', 'Illuminate\Pagination\PaginationServiceProvider', 'Illuminate\Pipeline\PipelineServiceProvider', 'Illuminate\Queue\QueueServiceProvider', 'Illuminate\Redis\RedisServiceProvider', 'Illuminate\Auth\Passwords\PasswordResetServiceProvider', 'Illuminate\Session\SessionServiceProvider', 'Illuminate\Translation\TranslationServiceProvider', 'Illuminate\Validation\ValidationServiceProvider', 'Illuminate\View\ViewServiceProvider', 'App\Providers\AppServiceProvider', 'App\Providers\AuthServiceProvider', 'App\Providers\EventServiceProvider', 'App\Providers\RouteServiceProvider')) in Application.php line 530 
18. at Application->registerConfiguredProviders() in RegisterProviders.php line 17 
19. at RegisterProviders->bootstrap(object(Application)) in Application.php line 203 
20. at Application->bootstrapWith(array('Illuminate\Foundation\Bootstrap\DetectEnvironment', 'Illuminate\Foundation\Bootstrap\LoadConfiguration', 'Illuminate\Foundation\Bootstrap\ConfigureLogging', 'Illuminate\Foundation\Bootstrap\HandleExceptions', 'Illuminate\Foundation\Bootstrap\RegisterFacades', 'Illuminate\Foundation\Bootstrap\RegisterProviders', 'Illuminate\Foundation\Bootstrap\BootProviders')) in Kernel.php line 232 
21. at Kernel->bootstrap() in Kernel.php line 127 
22. at Kernel->sendRequestThroughRouter(object(Request)) in Kernel.php line 99 
23. at Kernel->handle(object(Request)) in index.php line 53 
24. at require_once('/Users/exampleuser/Sites/multitenant/public/index.php') in server.php line 21 

回答

0

为了解决我有问题,我所做的就是创建一个自定义服务提供商(我也很相信这会提供的AppServiceProvider类工作过)和移动我$this->app->singleton()$this->app->runningInConsole()boot()方法和我离开$this->app->bind('setDbConnection', ...)register()方法。有了这一切,我现在可以无缝地为我的所有租户加载相应的测试数据。

这里是我TenantServiceProvider类:

namespace App\Providers; 

use App\Organization; 
use Illuminate\Support\Facades\App; 
use Illuminate\Support\Facades\Config; 
use Illuminate\Support\Facades\Request; 
use Illuminate\Support\ServiceProvider; 

class TenantServiceProvider extends ServiceProvider 
{ 
    /** 
    * Bootstrap the application services. 
    * 
    * @return void 
    */ 
    public function boot() 
    { 
     $this->app->singleton('tenant', function($app) { 
      $server = explode('.', Request::getHost()); 

      if (count($server) === 3 && $server !== 'www') { 
       return Organization::where('slug', $server[0])->firstOrFail(); 
      } 
     }); 

     // dd(App::make('tenant')); 

     if (! $this->app->runningInConsole()) { 
      $this->app->make('setDbConnection', [$this->app->make('tenant')->slug]); 
      Config::set('database.connections', $this->app->make('tenant')->slug); 
     } 
    } 

    /** 
    * Register the application services. 
    * 
    * @return void 
    */ 
    public function register() 
    { 
     $this->app->bind('setDbConnection', function($app, $db) { 
      Config::set("database.connections.{$db[0]}", [ 
       'driver' => env('DB_CONNECTION'), 
       'host'  => env('DB_HOST'), 
       'port'  => env('DB_PORT'), 
       'database' => "{$db[0]}", 
       'username' => env('DB_USERNAME'), 
       'password' => env('DB_PASSWORD'), 
       'charset' => 'utf8', 
       'collation' => 'utf8_unicode_ci', 
       'prefix' => '', 
       'strict' => false, 
       'engine' => null, 
      ]); 
     }); 
    } 
} 

此外,我添加了一个Route::bind()我的路线文件来处理,当一个人试图加载不存在租客的情况。它看起来像这样:

Route::bind('tenant', function($value) { 
     $tenant = $this->app->make('tenant'); 

     if ($tenant->slug === $value) { 
      return $tenant; 
     } else { 
      return $this->app->abort(404); 
     } 
    }); 

原来的实施构建多租户应用这种方法是由Matthew MachugaTutsplus在Laravel 4.2完成。但是,我想在Laravel 5.2中做类似的事情,这是我遇到的一个小问题。我希望这可以帮助别人。

0

请问你注释掉dd(App::make('tenant')->slug);实际工作,并返回一个字符串的行?如果你将它传递到setDbConnection那么'database' => "{$db[0]}",听起来不正确,如果它是一个字符串,那只会给你slu first的第一个字母。

+0

不,它不会返回任何东西,我不断收到上面突出显示的错误。我只是在检查,看看我是否真的找回了价值。 – k4r3y

相关问题