elnur/era 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

elnur/era

Composer 安装命令:

composer require elnur/era

包简介

Date & Time Library

README 文档

README

Build Status

Era is a date & time library.

Calendar

Testing datetime-based code is difficult if it's coupled to the system time. Suppose you have an age calculator:

<?php
class AgeCalculator
{
    /**
     * @param DateTime $from
     * @return int
     */
    public function age(DateTime $from)
    {
        $now = new DateTime;

        return $from->diff($now)->y;
    }
}

And a test for it:

<?php
class AgeCalculatorTest extends PHPUnit_Framework_TestCase
{
    public function testAge()
    {
        $ageCalculator = new AgeCalculator;
        $birthdate = new DateTime('1987-05-31');

        $this->assertEquals(25, $ageCalculator->age($birthdate));
    }
}

Now, the test is brittle because it will pass only between 2012-05-31 and 2013-05-30. After that, it'll start failing.

To uncouple your code from the system time, you need an abstraction for it. Here comes Calendar:

<?php
use Elnur\Era\CalendarInterface;

class AgeCalculator
{
    /**
     * @var CalendarInterface
     */
    private $calendar;

    /**
     * @var CalendarInterface $calendar
     */
    public function __construct(CalendarInterface $calendar)
    {
        $this->calendar = $calendar;
    }

    /**
     * @param DateTime $from
     * @return int
     */
    public function age(DateTime $from)
    {
        $now = $this->calendar->now();

        return $from->diff($now)->y;
    }
}

Notice how we use a CalendarInterface instance to get the current datetime. Now, you can mock it to make the test solid:

<?php
class AgeCalculatorTest extends PHPUnit_Framework_TestCase
{
    public function testAge()
    {
        $now = new DateTime('2012-05-31');

        $calendar = $this->getMockForAbstractClass('Elnur\Era\CalendarInterface');
        $calendar
            ->expects($this->any())
            ->method('now')
            ->will($this->returnValue($now))
        ;

        $ageCalculator = new AgeCalculator($calendar);
        $birthdate = new DateTime('1987-05-31');

        $this->assertEquals(25, $ageCalculator->age($birthdate));
    }
}

Now, the test won't fail just because some time have passed.

And here's how you use your new shiny AgeCalculator:

<?php
$calendar = new Calendar;
$ageCalculator = new AgeCalculator($calendar);

$birthdate = new DateTime('1987-05-31');
$age = $ageCalculator->age($birthdate);

AgeCalculator

AgeCalculator is the class implemented above but with a tweak: if you ask it to figure out the age of something from the future, it returns 0.

统计信息

  • 总下载量: 6.65k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 2
  • 点击次数: 2
  • 依赖项目数: 0
  • 推荐数: 0

GitHub 信息

  • Stars: 2
  • Watchers: 1
  • Forks: 3
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2012-11-02

承接程序开发

PHP开发

VUE

Vue开发

前端开发

小程序开发

公众号开发

系统定制

数据库设计

云部署

网站建设

安全加固