Extension point/extension pattern
Extension Point/extensionis a very powerful design pattern that promotes loose coupling and offers greatextensibility. There are many use cases in LoopBack 4 that fit into designpattern. For example:
@loopback/boot
usesBootStrapper
that delegates toBooters
to handledifferent types of artifacts@loopback/rest
usesRequestBodyParser
that finds the correspondingBodyParsers
to parse request body encoded in different media types@loopback/core
usesLifeCycleObserver
to observestart
andstop
eventsof the application life cycles.To add a feature to the framework and allow it to be extended, we divide theresponsibility into two roles:Extension point: it represents a common functionality that the frameworkdepends on and interacts with, such as, booting the application, parsing httprequest bodies, and handling life cycle events. Meanwhile, the extension pointalso defines contracts for its extensions to follow so that it can discovercorresponding extensions and delegate control to them without having to hardcode such dependencies.
Extensions: they are implementations of specific logic for an extensionpoint, such as, a booter for controllers, a body parser for xml, and a lifecycle observer to load some data when the application is started. Extensionsmust conform to the contracts defined by the extension point.
NOTE: Applications can also benefit from the extension point/extensionspattern by separating common functionality and specific behaviors for thebusiness logic.
Helper decorators and functions
To simplify implementations of extension point and extensions pattern on top ofLoopBack 4’s Inversion of Control andDependency Injection container, the following helperdecorators and functions are provided to ensure consistency and convention.
@extensionPoint
: decorates a class to be an extension point with an optionalcustom name@extensions
: injects a getter function to access extensions to the targetextension pointextensionFilter
: creates a binding filter function to find extensions forthe named extension pointextensionFor
: creates a binding template function to set the binding to bean extension for the named extension pointaddExtension
: registers an extension class to the context for the namedextension pointThe usage of these helper decorators and functions are illustrated in thegreeter-extension
tutorial.
Tutorial
Thegreeter-extension exampleprovides a walk-through on how to implement the extension point/extensionpattern using LoopBack 4’s Context andDependency injection container.