Service Providers
Introduction
Service providers are where an application is assembled. A provider is a class with two jobs: tell the container how to build things (register), and do any wiring that needs those things to exist (boot). Everything in the generated app that needs setup, such as the database connection, the logger, the exception handler, and the session manager, is set up by a provider.
You write a provider whenever you add a service to your application, and packages use them to ship their own defaults.
Writing a provider
A provider extends ServiceProvider from @plinthjs/core and gets the application as this.app:
import { ServiceProvider } from '@plinthjs/core'
class CacheServiceProvider extends ServiceProvider {
register(): void {
this.app.singleton('cache', () => new Map<string, unknown>())
}
boot(): void {
const cache = this.app.make<Map<string, unknown>>('cache')
cache.set('booted', true)
}
}Both methods are optional, and both may be async. The generated AppServiceProvider looks like this in outline:
export class AppServiceProvider extends ServiceProvider {
override register(): void {
this.app.singleton(DB, (): Connection => this.makeConnection())
this.app.singleton(LOGGER, (): Logger => this.makeLogger())
this.app.singleton(EXCEPTION_HANDLER, (): ExceptionHandler => this.makeExceptionHandler())
}
}Each binding is a lazy singleton: the connection is not opened until something resolves DB.
Register and boot
Plinth runs providers in two passes. First it calls register() on every provider, in the order they are listed. Only after all of them have registered does it call boot() on each one, in the same order. The split matters because of what each method may safely do:
- In
register, bind things into the container. Do not resolve services that other providers might provide, because they may not be registered yet. - In
boot, resolve and use services. By then every binding from every provider exists.
const log: string[] = []
class A extends ServiceProvider {
register() {
log.push('A.register')
this.app.singleton('a', () => ({ name: 'a' }))
}
boot() {
log.push('A.boot')
log.push(`sees b: ${this.app.bound('b')}`)
}
}
class B extends ServiceProvider {
async register() {
log.push('B.register')
this.app.singleton('b', () => ({ name: 'b' }))
}
async boot() {
await Promise.resolve()
log.push('B.boot')
}
}
const app = new Application()
await app.bootstrapWith([A, B])
log
// => ['A.register', 'B.register', 'A.boot', 'sees b: true', 'B.boot']Even though A is listed first, its boot can see the binding that B registered.
Registering providers
An application keeps its provider list in one file. In the generated app it is src/bootstrap/providers.ts:
import type { ServiceProviderClass } from '@plinthjs/core'
import { AppServiceProvider } from '../providers/app-service-provider.js'
import { AuthServiceProvider } from '../providers/auth-service-provider.js'
export const providers: ServiceProviderClass[] = [AppServiceProvider, AuthServiceProvider]createApplication() passes that list to app.bootstrapWith(providers), which registers every provider and then boots the application. To add a provider, create the class and append it to the array. Order matters only in that providers register and boot in list order, so put a provider before the ones that depend on its bindings at boot time.
You can also register a provider yourself with app.register. It accepts a class or an instance, ignores a provider that is already registered, and, when the application has already booted, boots the new provider right away:
await app.register(new CacheServiceProvider(app))Application lifecycle callbacks
The application announces its lifecycle, so code outside a provider can hook in:
app.booting((app) => {
// runs just before providers boot
})
app.booted((app) => {
// runs after every provider has booted; runs immediately if the app is already booted
})
app.terminating(async (app) => {
await flushBuffers()
})terminate() runs the terminating callbacks in the order they were registered, awaiting each one. The generated app does not call it; the persistent server in @plinthjs/cluster does when a worker stops. See Deployment for the shutdown path of the standard server.
app.isBooted() reports whether the boot phase has finished, and app.getProviders() returns a copy of the registered providers.
Deferred providers
If a provider's services are expensive to set up and rarely used, mark the provider as deferred. A deferred provider is not registered at startup. Plinth records the tokens it provides, and registers the provider the first time one of them is resolved:
class SearchServiceProvider extends ServiceProvider {
protected override deferred = true
override provides(): (string | symbol)[] {
return ['search']
}
override register(): void {
this.app.singleton('search', () => ({ query: () => 'results' }))
}
}
const app = new Application()
await app.bootstrapWith([SearchServiceProvider])
app.isDeferredService('search') // => true (nothing registered yet)
app.getProviders().length // => 0
app.make<{ query(): string }>('search').query() // => 'results'
app.isDeferredService('search') // => false (registered on first use)A deferred provider must list every token it binds in provides(). If the application has already booted when the provider loads, its boot() runs immediately after register(). A provider is loaded only once, no matter how many times its services are resolved.
You can override isDeferred() instead of setting the deferred field when the decision is dynamic, and load a deferred provider by hand with await app.registerDeferredProvider(provider).
WARNING
provides() may list string, symbol and class tokens. make is synchronous, so when a deferred provider is loaded by app.make(token), its register() (and its boot(), if the app has booted) must be synchronous: if either returns a promise, make throws an error that names the provider. Resolve such a provider with await app.makeAsync(token) instead, which awaits it.
Merging default configuration
A provider that ships with a package usually has default settings. mergeConfigFrom(defaults, key) deep-merges those defaults into the application's config at key, without overriding values the application already set:
class CacheConfigProvider extends ServiceProvider {
register(): void {
this.mergeConfigFrom(
{ driver: 'file', stores: { file: { path: 'x' }, redis: { db: 0 } } },
'cache',
)
}
}
const app = new Application({
config: { cache: { driver: 'redis', stores: { redis: { db: 3 } } } },
})
await app.bootstrapWith([CacheConfigProvider])
app.config.get('cache')
// => { driver: 'redis', stores: { redis: { db: 3 }, file: { path: 'x' } } }The application's own driver and redis.db win, and only the missing file store is added. Call it in register, so the final config exists by the time any provider boots. Compare this with config.merge, which replaces whole top-level sections (see Configuration).
Publishing assets
A package can offer files that you may want to copy into your project, such as a config file or views. publishes(paths, group) records a mapping from a source path to a destination path, optionally under one or more group names:
class ReportsProvider extends ServiceProvider {
register(): void {
this.publishes({ '/pkg/config/reports.ts': 'src/config/reports.ts' }, 'reports-config')
this.publishes({ '/pkg/views': 'src/resources/views/vendor/reports' }, ['views', 'reports'])
}
}Plinth records only the intent. It does not copy any files itself: copying is a job for a console command. You read the recorded entries from the application, and your command does the work:
app.publishablePaths()
// => [
// { from: '/pkg/config/reports.ts', to: 'src/config/reports.ts' },
// { from: '/pkg/views', to: 'src/resources/views/vendor/reports' },
// ]
app.publishableGroups() // => ['reports-config', 'views', 'reports']
app.publishablePaths(undefined, 'reports-config') // only the entries in that group
app.publishablePaths(ReportsProvider, 'views') // one provider, one groupThe generated app does not include a command that publishes these files. If you build packages with publishable assets, write a console command that loops over publishablePaths() and copies each entry.
Checking the environment
Providers often need to behave differently in the console and on the web, or in different environments. The application answers both:
if (this.app.runningInConsole()) {
// register commands
}
if (this.app.isProduction()) {
// production-only wiring
}runningInConsole() is an explicit flag, false by default (process.argv cannot tell a console run from a web run). The console entry sets it: pass runningInConsole: true to the Application constructor or call setRunningInConsole(true); the generated src/console.ts does this. The path helpers configPath(), databasePath() and bootstrapPath() resolve under an optional srcPath (new Application({ basePath, srcPath: 'src' }), as in the generated app); storagePath(), publicPath() and resourcePath() always resolve from basePath. See Configuration for the environment helpers.
Testing providers
Providers are plain classes, so you can bootstrap a throwaway application with only the providers under test and inspect its container:
const app = new Application({ config: { app: { env: 'testing' } } })
await app.bootstrapWith([CacheServiceProvider])
app.make<Map<string, unknown>>('cache').get('booted') // => trueTo replace a service with a fake, bind it after bootstrapping with app.instance('cache', fake).