-
-
Save akrabat/636a8833695f1e107701 to your computer and use it in GitHub Desktop.
<?php | |
// All file paths relative to root | |
chdir(dirname(__DIR__)); | |
require "vendor/autoload.php"; | |
$settings = ['foo' => 'FOO', 'bar' => 'BAR']; | |
$app = new \Slim\App($settings); | |
// Set some things into the container | |
$container = $app->getContainer(); | |
$container['App\Controller\BookController'] = function ($c) { | |
return new App\Controller\BookController(); | |
}; | |
$container['MyRouteMiddleware'] = function ($c) { | |
return function ($request, $response, $next) use ($c) { | |
$settings = $c['settings']; | |
// do something with $settings | |
return $next($request, $response); | |
}; | |
}; | |
// Routing | |
// Home page... | |
$app->get( | |
'/', | |
function ($request, $response) { | |
// access container via __get: | |
$foo = $this->settings['foo']; | |
// or via getContainer() | |
$container = $this->getContainer(); | |
$bar = $container['settings']['bar']; | |
$response->write("<p>Hello World</p>"); | |
return $response; | |
} | |
) | |
// ... with some middleware | |
->add(function ($request, $response, $next) use ($container) { | |
$middlware = $container['MyRouteMiddleware']; | |
return $middlware($request, $response, $next); | |
}); | |
// Another page | |
$app->map( | |
['GET', 'POST'], | |
'/book/edit/{id}', | |
'App\Controller\BookController:edit' | |
); | |
$app->run(); |
Say for example I want to store an array, can I just store it in the container?
How can I catch the requested JSON within a custom class method using container?
I have set \Slim\Container $container within a constructor, able to call response methods withJson, write etc, but can able to fetch the JSON I had sent...
My attempt was...
return $this->container->request->getParsedBody();
and it returns blank!
Can anyone please help?
How does this work with Slim 4? I have the standard PHP-DI here and want to add the line $container['penModel'] = new \Farm\Factories\PenModelFactory();
which is from Slim 3 I think.
return function (ContainerBuilder $containerBuilder) {
$containerBuilder->addDefinitions([
LoggerInterface::class => function (ContainerInterface $c) {
$settings = $c->get('settings');
$loggerSettings = $settings['logger'];
$logger = new Logger($loggerSettings['name']);
$processor = new UidProcessor();
$logger->pushProcessor($processor);
$handler = new StreamHandler($loggerSettings['path'], $loggerSettings['level']);
$logger->pushHandler($handler);
return $logger;
},
]);
};
For PHP-DI in Slim 4, look up how PHP-DI's container builder works.
addDefinitions()
takes an array, so you can just add to the list of things it knows about. I don't know how it expects a factory to be registered.
Thank You :)