S
S
semki0962019-03-13 11:47:17
Slim Framework
semki096, 2019-03-13 11:47:17

How to access a container in the Slim PHP framework, using an example from the documentation?

An example from the documentation www.slimframework.com/docs/v3/concepts/di.html , we add a service to the container, and it seems to be clear here, we get the container and create our object in it (please correct if it’s wrong)

$container = $app->getContainer();
$container['myService'] = function ($container) {
    $myService = new MyService();
    return $myService;
};

But I didn't understand further. "You can get services from your container explicitly or implicitly. You can get an explicit reference to the container instance from within the Slim application's route like this:"
$app->get('/foo', function ($req, $res, $args) {
    $myService = $this->get('myService');
    return $res;
});

How? I would be grateful for the clarification of this code, I can not understand it.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
W
wagoodoogoo, 2019-03-13
@semki096

You add your object to the container once, and then you can call it anywhere in the application.

$container = $app->getContainer();
$container['myService'] = function ($container) {
    $myService = new MyService();
    $myService->code = 123;
    return $myService;
};

somewhere in the app:
$myService = $this->myService;
echo $myService->code; 
// выведется 123

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question