Im having trouble understanding how to access the instance of Slim when a route is in a seperate class than index.php
When using Slim Framework 2 I always used the follo
Have a look at the Slim 3 Skeleton created by Rob Allen.
Slim 3 heavily uses dependency injection, so you might want to use it too.
In your dependencies.php
add something like:
$container = $app->getContainer();
$container['rdb'] = function ($c) {
return $conn;
};
$container['Your\Custom\Class'] = function ($c) {
return new \Your\Custom\Class($c['rdb']);
};
And in your Your\Custom\Class.php
:
class Class {
private $rdb;
function __construct($rdb) {
$this->rdb = $rdb;
}
public function test($request, $response, $args) {
$this->rdb->doSomething();
}
}
I hope this helps, if you have any more questions feel free to ask.
Update:
When you define your route like this
$app->get('/test', '\mycontroller:test');
Slim looks up \mycontroller:test
in your container:
$container['\mycontroller'] = function($c) {
return new \mycontroller($c['rdb']);
}
So when you open www.example.com/test
in your browser, Slim automatically creates a new instance of \mycontroller
and executes the method test
with the arguments $request
, $response
and $args
.
And because you accept the database connection as an argument for the constructor of your mycontroller
class, you can use it in the method as well :)