{"id":20672795,"url":"https://github.com/selective-php/container","last_synced_at":"2025-04-19T19:11:08.970Z","repository":{"id":41111062,"uuid":"260789882","full_name":"selective-php/container","owner":"selective-php","description":"A PSR-11 container implementation with factories and autowiring","archived":false,"fork":false,"pushed_at":"2023-09-09T16:58:24.000Z","size":51,"stargazers_count":12,"open_issues_count":0,"forks_count":2,"subscribers_count":3,"default_branch":"master","last_synced_at":"2024-09-23T08:09:11.494Z","etag":null,"topics":["autowire","autowiring","container","dependency-injection","factories","php","psr-11","slim","slim4"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"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/selective-php.png","metadata":{"files":{"readme":"README.md","changelog":null,"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":"2020-05-02T22:56:43.000Z","updated_at":"2024-08-25T18:17:26.000Z","dependencies_parsed_at":"2024-06-21T19:05:47.920Z","dependency_job_id":"c35c774a-0567-47ef-8afe-55a66fe305f7","html_url":"https://github.com/selective-php/container","commit_stats":{"total_commits":53,"total_committers":3,"mean_commits":"17.666666666666668","dds":0.3584905660377359,"last_synced_commit":"c6f07dbcc52e29399d745886a105064c1fa1d5c3"},"previous_names":[],"tags_count":6,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/selective-php%2Fcontainer","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/selective-php%2Fcontainer/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/selective-php%2Fcontainer/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/selective-php%2Fcontainer/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/selective-php","download_url":"https://codeload.github.com/selective-php/container/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":249773441,"owners_count":21323468,"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":["autowire","autowiring","container","dependency-injection","factories","php","psr-11","slim","slim4"],"created_at":"2024-11-16T20:38:50.201Z","updated_at":"2025-04-19T19:11:08.939Z","avatar_url":"https://github.com/selective-php.png","language":"PHP","readme":"# selective/container\n\n[![Latest Version on Packagist](https://img.shields.io/github/release/selective-php/container.svg)](https://packagist.org/packages/selective/container)\n[![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg)](LICENSE)\n[![Build Status](https://github.com/selective-php/container/workflows/build/badge.svg)](https://github.com/selective-php/container/actions)\n[![Coverage Status](https://img.shields.io/scrutinizer/coverage/g/selective-php/container.svg)](https://scrutinizer-ci.com/g/selective-php/container/code-structure)\n[![Quality Score](https://img.shields.io/scrutinizer/quality/g/selective-php/container.svg)](https://scrutinizer-ci.com/g/selective-php/container/?branch=master)\n[![Total Downloads](https://img.shields.io/packagist/dt/selective/container.svg)](https://packagist.org/packages/selective/container/stats)\n\n## Description\n\nA PSR-11 container implementation with optional **autowiring**.\n\n## Requirements\n\n * PHP 8.1+\n\n## Installation\n\n```\ncomposer require selective/container\n```\n\n## Usage\n\n```php\nuse Selective\\Container\\Container;\n\n$container = new Container();\n// ...\n\n$myService = $container-\u003eget(MyService::class);\n```\n\n### Enable Autowiring\n\nThe container is able to automatically create and inject dependencies for you. This is called \"autowiring\".\n\nTo enable autowiring you have to add the `ConstructorResolver`:\n\n```php\n\u003c?php\n\nuse Selective\\Container\\Container;\nuse Selective\\Container\\Resolver\\ConstructorResolver;\n\n$container = new Container();\n\n// Enable autowiring\n$container-\u003eaddResolver(new ConstructorResolver($container));\n\n//...\n\n```\n\n### Defining DI Container Definitions\n\nYou can use a factories (closures) to define injections.\n\n```php\n\u003c?php\n\nuse App\\Service\\MyService;\nuse Selective\\Container\\Container;\nuse Psr\\Container\\ContainerInterface;\nuse Psr\\Log\\LoggerInterface;\n\n$container = new Container();\n\n// Add definition\n$container-\u003efactory(MyService::class, function (ContainerInterface $container) {\n    return new MyService();\n});\n```\n\n## Defining Multiple DI Container Definitions\n\n```php\nuse Psr\\Container\\ContainerInterface;\n// ...\n\n$entries = [\n    MyService::class =\u003e function (ContainerInterface $container) {\n        return new MyService();\n    },\n    \n    PDO::class =\u003e function (ContainerInterface $container) {\n        return new PDO('sqlite:example.db');\n    },\n    \n    // and so on...\n];\n\n$container-\u003efactories($entries);\n```\n\n\n### Service Providers\n\nService providers give the benefit of organising your container \ndefinitions along with an increase in performance for larger applications \nas definitions registered within a service provider are lazily registered \nat the point where a service is retrieved.\n\nTo build a service provider create a invokable class and \nreturn the definitions (factories) you would like to register.\n\n```php\n\u003c?php\n\nuse App\\Service\\MyService;\nuse Selective\\Container\\Container;\nuse Psr\\Container\\ContainerInterface;\nuse Psr\\Log\\LoggerInterface;\n\nfinal class MyServiceFactoryProvider\n{\n    /**\n     * @return array\u003cstring, callable\u003e\n     */\n    public function __invoke(): array\n    {\n        return [\n            MyService::class =\u003e function (ContainerInterface $container) {\n                return new MyService($container-\u003eget(LoggerInterface::class));\n            },\n        ];\n    }\n}\n\n$container-\u003efactories((new MyServiceFactoryProvider())());\n```\n\n### Set definitions directly\n\nIn addition to defining entries in an array of factories / callbacks, \nyou can also set the value directly as shown below:\n\n```php\n$container-\u003eset(\\App\\Domain\\MyService::class, new \\App\\Domain\\MyService());\n```\n\n### Fetching DI container entries\n\nTo fetch a value use the `get` method:\n\n```php\n$pdo = $container-\u003eget(PDO::class);\n```\n\n### Testing\n\n* Make sure that your container will be recreated for each test. You may use the phpunit `setUp()` method to initialize the container definitions.\n* You can use the `set()` method to overwrite existing container entries.\n\n#### Mocking\n\nThe `set` method can also be used to set mocked objects directly into the container.\n\nThis example requires phpunit:\n\n```php\n\u003c?php\n\n$class = \\App\\Domain\\User\\Repository\\UserRepository::class;\n\n$mock = $this-\u003egetMockBuilder($class)\n    -\u003edisableOriginalConstructor()\n    -\u003egetMock();\n\n$mock-\u003emethod('methodToMock1')-\u003ewillReturn('foo');\n$mock-\u003emethod('methodToMock2')-\u003ewillReturn('bar');\n\n$container-\u003eset($class, $mock);\n```\n\n## Slim 4 integration\n\nExample to boostrap a Slim 4 application using the container:\n\n```php\n\u003c?php\n\nuse Selective\\Container\\Container;\nuse Selective\\Container\\Resolver\\ConstructorResolver;\nuse Slim\\App;\nuse Slim\\Factory\\AppFactory;\n\nrequire_once __DIR__ . '/../vendor/autoload.php';\n\n$container = new Container();\n\n// Enable autowiring\n$container-\u003eaddResolver(new ConstructorResolver($container));\n\n// Load container definitions\n$container-\u003efactories(require __DIR__ . '/container.php');\n\n// Create slim app instance\nAppFactory::setContainer($container);\n$app = AppFactory::create();\n\n// Add routes, middleware etc...\n\n$app-\u003erun();\n```\n\nThe `container.php` file must return an array of factories (closures):\n\n```php\n\u003c?php\n\nuse Monolog\\Logger;\nuse Psr\\Container\\ContainerInterface;\nuse Psr\\Log\\LoggerInterface;\n\nreturn [\n    'settings' =\u003e function () {\n        return require __DIR__ . '/settings.php';\n    },\n\n    LoggerInterface::class =\u003e function (ContainerInterface $container) {\n        $logger = new Logger('name');\n        \n        // ...\n        \n        return $logger;\n    },\n    \n    // Add more definitions here...\n]\n```\n\n## PhpStorm Integration\n\nIf you use PhpStorm, then create a new file `.phpstorm.meta.php`\nin your project root directory and copy/paste the following content:\n\n```php\n\u003c?php\n\nnamespace PHPSTORM_META;\n\noverride(\\Psr\\Container\\ContainerInterface::get(0), map(['' =\u003e '@']));\n```\n\n## Performance Comparison\n\n`selective/container` is about:\n\n* 11% faster then `php-di/php-di`.\n* 5.4% faster then `league/container`.\n\nAll tests where made with enabled autowiring.\n\n## Migrating from PHP-DI\n\nThis PSR-11 container implementation mimics the behavior of PHP-DI.\n\nIf you already use [factories](https://php-di.org/doc/php-definitions.html#factories) for your container definitions,\nthe switch should be very simple.\n\nReplace this:\n\n```php\n\u003c?php\nuse DI\\ContainerBuilder;\n\n// ...\n\n$containerBuilder = new ContainerBuilder();\n\n$containerBuilder-\u003eaddDefinitions(__DIR__ . '/container.php');\n\n$container = $containerBuilder-\u003ebuild();\n```\n\n... with this:\n\n```php\n\u003c?php\nuse Selective\\Container\\Container;\nuse Selective\\Container\\Resolver\\ConstructorResolver;\n// ...\n\n$container = new Container();\n\n// Enable auto-wiring\n$container-\u003eaddResolver(new ConstructorResolver($container));\n\n// Add definitions\n$container-\u003efactories(require __DIR__ . '/container.php');\n```\n\nThat's it.\n\n## Credits\n\n* Dominik Zogg (chubbyphp)\n\n## Similar libraries\n\n* https://github.com/chubbyphp/chubbyphp-container\n* http://php-di.org/\n* https://container.thephpleague.com/\n\n## License\n\nThe MIT License (MIT). Please see [License File](LICENSE) for more information.\n","funding_links":[],"categories":["PHP"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fselective-php%2Fcontainer","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fselective-php%2Fcontainer","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fselective-php%2Fcontainer/lists"}