Joao
Joao

Reputation: 2746

PHP: How to pass an object property or single value from an array to anonymous function closure

I'm trying to setup a PHP Slim app (not directly related to my question) and I'd like a better way of passing a route's dependencies to my route function. For example, the following works as it should:

$app = new \Slim\Slim();

$testMessage = 'This is a test';

$app->get('/hello', function () use ($testMessage) {
    echo $testMessage; //output: This is a test
});

But I'm trying to use Pimple also (Dependency Injection) which creates an array that I can reference. Rather than passing the entire array to my route, I'd rather pass only the objects/services I need (makes for much more maintainable code). For example:

$app = new \Slim\Slim();

$container = new Container();

$container['test'] = function ($c) {
    return new Test();
};

$app->get('/hello', function () use ($container['test']) { //I get a syntax error on this line
    var_dump($container['test']);
});

I could "use" the whole $container, but then I'm passing everything in the container to the route, even if I only need one object. In attempting to debug this I found that I can pass any variable that looks like this: $simple which can include an entire array or an object, but I can't use an object property ($Test->value) or a single value from an array ($array['value']) unless I add the extra boilerplate of reassigning those values like this:

$Test = $container['test'];
$app->get('/hello', function () use ($Test) {
    var_dump($Test); //everything works fine
});

But then I'm creating extra objects out of my route scope, and this can get messy, of course.

Can anybody tell me if there's a way to use $container['test'] in the closure, or offer any advice?

Upvotes: 0

Views: 126

Answers (1)

T0xicCode
T0xicCode

Reputation: 4951

I'd recommend passing the whole container object. It creates very little extra overhead (just a new reference), and you are not creating extra unscoped variables. It also allows you to add dependencies, should the need arise.

Upvotes: 1

Related Questions