我正在使用这个:
创建中间件 setDB:
namespace App\Http\Middleware;
use Cookie;
use Config;
use Closure;
use DB;
use App\User;
use App\Common;
use Auth;
use Session;
use View;
use Illuminate\Contracts\Foundation\Application;
class SetDB
{
public function __construct(Application $app){
$this->app=$app;
}
public function handle($request, Closure $next)
{
$server=$_SERVER["SERVER_NAME"];
$paths = 'resources/views';
$asset = 'public';
$result=DB::connection('mysql2')->table('mst_editor_database_info')->where("paths",$server)->first();
DB::disconnect(env('DB_DATABASE'));
if(count($result) > 0){
$dbname=$result->dbname;
$paths = 'themes/'.$result->paths.'/views';
Session::put('paths',$paths);
Session::put('asset','themes/'.$result->paths.'/assets');
Config::set('database.connections.mysql', array(
'driver' => 'mysql',
'host' => env('DB_HOST'),
'port' => env('DB_PORT'),
'database' =>$dbname,
'username' => 'username',
'password' => 'password',
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
));
DB::reconnect('mysql');
}else{
DB::disconnect('mysql');
Config::set('database.connections.mysql', config('database.connections.mysql2'));
DB::reconnect('mysql');
Session::put('paths',$paths);
Session::put('asset',$asset);
}
Common::setTheme();
Config::set('site.asset', Session::get('asset'));
return $next($request);
}
}
创建类 App\Common.php:
namespace App;
use Config;
use Session;
use Illuminate\Database\Eloquent\Model;
use View;
class Common extends Model
{
public static function setTheme(){
Config::set('view.paths', Session::get('paths'));
View::addNamespace('Theme', Session::get('paths'));
}
}
使用命名空间主题:
return View::make('Theme::welcome');
在 kernel.php 中注册中间件:
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\SetDB::class,
]
];
在 config/database.php 中设置默认数据库连接:
'connections' => [
'mysql' => [
'driver' => 'mysql',
'host' => env('DB_HOST'),
'port' => env('DB_PORT'),
'database' => env('DB_DATABASE'),
'username' => env('DB_USERNAME'),
'password' => env('DB_PASSWORD'),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
'mysql2' => [
'driver' => 'mysql',
'host' => env('DB_HOST'),
'port' => env('DB_PORT'),
'database' => env('DB_DATABASE'),
'username' => env('DB_USERNAME'),
'password' => env('DB_PASSWORD'),
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
'strict' => true,
'engine' => null,
],
],
设置配置/view.php:
'paths' => [base_path('/')],
创建您的模板文件夹
themes/{paths}/views