0.1.0 • Published 7 years ago

pore v0.1.0

Weekly downloads
4
License
MIT
Repository
github
Last release
7 years ago

Pore (dependency injection container)

A super simple dependency injection container for applying the Inversion of Control principle in JavaScript.

Key features:

Usage

Import the library

const Pore = require('pore')

Instantiate the container.

let pore = new Pore()

Register constructor functions by their logical names.

pore.register('Database', () => {
  return new MongoloidDatabaseAdapter()
});

Call constructor functions by their logical names;

pore.get('Database')
// a new instance of MongoloidDatabaseAdapter

Chain constructors to build object graphs.

pore.register('Service', (pore) => {
  return new Service(
    pore.get('Database') // <-- This is where the magic happens
  );
});

Throw some scalar values at it, too.

pore.register('Pi', 3.14);
pore.get('Pi')
// 3.14

Flag constructors as shared to only construct a single instance of your thing.

pore.register('SharedService', () => {
  return new SharedService();
}, {
  shared: true
});

Tag constructor functions, and get logical names associated with tags.

pore.register('one', 1, { tags: [ 'number' ]);
pore.register('two', 2, { tags: [ 'number' ]);
pore.register('carrot', '???', { tags: [ 'vegetable' ]);

pore.getTagged('number');
// [ 'one', 'two' ]

Bonus feature: extract a subset (defined by a tag) of the registered constructors into a completely new pore. (If you are wondering why, try and think of this as a FactoryFactory).

pore.register('one', 1, { tags: [ 'number' ]);
pore.register('two', 2, { tags: [ 'number' ]);
pore.register('carrot', '???', { tags: [ 'vegetable' ]);

pore.createNewFromTag('number');
// returns a completely fresh Pore with 'one' and 'two'

API

pore.register(name, item, options) : undefined

ParameterTypeDescription
namestringLogical name of the item. Use this to also get the item.
item*Anything you want to store against the logical name. If the item is of type function the pore instance will be passed as the first argument.
optionsobjectOptional. See below.

Options:

OptionTypeDescription
sharedbooleanOptional. If set, and if the item is of type function, the function will only be executed once and the result returned every time you get it from pore.
tagsarray of stringsOptional. Tags associated with the item

pore.get(name) : *

ParameterTypeDescription
namestringLogical name of the item to get.

pore.getTagged(tag) : *

Parameters:

ParameterTypeDescription
tagstringGet items with this tag.

pore.createNewFromTag(tag) : pore

Paramters:

ParameterTypeDescription
tagstringCreate new pore out of items with this tag.

Specs

It's fully tested.

License

Licensed under MIT license.