1

Background. I am using Slim where an ID is either in the endpoint or parameters. Based on the ID, a factory creates the appropriate object to perform the needed action.

I have a service which needs some data obtained in the request injected into it. I could therefore do the following:

//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'];

But the service is not used in index.php where the service is defined but in another class, so i can do the following:

class SomeOtherClass1
{
    public function someMethod($dataFromTheRequest){
        $someService=new SomeService($dataFromTheRequest);
    }

}
$someOtherClass1=new SomeOtherClass1();
$someOtherClass1->someMethod('stuff2');

But I want to use the instance assigned in index.php, so I can do the following:

$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();

But using the container to pass data just seems wrong.

How should data be injected in a pimple service if that data is not known when the service is defined?

user1032531
  • 24,767
  • 68
  • 217
  • 387
  • Constructors are handling **dependencies**. If a dependency in unknown at the time the service is defined, it seems like that service is being defined at the wrong time. – Devon Bessemer Jun 27 '18 at 13:36
  • 1
    It's hard to understand exactly what you're doing with SomeOtherClass2, but why not pass SomeService2 (from the container) in to that constructor instead of passing the entire container? – Devon Bessemer Jun 27 '18 at 13:38
  • 1
    How come you want to insert `$dataFromTheRequest` when the services are defined, as opposed to passing it in to the method that needs said data? I'm not doubting yer motivations, just asking for clarification so as to best answer the question. Normally one would only have the controller dealing with the notions of requests, and the controller extracts the bits the methods of the services will need when they come to call the service methods, at which point the values are just arguments, and that they came from a request is irrelevant? – Adam Cameron Jun 27 '18 at 13:40

0 Answers0