Advertisement
Guest User

Untitled

a guest
Dec 11th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.40 KB | None | 0 0
  1. // Let's say we need to get the date in our project.
  2.  
  3. class DateStuff {
  4.     function isItFriday() {
  5.         return (date('w') == 5)
  6.     }
  7. }
  8.  
  9. // How do you test that? You'd have to run the test on a Friday to get the right input. We can create an abstraction of the date function to get around this:
  10.  
  11. // The interface that defines how our date class should look
  12. interface IDateManager {
  13.     function getDayOfWeekIndex();
  14. }
  15.  
  16. // And here's an implementation of that interface
  17. class DateManager implements IDateManager {
  18.     function getDayOfWeekIndex() {
  19.         return date('w');
  20.     }
  21. }
  22.  
  23. // Now we add the dependency:
  24.  
  25. class DateStuff {
  26.     private $dateManager;
  27.     function __construct(IDateManager $d) {
  28.         $this->dateManager = $d;
  29.     }
  30.     function isItFriday() {
  31.         return ($this->dateManager->getDayOfWeekIndex()  == 5)
  32.     }
  33. }
  34.  
  35. // So to use that class, you'd have to instantiate a DateManager and pass it to the DateStuff class when you create it:
  36.  
  37. $dm = new DateManager();
  38. $d = new DateStuff($dm);
  39. echo $d->isItFriday();
  40.  
  41. // Now its easier to test this class by creating a deterministic implementation of our date manager:
  42.  
  43. class DeterministicDateManager implements IDateManager {
  44.     function getDayOfWeekIndex() {
  45.         return 5;
  46.     }
  47. }
  48.  
  49. // Now we can go:
  50.  
  51. $dm = new DeterministicDateManager();
  52. $d = new DateStuff($dm);
  53. echo $d->isItFriday(); // Always true
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement