draba-injector 降低耦合度的利器

2016-03-18 11:04:28

     先看下官方解释

   dependent injection module, used to help isolating components which will become more easily test 依赖注入模块,用来分离应用程序中的组件,或用来测试。

"require" is the default module in Node.js, but more dependencies, and hard to test require是nodejs默认的模块加载组件,耦合性非常强,非常不利于单元测试。

follow is a example, more code in the "tests" directory 下面介绍一个简单的例子来展示此模块的用法(具体代码见tests目录)

directory 目录结构

/example
    /recursive
        entityA.js
        entityB.js
        entityC.js
        entityD.js

dependency: 依赖关系:

"entityA" dependents to "entityB"
"entityB" dependents to "entityC" and "entityD"

entityA.js的内容

module.exports = ['example.recursive.entityB', function (entityB) {
}];

entityB.js的内容

module.exports = ['example.recursive.entityC', 'example.recursive.entityD', function (entityC, entityD) {
}];

entityC.js的内容

module.exports = [function () {
    return 4;
}];

entityD.js的内容

module.exports = [function () {
    return 8;
}];

how to use 如何加载使用

var Inject = require('draba-injector');
var injector = new Injector(__dirname '/tests');
var app = injector.inject(['example.recursive.entityA', function (entityA) {
    return {entityA:entityA};
}]);

格式如下:

[entityName1, entityName2,..., function (entity1, entity2,...) {
}]

same to component 等同于组件

格式如下:

format is RegExp('^[0-9a-z_$\-] ([.][0-9a-z_$\-] )*(:[0-9a-z_$\-] )*$', 'i')
实体名称格式为 RegExp('^[0-9a-z_$\-] ([.][0-9a-z_$\-] )*(:[0-9a-z_$\-] )*$', 'i')
entity name will be parsed to a path by replace "." to "/"
实体名称会被解析成路径,每一个"."被替解析成“/”,加上basePath前缀做路径得到实体的文件路径

params:

@basePath <string> the basePath of the Injector

params:

@target <array|other> the main component which will be injected;if not an array, directly return
@injectionData <undefined|object> the predefined data that will be injected to the target

78B51F9E-8396-4965-B4A2-0A0D91FF074D.png


来玩个例子吧

var Injector = require('draba-injector') ;
var injector = new Injector(__dirname);
injector.inject(["config.db",function(data)
{
    console.log(data)
}
])

结果:

kevie:restify_demo tom$ node test.js
{ mysql: 
   { read: 'mysql://root:root@localhost:3306/test',
     write: 'mysql://root:root@localhost:3306/test' } }

   其实读配置只是此模块的简易功能,应用范围。可以更加的广,比如读入不同文件。 方便测试等等。  就看实际应用中,你应用到哪里了 。

你打算打赏多少钱呢?

打赏
(微信扫一扫)