2016-07-05 47 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

相關問題