程式CODE

2016年12月7日 星期三

laravel 5.3 想辦法變成multi版,利用middlewaare

一、修改 .env
增加,0為單機版;1為multi版

MULTI_SERVER=1


二、新增一個 middleware
php artisan make:middleware MultiMiddleware

修改它
...
    public function handle($request, Closure $next)
    {
      if(!isset($_SESSION)) session_start();
      if(env('MULTI_SERVER')=='0') $_SESSION['schoolDB'] = env('DB_DATABASE', 'forge');
      if(env('MULTI_SERVER')=='1'){
        if(empty($_SESSION['schoolDB'])){
          $_SESSION['schoolDB']="";
          return redirect('school_list');
        }
      }
      return $next($request);
    }
}

...

註冊此middleware
在 ./app/Http/下修改kernel.php,增加一個multi的類別
    protected $routeMiddleware = [
        'auth' => \Illuminate\Auth\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'admin' => \App\Http\Middleware\AdminMiddleware::class,
        'multi' => \App\Http\Middleware\MultiMiddleware::class,
    ];

三、修改 ./config/database.php
//第1行加入
<?php
if(!isset($_SESSION)) session_start();
$schoolDB = $_SESSION['schoolDB'];
...

//約58行處,改成以下
...
'database' => $schoolDB,
...

四、做一個選擇學校的 route 及 view
route
修改web.php
//在根目錄下,用multi這個middleware驗證資料庫
Route::get('/', function () {
    return view ('welcome');
})->middleware(multi::class);

//或是用group,底下的route都要這個驗證
Route::group(['middleware' => 'multi'],function(){
  Route::get('/admin', function () {
      ...
  });
});

//選擇學校的route
Route::get('school_list',function(){
  return view('school_list');
});

//處理該校的資料庫
Route::get('school/{schoolDB}',function($schoolDB){
  if(!isset($_SESSION)) session_start();
  $_SESSION['schoolDB'] = $schoolDB;
  return redirect('/');
});

view
新增一個 school_list.blade.php





















每個連結到  /school/074xxx

沒有留言:

張貼留言