PHP-DI / Slim-Bridge

PHP-DI integration with the Slim framework
http://php-di.org/doc/frameworks/slim.html
MIT License
176 stars 38 forks source link

Closure route handler doesnt' support $this #52

Closed joke2k closed 4 years ago

joke2k commented 4 years ago

The Invoker doesn't bind the container with route closure.

use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use DI\Bridge\Slim\Bridge as AppFactory;

require __DIR__ . '/../vendor/autoload.php';

$app = AppFactory::create();

// ... $app->getContainer()->set('view', ... );

$app->get('/[{name}]', function (Request $request, Response $response, $name = null) {
    $str = $this->get('view')->fetchFromString(
        '<p>Hi, my name is {{ name }}.</p>',
        ['name' => $name ?? 'Anonymous']
    );
    $response->getBody()->write($str);
    return $response;
});

$app->run();

raises:

Uncaught Error: Using $this when not in object context

mnapoli commented 4 years ago

Are you sure about your example? $this is not used in your controller.

joke2k commented 4 years ago

wrong copy&paste sorry. I edited with the right code.

mnapoli commented 4 years ago

OK I see what you mean, but this is expected behavior. With the PHP-DI bridge, dependencies are supposed to be passed via closure parameters.

I'm not sure if we should enable that behavior, if several people want this we may consider this.