{"id":15028929,"url":"https://github.com/silexphp/pimple","last_synced_at":"2025-05-13T00:09:11.991Z","repository":{"id":593012,"uuid":"227707","full_name":"silexphp/Pimple","owner":"silexphp","description":"A small PHP dependency injection container","archived":false,"fork":false,"pushed_at":"2024-03-21T17:35:28.000Z","size":268,"stargazers_count":2649,"open_issues_count":0,"forks_count":305,"subscribers_count":103,"default_branch":"main","last_synced_at":"2025-05-13T00:09:04.090Z","etag":null,"topics":["dependency-injection","php","pimple","silex"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":false,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/silexphp.png","metadata":{"files":{"readme":"README.rst","changelog":"CHANGELOG","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2009-06-15T15:57:01.000Z","updated_at":"2025-04-20T12:12:58.000Z","dependencies_parsed_at":"2024-06-18T10:44:06.454Z","dependency_job_id":null,"html_url":"https://github.com/silexphp/Pimple","commit_stats":{"total_commits":202,"total_committers":48,"mean_commits":4.208333333333333,"dds":0.5495049504950495,"last_synced_commit":"69bba50d1600342deae9dca3372a2b5f1ac32ae6"},"previous_names":[],"tags_count":20,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/silexphp%2FPimple","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/silexphp%2FPimple/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/silexphp%2FPimple/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/silexphp%2FPimple/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/silexphp","download_url":"https://codeload.github.com/silexphp/Pimple/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253843215,"owners_count":21972873,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["dependency-injection","php","pimple","silex"],"created_at":"2024-09-24T20:09:22.961Z","updated_at":"2025-05-13T00:09:11.948Z","avatar_url":"https://github.com/silexphp.png","language":"PHP","readme":"Pimple\n======\n\n.. caution::\n\n    Pimple is now closed for changes. No new features will be added and no\n    cosmetic changes will be accepted either. The only accepted changes are\n    compatibility with newer PHP versions and security issue fixes.\n\n.. caution::\n\n    This is the documentation for Pimple 3.x. If you are using Pimple 1.x, read\n    the `Pimple 1.x documentation`_. Reading the Pimple 1.x code is also a good\n    way to learn more about how to create a simple Dependency Injection\n    Container (recent versions of Pimple are more focused on performance).\n\nPimple is a small Dependency Injection Container for PHP.\n\nInstallation\n------------\n\nBefore using Pimple in your project, add it to your ``composer.json`` file:\n\n.. code-block:: bash\n\n    $ ./composer.phar require pimple/pimple \"^3.0\"\n\nUsage\n-----\n\nCreating a container is a matter of creating a ``Container`` instance:\n\n.. code-block:: php\n\n    use Pimple\\Container;\n\n    $container = new Container();\n\nAs many other dependency injection containers, Pimple manages two different\nkind of data: **services** and **parameters**.\n\nDefining Services\n~~~~~~~~~~~~~~~~~\n\nA service is an object that does something as part of a larger system. Examples\nof services: a database connection, a templating engine, or a mailer. Almost\nany **global** object can be a service.\n\nServices are defined by **anonymous functions** that return an instance of an\nobject:\n\n.. code-block:: php\n\n    // define some services\n    $container['session_storage'] = fn($c) =\u003e new SessionStorage('SESSION_ID');\n\n    $container['session'] = fn($c) =\u003e new Session($c['session_storage']);\n\nNotice that the anonymous function has access to the current container\ninstance, allowing references to other services or parameters.\n\nAs objects are only created when you get them, the order of the definitions\ndoes not matter.\n\nUsing the defined services is also very easy:\n\n.. code-block:: php\n\n    // get the session object\n    $session = $container['session'];\n\n    // the above call is roughly equivalent to the following code:\n    // $storage = new SessionStorage('SESSION_ID');\n    // $session = new Session($storage);\n\nDefining Factory Services\n~~~~~~~~~~~~~~~~~~~~~~~~~\n\nBy default, each time you get a service, Pimple returns the **same instance**\nof it. If you want a different instance to be returned for all calls, wrap your\nanonymous function with the ``factory()`` method\n\n.. code-block:: php\n\n    $container['session'] = $container-\u003efactory(fn($c) =\u003e new Session($c['session_storage']));\n\nNow, each call to ``$container['session']`` returns a new instance of the\nsession.\n\nDefining Parameters\n~~~~~~~~~~~~~~~~~~~\n\nDefining a parameter allows to ease the configuration of your container from\nthe outside and to store global values:\n\n.. code-block:: php\n\n    // define some parameters\n    $container['cookie_name'] = 'SESSION_ID';\n    $container['session_storage_class'] = 'SessionStorage';\n\nIf you change the ``session_storage`` service definition like below:\n\n.. code-block:: php\n\n    $container['session_storage'] = fn($c) =\u003e new $c['session_storage_class']($c['cookie_name']);\n\nYou can now easily change the cookie name by overriding the\n``cookie_name`` parameter instead of redefining the service\ndefinition.\n\nProtecting Parameters\n~~~~~~~~~~~~~~~~~~~~~\n\nBecause Pimple sees anonymous functions as service definitions, you need to\nwrap anonymous functions with the ``protect()`` method to store them as\nparameters:\n\n.. code-block:: php\n\n    $container['random_func'] = $container-\u003eprotect(fn() =\u003e rand());\n\nModifying Services after Definition\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nIn some cases you may want to modify a service definition after it has been\ndefined. You can use the ``extend()`` method to define additional code to be\nrun on your service just after it is created:\n\n.. code-block:: php\n\n    $container['session_storage'] = fn($c) =\u003e new $c['session_storage_class']($c['cookie_name']);\n\n    $container-\u003eextend('session_storage', function ($storage, $c) {\n        $storage-\u003e...();\n\n        return $storage;\n    });\n\nThe first argument is the name of the service to extend, the second a function\nthat gets access to the object instance and the container.\n\nExtending a Container\n~~~~~~~~~~~~~~~~~~~~~\n\nIf you use the same libraries over and over, you might want to reuse some\nservices from one project to the next one; package your services into a\n**provider** by implementing ``Pimple\\ServiceProviderInterface``:\n\n.. code-block:: php\n\n    use Pimple\\Container;\n\n    class FooProvider implements Pimple\\ServiceProviderInterface\n    {\n        public function register(Container $pimple)\n        {\n            // register some services and parameters\n            // on $pimple\n        }\n    }\n\nThen, register the provider on a Container:\n\n.. code-block:: php\n\n    $pimple-\u003eregister(new FooProvider());\n\nFetching the Service Creation Function\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nWhen you access an object, Pimple automatically calls the anonymous function\nthat you defined, which creates the service object for you. If you want to get\nraw access to this function, you can use the ``raw()`` method:\n\n.. code-block:: php\n\n    $container['session'] = fn($c) =\u003e new Session($c['session_storage']);\n\n    $sessionFunction = $container-\u003eraw('session');\n\nPSR-11 compatibility\n--------------------\n\nFor historical reasons, the ``Container`` class does not implement the PSR-11\n``ContainerInterface``. However, Pimple provides a helper class that will let\nyou decouple your code from the Pimple container class.\n\nThe PSR-11 container class\n~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe ``Pimple\\Psr11\\Container`` class lets you access the content of an\nunderlying Pimple container using ``Psr\\Container\\ContainerInterface``\nmethods:\n\n.. code-block:: php\n\n    use Pimple\\Container;\n    use Pimple\\Psr11\\Container as PsrContainer;\n\n    $container = new Container();\n    $container['service'] = fn($c) =\u003e new Service();\n    $psr11 = new PsrContainer($container);\n\n    $controller = function (PsrContainer $container) {\n        $service = $container-\u003eget('service');\n    };\n    $controller($psr11);\n\nUsing the PSR-11 ServiceLocator\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nSometimes, a service needs access to several other services without being sure\nthat all of them will actually be used. In those cases, you may want the\ninstantiation of the services to be lazy.\n\nThe traditional solution is to inject the entire service container to get only\nthe services really needed. However, this is not recommended because it gives\nservices a too broad access to the rest of the application and it hides their\nactual dependencies.\n\nThe ``ServiceLocator`` is intended to solve this problem by giving access to a\nset of predefined services while instantiating them only when actually needed.\n\nIt also allows you to make your services available under a different name than\nthe one used to register them. For instance, you may want to use an object\nthat expects an instance of ``EventDispatcherInterface`` to be available under\nthe name ``event_dispatcher`` while your event dispatcher has been\nregistered under the name ``dispatcher``:\n\n.. code-block:: php\n\n    use Monolog\\Logger;\n    use Pimple\\Psr11\\ServiceLocator;\n    use Psr\\Container\\ContainerInterface;\n    use Symfony\\Component\\EventDispatcher\\EventDispatcher;\n\n    class MyService\n    {\n        /**\n         * \"logger\" must be an instance of Psr\\Log\\LoggerInterface\n         * \"event_dispatcher\" must be an instance of Symfony\\Component\\EventDispatcher\\EventDispatcherInterface\n         */\n        private $services;\n\n        public function __construct(ContainerInterface $services)\n        {\n            $this-\u003eservices = $services;\n        }\n    }\n\n    $container['logger'] = fn($c) =\u003e new Monolog\\Logger();\n    $container['dispatcher'] = fn($c) =\u003e new EventDispatcher();\n    \n    $container['service'] = function ($c) {\n        $locator = new ServiceLocator($c, array('logger', 'event_dispatcher' =\u003e 'dispatcher'));\n\n        return new MyService($locator);\n    };\n\nReferencing a Collection of Services Lazily\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nPassing a collection of services instances in an array may prove inefficient\nif the class that consumes the collection only needs to iterate over it at a\nlater stage, when one of its method is called. It can also lead to problems\nif there is a circular dependency between one of the services stored in the\ncollection and the class that consumes it.\n\nThe ``ServiceIterator`` class helps you solve these issues. It receives a\nlist of service names during instantiation and will retrieve the services\nwhen iterated over:\n\n.. code-block:: php\n\n    use Pimple\\Container;\n    use Pimple\\ServiceIterator;\n\n    class AuthorizationService\n    {\n        private $voters;\n\n        public function __construct($voters)\n        {\n            $this-\u003evoters = $voters;\n        }\n\n        public function canAccess($resource)\n        {\n            foreach ($this-\u003evoters as $voter) {\n                if (true === $voter-\u003ecanAccess($resource)) {\n                    return true;\n                }\n            }\n\n            return false;\n        }\n    }\n\n    $container = new Container();\n\n    $container['voter1'] = fn($c) =\u003e new SomeVoter();\n    $container['voter2'] = fn($c) =\u003e new SomeOtherVoter($c['auth']);\n    $container['auth'] = fn ($c) =\u003e new AuthorizationService(new ServiceIterator($c, array('voter1', 'voter2'));\n\n.. _Pimple 1.x documentation: https://github.com/silexphp/Pimple/tree/1.1\n","funding_links":[],"categories":[],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsilexphp%2Fpimple","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsilexphp%2Fpimple","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsilexphp%2Fpimple/lists"}