背景。我正在使用Slim,其中ID在端点或参数中。工厂根据该ID创建适当的对象以执行所需的操作。
我有一个服务,该服务需要在注入请求的请求中获得一些数据。因此,我可以执行以下操作:
//index.php
require '../vendor/autoload.php';
use Pimple\Container;
$container = new Container();
class SomeService
{
private $dataFromTheRequest;
public function __construct($dataFromTheRequest){
$this->dataFromTheRequest=$dataFromTheRequest;
echo($dataFromTheRequest);
}
}
$dataFromTheRequest='stuff1';
$container['someService1'] = function ($c) use($dataFromTheRequest) {
return new SomeService($dataFromTheRequest);
};
$someService=$container['someService1'];
但是该服务未在定义该服务的index.php中使用,而是在另一个类中使用,因此我可以执行以下操作:
class SomeOtherClass1
{
public function someMethod($dataFromTheRequest){
$someService=new SomeService($dataFromTheRequest);
}
}
$someOtherClass1=new SomeOtherClass1();
$someOtherClass1->someMethod('stuff2');
但是我想使用在index.php中分配的实例,因此我可以执行以下操作:
$container['someService2'] = function ($c) {
return new SomeService($c['dataFromTheRequest']);
};
class SomeOtherClass2
{
public function __construct($container){
$this->container=$container;
}
public function someMethod($dataFromTheRequest){
$this->container['dataFromTheRequest']='stuff3';
$someService=$this->container['someService2'];
}
}
$someOtherClass2=new SomeOtherClass2($container);
$someOtherClass2->someMethod();
但是使用容器传递数据似乎是错误的。
如果在定义服务时不知道该数据,应如何将数据注入该服务?