I wish to create a new instance of SomeService which must be injected with some data which is not known when defining the service in Pimple. The following technically works, but surely cannot be the proper way to do so. How should this be accomplished?
<?php
use Pimple\Container;
class SomeService
{
private $theNewData;
public function __construct(MyPdo $pdo, array $theNewData){
$this->theNewData=$theNewData;
}
public function getJsonString():string{
return json_encode($this->theNewData);
}
}
class MyPdo{}
function getServiceSometimeInTheFuture(Container $container):SomeService {
$someFutureData= ['a'=>1,'b'=>2,'c'=>3,];
/*
How do I inject this content into SomeService other than using Pimple as a temporary transport?
*/
$container['temp']=$someFutureData;
$newInstance=$container['someService'];
unset($container['temp']);
return $newInstance;
}
require '../vendor/autoload.php';
$container=new Container();
$container['myPdo'] = function ($c) {
return new MyPdo();
};
$container['someService'] = $container->factory(function ($c) {
return new SomeService($c['myPdo'], $c['temp']);
});
$service = getServiceSometimeInTheFuture($container);
echo($service->getJsonString());
I think the root cause for this problem is that
future datais actually data as its name suggests, and it is going to change multiple times over the time, so it should not be passed to the service at the time of service definition, but every time the consumer method in the service (getJsonStringhere) needs that data.The data is not known, but how about the source of the data? Could you write a new service to act as data provider, so the original service can get required data when required in the future?
I can suggest two solutions.
(I intentionally removed MyPdo from everywhere because it was not used at all, even in the constructor)
If you really need the data to be passed to the service at creation time:
If you can postpone providing data to the service at the time it needs that data in the future: