Pimple.js icon indicating copy to clipboard operation
Pimple.js copied to clipboard

Tagging services

Open h4cc opened this issue 10 years ago • 3 comments

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 avatar Feb 03 '15 13:02 h4cc

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;
        });
    };

h4cc avatar Feb 04 '15 10:02 h4cc

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?

tmilos avatar Mar 22 '16 06:03 tmilos

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

Mparaiso avatar Apr 06 '16 03:04 Mparaiso