watson.di.container¶
- class watson.di.container.IocContainer(config=None)[source]¶
A simple dependency injection container that can store and retrieve dependencies for an application.
The container is configured via a dict containing the following keys.
- params
- A dict of data that can be injected into a dependency. If the value of the key is the same as the name of another dependency then the dependency will be referenced.
- definitions
A dict of definitions that are to be loaded by the container. Available keys within a definition are as follows.
- item
- The qualified name of a class or function
- type
- singleton (only load the dependency once) or prototype (instantiate and return a new dependency on each request)
- init
- A list or dict of items to be injected into the dependency on instantiation.
- setter
- A list or dict of methods to be called upon instantiation.
- property
- Same as setter
Only ‘item’ is a required key.
- processors
- A dict of events to be listened for and processors to be called.
Example:
container = IocContainer({ 'params': { 'db.host': 'localhost' }, 'definitions': { 'database': { 'item': 'db.adapters.MySQL' 'init': { 'host': 'db.host', 'username': 'simon', 'password': 'test', 'db': 'test' } } } }) db = container.get('database') # an instance of db.adapters.MySQL
- config¶
dict
A dict containing the definitions, params and processors.
- __instantiated__¶
dict
A cache of already instantiated dependencies.
- __init__(config=None)[source]¶
Initializes the container and set some default configuration options.
Parameters: config (dict) – The params, definitions and processors.
- add(name, obj, type_='singleton')[source]¶
Add an instantiated dependency to the container.
Parameters: - name (string) – The name used to reference the dependency
- obj (mixed) – The dependency to add
- type (string) – prototype|singleton depending on if it should be instantiated on each IocContainer.get call.
- add_definition(name, definition)[source]¶
Adds a dependency definition to the container.
Parameters: - name (string) – The name used to reference the dependency
- definition (dict) – The definition of the dependency.
- attach_processor(event, processor)[source]¶
Attach a processor to the container.
Attaches a processor to the container that will be triggered on a specific event.
Parameters: - event (string) – The name of the event (watson.di.container.POST_EVENT or PRE_EVENT)
- processor (watson.di.processors.BaseProcessor) – The processor to attach.
- definitions[source]¶
Convenience method for retrieving the definitions.
Returns: A dict of params. Return type: dict