在 Laravel 5.4 中,我注册了一个服务提供者,它为我的 Context 类创建了一个单例,该类包含应用程序上下文。
上下文服务提供者
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App;
class ContextServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
// Set-up application context
$context = app('context');
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->singleton('context', function ($app) {
return new App\Context();
});
}
}
然后我创建了一个具有全局范围的 Eloquent 模型。
模型媒体
namespace App\Models;
use App\Scopes\SchoolScope;
use Illuminate\Database\Eloquent\Model;
class Media extends Model
{
public static function boot()
{
parent::boot();
static::addGlobalScope(new SchoolScope());
}
}
现在,当我在 SchoolScope 范围内访问 Context 单例时,会创建两次单例!
学校范围
namespace App\Scopes;
use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;
use App\Models\School;
class SchoolScope implements Scope
{
protected $school;
public function __construct()
{
$this->school = app('context')->school;
}
public function apply(Builder $builder, Model $model)
{
$builder->where('school_id', '=', $this->school->id);
}
}
有谁知道为什么单例会被创建两次?