-
-
Save psema4/6ce270938d65075b2146b492fc6998ab to your computer and use it in GitHub Desktop.
Example uses of Slim 3's container
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment