pine3ree / pine3ree-auto-resolve-factory
A ioc factory that resolves dependencies using reflection
Requires
- php: ^7.4 || ^8.0
- pine3ree/pine3ree-params-resolver: ^1.0
- pine3ree/pine3ree-reflection-helper: ^1.0
- psr/container: ^1.1.2 || ^2.0
Requires (Dev)
- phpspec/prophecy-phpunit: ^1.1 || ^2.0
- phpstan/phpstan: ^1.12 || ^2.0
- phpstan/phpstan-strict-rules: ^1.5
- phpunit/phpunit: ^9.3
- squizlabs/php_codesniffer: ^3.5.7
- webimpress/coding-standard: ^1.3
This package is auto-updated.
Last update: 2025-05-28 15:33:53 UTC
README
This package provides an autowiring reflection-based factory, which operates
using the pine3ree-params-resolver
library
Example:
// file: src/My/App/Model/PostMapper.php use My\App\Database\DbInterface; use My\App\Database\Db\HydratorInterface; use My\App\Configuration\Config; class PostMapper { //... public function __construct(DbInterface $db, HydratorInterface $hydrator) { // ... inject deps here } } /// --- // file: test.php use My\App\Model\PostMapper; use Psr\Container\ContainerInterface; use pine3ree\Container\Factory\AutoResolveFactory; $container = include("config/container.php"); $factory = new AutoResolveFactory(); // We need just one instance of it // All dependencies of PostMapper are resolved by the factory if they are found // in the container, i.e. if: // - $container->get(DbInterface::class) returns a DbInterface object // - $container->get(HydratorInterface::class) returns a HydratorInterface object $postMapper = $factory($container, PostMapper::class);
If the container configuration for the service PostMapper::class
instructs
the container to use the auto-resolve-factory, you can just fetch the service instance
from the container:
$postMapper = $container->get(PostMapper::class);
The requested service constructor's arguments are resolved in the following way:
-
If the argument is a type-hinted dependency with a fully-qualified-class/interface name the factory tries to load a dependency registered in the container with that class-string as identifier. If no such dependency is found, the factory will try the default provided value, if any, then the
null
value if the argument is nullable, and eventually it will try to instantiate the class directly. An exception is thrown on failure. -
If the argument is not type-hinted or is type-hinted with a builtin type the factory will try to load a service or a parameter value registered in the container with the parameter name as identifier. If not found, the factory will try the default provided value, if any, then the
null
value if the argument is nullable, otherwise an exception is thrown.