kko
kko

Reputation: 117

Pass arguments in Slim DI service

I have a service that I want to access from a route but pass arguments to.

$container = new \Slim\Container();    
$container['myService'] = function($arg1, $arg2) {
        //my code here
};
$app = new \Slim\App($container);

and inside my route, I try to call the service like so:

$this->myService('my arg1', 'my arg2');

This is not working. When I try to call it without specifying the arguments, it works.

How to call with arguments? Or is that an alternative way to specify a function or method to be called from inside a route?

Upvotes: 2

Views: 2440

Answers (1)

geggleto
geggleto

Reputation: 2625

so you are pretty close.

$container = new \Slim\Container();    
$container['myService'] = function ($c) { 
    return function($arg1, $arg2) {
        //my code here
    }
};
$app = new \Slim\App($container);

$app->get('/', function ($req, $res, $args) {
    $this->myService($a, $b);
});

This should work.

Optionally, with your original code... you have to save it to a variable first before invoking it.

$service = $this->myService;
$service('my arg1', 'my arg2');

Both of these should work.

Upvotes: 10

Related Questions