Search code examples
phpdependenciespimple

Pimple dependency injection static or object


Pimple help re-use the same object across application, and manage dependecy.

but how to manage Pimple itself?

Should I create a global object? Or make it static class? Or use a function?

I would like to access on Pimple methods from anywhere, controllers, models, plugins, etc...

Thanks!!


Solution

  • A lot of folk consider ServiceLocator to be an anti-pattern, but if you use it sparingly, there's little harm done.

    <?php
    
    namespace Acme;
    
    class ServiceLocator
    {
        static protected $container;
    
        public static function setContainer(\Pimple $container)
        {
            static::$container = $container;
        }
    
        public static function get($id)
        {
            return static::$container[$id];
        }
    }