Advertisement
Guest User

DIC over multiple dependencies

a guest
Oct 29th, 2014
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.21 KB | None | 0 0
  1. /**
  2.  * Passing multiple dependencies
  3.  */
  4. //Create the dependencies or retrieve them from the registry
  5. $connection = new Connection();
  6. $session = new Session();
  7. $fileSystem = new FileSystem();
  8. $filter = new Filter();
  9. $selector = new Selector();
  10.  
  11. //Pass them as constructor parameters
  12. $some = new SomeComponent($connection, $session, $fileSystem, $filter, $selector);
  13.  
  14. // ... or using setters
  15.  
  16. $some->setConnection($connection);
  17. $some->setSession($session);
  18. $some->setFileSystem($fileSystem);
  19. $some->setFilter($filter);
  20. $some->setSelector($selector);
  21.  
  22.  
  23. /**
  24.  * Using a DIC to set the dependencies and pass it as a single argument
  25.  */
  26. $di = new DIC();
  27.  
  28. //Register a "db" service in the container
  29. $di->set('db', function() {
  30.     return new Connection(array(
  31.         "host" => "localhost",
  32.         "username" => "root",
  33.         "password" => "secret",
  34.         "dbname" => "invo"
  35.     ));
  36. });
  37.  
  38. //Register a "filter" service in the container
  39. $di->set('filter', function() {
  40.     return new Filter();
  41. });
  42.  
  43. //Register a "session" service in the container
  44. $di->set('session', function() {
  45.     return new Session();
  46. });
  47.  
  48. //Pass the service container as unique parameter
  49. $some = new SomeComponent($di);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement