Skip to content

Instantly share code, notes, and snippets.

@akrabat
Last active April 12, 2016 09:49
Show Gist options
  • Save akrabat/c8d8cc004ec084d7833700a0c9472d94 to your computer and use it in GitHub Desktop.
Save akrabat/c8d8cc004ec084d7833700a0c9472d94 to your computer and use it in GitHub Desktop.
Dependencies in Slim Framework
<?php
namespace App;
class Foo
{
protected $db;
public function __construct(PDO $db)
{
$this->db = $db;
}
public function doSomething()
{
// use $this->db to do something
}
}
<?php
namespace App;
class HomeAction
{
protected $foo;
public function __construct(Foo $foo)
{
$this->db = $foo;
}
public function __invoke($request, $response, $args)
{
// do something with $this->foo
return $reponse;
}
}
<?php
$app = new Slim\App(['settings' => ['displayErrorDetails' => true]]);
// set up DIC
$container = new $app->getContainer();
$container['db'] = function ($c) {
return new PDO();
};
$container[App\Foo::class] = function ($c) {
return new App\Foo($c->get('db'));
};
$container[App\HomeAction::class] = function ($c) {
return new App\HomeAction($c->get(App\Foo::class));
};
// register routes
$app->get('/', App\HomeAction::class);
// run application
$app->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment