jankal / checked-instance
Being able to create instances from a factory and only return valid instances
Requires (Dev)
- phpunit/phpunit: 6.0.*
This package is auto-updated.
Last update: 2024-11-18 03:13:11 UTC
README
Create instances without the hassle of setting many constructor arguments.
CheckedInstance\Factory
will create an instance of a given class implementing the CheckedInstance\InstanceInterface
.
Factory
Create a newiInstance of TestClass
<?php $factory = CheckedInstance\Factory::for(TestClass::class); $object = $factory->make();
OR
<?php $factory = new CheckedInstance\Factory(); $factory->as(TestClass::class); $object = $factory->make();
OR
<?php $factory = new CheckedInstance\Factory(); $object = $factory->make(TestClass::class);
Create a new instance of TestClass
with parameters
<?php $factory = new CheckedInstance\Factory(); $factory->with('authKey', '84746afg7u789h2'); $object = $factory->make();
Other options according to the examples above!
Inject parameters from an \Psr\Container\ContainerInterface
<?php /** @var $c \Psr\Container\ContainerInterface */ CheckedInstance\Factory::container($c); $factory = new CheckedInstance\Factory(); $object = $factory->make();
One can also use a prefix that is prepended in front of the actual parameter
<?php /** @var $c \Psr\Container\ContainerInterface */ CheckedInstance\Factory::container($c); $factory = CheckedInstance\Factory::prefix('test.'); $object = $factory->make();
Instance
A class which can be instantiated by the CheckedInstance\Factory
needs to implement the CheckedInstance\InstanceInterface
.
But it may also inherit from CheckedInstance\Instance
.
<?php class TestInstance extends CheckedInstance\Instance { protected $required = [ 'authKey' ]; }
With this the Instance will only be made successfully if the authKey
is set like CheckedInstance\Factory->with('authKey', <-value->)