Skip to content

Instantly share code, notes, and snippets.

@akrabat
Last active April 28, 2020 08:14
Show Gist options
  • Save akrabat/636a8833695f1e107701 to your computer and use it in GitHub Desktop.
Save akrabat/636a8833695f1e107701 to your computer and use it in GitHub Desktop.
Example uses of Slim 3's container
<?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();
@akrabat
Copy link
Author

akrabat commented Apr 28, 2020

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment