0

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?

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.