Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Dependency Injection and Pimple

4,330 views

Published on

Presentation at #phpblt

Published in: Technology
  • Be the first to comment

  • Be the first to like this

Dependency Injection and Pimple

  1. 1. Dependency Injection And Pimple 2015.11.23 PHP BLT @DQNEO
  2. 2. What is Dependency Injection? http://fabien.potencier.org/what-is- dependency-injection.html Fabien explained it well
  3. 3. Primitive Code class User { public function __construct() { $this->storage = new Storage(); }
  4. 4. Dependency Injection class User { public function __construct($storage) { $this->storage = $storage; }
  5. 5. class MyController { public function indexAction() { $user = new User(new Storage()); } Caller does
  6. 6. class MyController { public function indexAction($id) { $user = new User(new Storage(),$id); } Caller does
  7. 7. class MyController { public function indexAction($id) { $user = new User(new Storage(new Account()), $id); } Caller does
  8. 8. class MyController { public function indexAction($id) { $user = new User(new Storage(new Account()), $id); } Caller does Too Com plicated
  9. 9. class MyController { public function indexAction($id) { $user = new User(new Storage(new Account()), $id); } Caller does new 書 い と る や ん け
  10. 10. Solution • Depenjency Injection Container • etc
  11. 11. Pimple https://github.com/silexphp/Pimple
  12. 12. How to use Pimple // in bootstrap phase of your codes use PimpleContainer; $container = new Container(); // define a service $container['storage'] = function ($c) { return new Storage(); };
  13. 13. How to use Pimple // in business logic of your codes public function indexAction() { $storage = $this->$container[ storage ]; … }
  14. 14. Internal of Pimple class 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]); } }
  15. 15. Internal of Pimple class Container implements ArrayAccess
  16. 16. Internal of Pimple public function offsetGet($key) { $value = $this->values[$key]; return is_callable($value)? $value($this) : $value; }
  17. 17. Pimple pros/cons • Loosely Coupling • can make your app more testable Pros Cons • reduce the power of IDE (wait for PHP7) • Indirect programming

×