The document describes an object-oriented program for calculating a user's age from their name and birthday input. It introduces classes like Reader, Writer, and AgeCalculator. It then discusses improvements like dependency injection and using a factory pattern to decouple class dependencies and make the code more flexible and reusable.
2. /* ask name */
fwrite(STDOUT, "enter your name :");
$name = trim(fgets(STDIN, 255));
/* ask birthday */
fwrite(STDOUT, "enter your birthday (yyyy/mm/dd) :");
$birthday = new DateTime(trim(fgets(STDIN, 255)));
/* calculate the age */
$age = $birthday->diff(new DateTime());
Case study
/* display the result */
fwrite(
STDOUT,
sprintf(PHP_EOL."hello %s you've got %s years old.", $name, $age->y)
);
5. // src/Reader.php
class Reader
{
private $handle = STDIN;
private $length = 255;
private $writer;
public function __construct()
{
$this->writer = new Writer();
}
public function read($msg)
{
$this->writer->write($msg);
return trim(fgets($this->handle, $this->length));
}
}
6. // src/AgeCalculator.php
class AgeCalculator
{
private $reader, $writer;
public function __construct()
{
$this->reader = new Reader();
$this->writer = new Writer();
}
public function execute()
{
$name = $this->reader->read('your name:');
$birthday = new DateTime(
$this->reader->read('your birthday (yyyy/mm/dd):')
);
$age = $birthday->diff(new DateTime('now'));
$this->writer->write(
sprintf("hello %s you've got %s years old.", $name, $age->y)
);
}
}
7. // age-calculator.php
$ageCalculator = new AgeCalculator();
$ageCalculator->execute();
$ php age-calculator.php
your name: thomas
your birthday (yyyy/mm/dd): 1994/01/01
hello thomas you've got 20 years old.
Running the application
18. // src/FileWriter.php
class FileWriter extends Writer
{
public function __construct($filename, $length = 255)
{
$this->handle = fopen($filename, 'w+');
$this->length = $length;
}
}
// src/Filereader.php
class FileReader extends Reader
{
public function __construct($filename, $length = 255)
{
$this->handle = fopen($filename, 'r');
$this->length = $length;
}
}
19. // src/Factory.php
abstract class Factory
{
private $class;
public function __construct($class)
{
$this->class = new ReflectionClass($class);
}
protected abstract function configure(ReflectionClass $class);
public function create($args = array())
{
return $this->class->newInstanceArgs($args);
}
}