Skip to content

Container Methods

MethodNew instance each call?Cleared between requests?
bind()YesN/A
singleton()NoNo
scoped()NoYes
instance()NoNo
for()(modifier)(modifier)

The for() method is a modifier—call it after bind(), singleton(), or instance() to make that binding contextual.

Create a new instance each time:

app()->bind(Logger::class, fn() => new Logger());
app()->bind(UserRepository::class, PostgresUserRepository::class);

Cache instance forever (across all requests in worker mode):

app()->singleton(DB::class, fn() => new DB(app()->env('DATABASE_URL')));

Cache per-request, reset between requests:

app()->scoped(RequestContext::class, fn() => new RequestContext());

Store an existing value directly:

$config = ['debug' => true];
app()->instance('config', $config);

Make the preceding binding contextual for specific classes:

app()
->bind(CacheInterface::class, RedisCache::class)
->for(UserService::class);
app()
->bind(CacheInterface::class, MemoryCache::class)
->for([SessionManager::class, TokenService::class]);

When UserService is resolved, it receives RedisCache. When SessionManager or TokenService are resolved, they receive MemoryCache.

MethodDescription
make($abstract, $params?)Resolve from container
get($abstract)PSR-11 alias for make()
has($abstract)Check if bound

Resolve with optional parameters:

$users = app()->make(UserService::class);
$report = app()->make(ReportGenerator::class, ['format' => 'pdf']);

Check binding exists:

if (app()->has(CacheInterface::class)) {
$cache = app()->make(CacheInterface::class);
}
use function Verge\make;
$users = make(UserService::class);
$report = make(ReportGenerator::class, ['format' => 'pdf']);