I have a class that extends the SlimHttpResponse class and would like to use that with my slim app. I thought I could do that using the DI container but when I inspect the class of the response, it's still just SlimHttpResponse and not my custom class (called ApiResponse).
Example:
$app = new App();
$container = $app->getContainer();
$response = $container->get('response');
var_dump(get_class($container->get('response'))); // doesnt return my custom class
The App class constructor:
public function __construct(SlimContainer $container = null) {
if (!isset($container)) {
$container = new \Slim\Container(array(
'response' => new ApiResponse()
));
}
parent::__construct($container);
}
I'm not sure if this is a bug or I'm just not using the DI container correctly.....
This works for me:
class ApiRequest extends Slim\Http\Request
{
}
$app = new Slim\App([
'request' => function ($c) {
return ApiRequest::createFromEnvironment($c['environment']);
}
]);
$app->get('/', function ($request, $response, $args) {
echo get_class($request); // -> ApiRequest
return $response;
});
$app->run();
The extended App also is fine for me:
use Slim\App;
use Slim\Container;
use Slim\Http\Request;
require 'vendor/autoload.php';
class ApiRequest extends Request
{
}
class MyApp extends App
{
public function __construct()
{
$container = new Container([
'request' => function ($c) {
return ApiRequest::createFromEnvironment($c['environment']);
}
]);
parent::__construct($container);
}
}
$app = new MyApp();
$app->get('/', function ($request, $response, $args) {
echo get_class($request); // -> ApiRequest
return $response;
});
$app->run();
@jwyuen you are missing a closure for your new Response class.
if (!isset($container)) {
$container = new \Slim\Container(array(
'response' => new ApiResponse()
));
}
parent::__construct($container);
should be
if (!isset($container)) {
$container = new \Slim\Container(array(
'response' => function () {
return new ApiResponse();
}
));
}
parent::__construct($container);
Hmm I've tried all of the suggestions and the class is still not getting overridden. I'm using Slim 3.0.0-beta2 fwiw
Nevermind, it works on the latest dev commit on the 3.x-dev branch.... (commit a1427aaea68bf490be8481921ec4a07cf2279949)
Most helpful comment
This works for me: