Last active
April 12, 2016 09:49
-
-
Save akrabat/c8d8cc004ec084d7833700a0c9472d94 to your computer and use it in GitHub Desktop.
Dependencies in Slim Framework
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 | |
namespace App; | |
class Foo | |
{ | |
protected $db; | |
public function __construct(PDO $db) | |
{ | |
$this->db = $db; | |
} | |
public function doSomething() | |
{ | |
// use $this->db to do something | |
} | |
} |
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 | |
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; | |
} | |
} |
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 | |
$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