Mparaiso / Pimple.js

Pimple is a Dependency Injection Container for javascript , compatible with all javascript enabled browsers.
26 stars 4 forks source link

Tagging services #7

Open h4cc opened 9 years ago

h4cc commented 9 years ago

I know such a feature is not part of pimple by Fabién, but it would be cool feature for dependency injection.

How about beeing abled to "tag" services, so all tagged services could be retrieved?

Example:

pimple.set('foo', function () {
  return 'foo';
});
pimple.tag('foo', ['bar']);

console.log(pimple.taggedWith('bar')); // Will output ['foo']
h4cc commented 9 years ago

FYI: Using currently this code.

    var tagged = {};

    /**
     * Will add a list of tags to a service name.
     *
     * @param service string
     * @param tags array
     */
    pimple.tag = function (service, tags) {
        tags.forEach(function (tag) {
            if (!tagged[tag]) {
                tagged[tag] = [];
            }
            tagged[tag].push(service);
        });
    };

    /**
     * Will return the names of services tagged with given tag.
     * 
     * @param tag
     * @returns [string]
     */
    pimple.tagged = function (tag) {
        if (!tagged[tag]) {
            return [];
        }

        // Return unique list.
        return tagged[tag].filter(function (value, index, self) {
            return self.indexOf(value) === index;
        });
    };
tmilos commented 8 years ago

It would be great to have this built in. But think API would be better like this

pimple.set('service.A', function () { ... });
pimple.set('service.B', function () { ... });

pimple.tag('service.A', 'kernel.request', { method: "onRequest" } );
pimple.tag('service.A', 'kernel.request', { method: "handleRequest", priority: 10 } );
pimple.tag('service.B', 'kernel.request', { method: "onRequest", priority: -20 } );

console.log(pimple.taggedWith('kernel.request')); 
// Will output 
{
    "service.A": [
        { method: "onRequest" },
        { method: "handleRequest", priority: 10 }
    ],
    "service.B": [
        { method: "onRequest", priority: -20 }
    ]
}

If there's no will to include this in the core lib, I would definitely extend it in separate lib... pimple-tags for example, so who needs simple DPI can use just pimple, and those who needs tags also could use that other lib. @Mparaiso what do you say?

Mparaiso commented 8 years ago

What's the use case of tagging ? I don't really get it. Why do you need the same service with different tags ?