Click here to load reader
Upload
dqneo
View
4.017
Download
2
Embed Size (px)
Citation preview
Dependency Injection And Pimple
2015.11.23 PHP BLT @DQNEO
What is Dependency Injection?
http://fabien.potencier.org/what-is-dependency-injection.html
Fabien explained it well
Primitive Code
class User { public function __construct() { $this->storage = new Storage(); }
Dependency Injection
class User { public function __construct($storage) { $this->storage = $storage; }
class MyController { public function indexAction() { $user = new User(new Storage()); }
Caller does
class MyController { public function indexAction($id) { $user = new User(new Storage(),$id); }
Caller does
class MyController { public function indexAction($id) { $user = new User(new Storage(new Account()), $id); }
Caller does
class MyController { public function indexAction($id) { $user = new User(new Storage(new Account()), $id); }
Caller does
Too Complicated
class MyController { public function indexAction($id) { $user = new User(new Storage(new Account()), $id); }
Caller does
new 書いとるやんけ
Solution
• Depenjency Injection Container
• etc
How to use Pimple// in bootstrap phase of your codes
use Pimple\Container; $container = new Container();
// define a service $container['storage'] = function ($c) { return new Storage(); };
How to use Pimple// in business logic of your codes
public function indexAction() { $storage = $this->$container[‘storage’]; … }
Internal of Pimpleclass Container implements \ArrayAccess { protected $values = [];
public function __construct(array $values = []) { $this->values = $values; }
public function offsetSet($key, $value) { $this->values[$key] = $value; }
public function offsetGet($key) { $value = $this->values[$key]; return is_callable($value)? $value($this) : $value; }
public function offsetExists($key) { return array_key_exists($key, $this->values); }
public function offsetUnset($key) { unset($this->values[$key]); } }
Internal of Pimple
class Container implements \ArrayAccess
Internal of Pimple
public function offsetGet($key) { $value = $this->values[$key]; return is_callable($value)? $value($this) : $value; }
Pimple pros/cons
• Loosely Coupling
• can make your app more testable
Pros
Cons• reduce the power of IDE (wait for PHP7)
• Indirect programming