Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Let's say we need to get the date in our project.
- class DateStuff {
- function isItFriday() {
- return (date('w') == 5)
- }
- }
- // 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:
- // The interface that defines how our date class should look
- interface IDateManager {
- function getDayOfWeekIndex();
- }
- // And here's an implementation of that interface
- class DateManager implements IDateManager {
- function getDayOfWeekIndex() {
- return date('w');
- }
- }
- // Now we add the dependency:
- class DateStuff {
- private $dateManager;
- function __construct(IDateManager $d) {
- $this->dateManager = $d;
- }
- function isItFriday() {
- return ($this->dateManager->getDayOfWeekIndex() == 5)
- }
- }
- // So to use that class, you'd have to instantiate a DateManager and pass it to the DateStuff class when you create it:
- $dm = new DateManager();
- $d = new DateStuff($dm);
- echo $d->isItFriday();
- // Now its easier to test this class by creating a deterministic implementation of our date manager:
- class DeterministicDateManager implements IDateManager {
- function getDayOfWeekIndex() {
- return 5;
- }
- }
- // Now we can go:
- $dm = new DeterministicDateManager();
- $d = new DateStuff($dm);
- echo $d->isItFriday(); // Always true
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement