Using instance of response in another class by autowiring PHP-DI

Hello,

I am new to autowiring and currently using PHP-DI.

I have the following controller:

<?php

namespace Registration\Actions;

class Home
{
    protected $responder;
    public function __construct(\Registration\Responders\Home $responder)
    {
        $this->responder = $responder;
    }

    public function __invoke($request,$response)
    {
        return $this->responder->send();
        
    }
}

and this is responder class

<?php

namespace Registration\Responders;
use Psr\Http\Message\ResponseInterface as Response;

class Home
{
    protected $response;

    public function __construct(Response $response)
    {
        $this->response = $response;
    }

    public function send()
    {
        return 'Test';
    }
}

I am facing the following error:

Entry "Registration\Actions\Home" cannot be resolved: Entry "Registration\Responders\Home" cannot be resolved: Entry "Psr\Http\Message\ResponseInterface" cannot be resolved: the class is not instantiable Full definition: Object ( class = #NOT INSTANTIABLE# Psr\Http\Message\ResponseInterface scope = singleton lazy = false ) Full definition: Object ( class = Registration\Responders\Home scope = singleton lazy = false __construct( $response = get(Psr\Http\Message\ResponseInterface) ) ) Full definition: Object ( class = Registration\Actions\Home scope = singleton lazy = false __construct( $responder = get(Registration\Responders\Home) ) )

What am I doing wrong ?

Hello @ahmed.medhat,

The error means PHP-DI does not how to autowire an interface instance. You have to tell PHP-DI which class to use to create an instance of an interface such as Psr\Http\Message\ResponseInterface. You shouldn’t be fetching the response object from the container, though, because it could be stale.

Instead pass the response to the Home::send method of the responder:

<?php

namespace Registration\Actions;

class Home
{
    protected $responder;

    public function __construct(\Registration\Responders\Home $responder)
    {
        $this->responder = $responder;
    }

    public function __invoke($request,$response)
    {
        return $this->responder->send($response);        
    }
}
<?php

namespace Registration\Responders;
use Psr\Http\Message\ResponseInterface as Response;

class Home
{
    public function send(Response $response)
    {
        return 'Test';
    }
}