如何添加新的碳功能来处理laravel中的碳日期?

Ram*_*ami 2 php datetime date laravel php-carbon

我知道碳是如何工作的,但我想创造定制的碳功能.carbon有一个函数调用diffForHumans(),我想对该函数进行一些修改并调用该函数diffForHumansCustom().如果我编辑Carbon.php供应商文件,我可以实现我的目标,但修改将会消失composer update.任何建议或代码帮助表示赞赏.

原始功能

public function diffForHumans(Carbon $other = null, $absolute = false)
    {
        $isNow = $other === null;

        if ($isNow) {
            $other = static::now($this->tz);
        }

        $diffInterval = $this->diff($other);

        switch (true) {
            case ($diffInterval->y > 0):
                $unit = 'year';
                $delta = $diffInterval->y;
                break;

            case ($diffInterval->m > 0):
                $unit = 'month';
                $delta = $diffInterval->m;
                break;

            case ($diffInterval->d > 0):
                $unit = 'day';
                $delta = $diffInterval->d;
                if ($delta >= self::DAYS_PER_WEEK) {
                    $unit = 'week';
                    $delta = floor($delta / self::DAYS_PER_WEEK);
                }
                break;

            case ($diffInterval->h > 0):
                $unit = 'hour';
                $delta = $diffInterval->h;
                break;

            case ($diffInterval->i > 0):
                $unit = 'minute';
                $delta = $diffInterval->i;
                break;

            default:
                $delta = $diffInterval->s;
                $unit = 'second';
                break;
        }

        if ($delta == 0) {
            $delta = 1;
        }

        $txt = $delta . ' ' . $unit;
        $txt .= $delta == 1 ? '' : 's';

        if ($absolute) {
            return $txt;
        }

        $isFuture = $diffInterval->invert === 1;

        if ($isNow) {
            if ($isFuture) {
                return $txt . ' from now';
            }

            return $txt . ' ago';
        }

        if ($isFuture) {
            return $txt . ' after';
        }

        return $txt . ' before';
    }
Run Code Online (Sandbox Code Playgroud)

我修改过的功能

public function diffForHumansCustom(Carbon $other = null, $absolute = false)
    {
        $isNow = $other === null;

        if ($isNow) {
            $other = static::now($this->tz);
        }

        $diffInterval = $this->diff($other);

        switch (true) {
            case ($diffInterval->y > 0):
                $unit = 'year';
                $delta = $diffInterval->y;
                break;

            case ($diffInterval->m > 0):
                $unit = 'month';
                $delta = $diffInterval->m;
                break;

            case ($diffInterval->d > 0):
                $unit = 'day';
                $delta = $diffInterval->d;
                if ($delta >= self::DAYS_PER_WEEK) {
                    $unit = 'week';
                    $delta = floor($delta / self::DAYS_PER_WEEK);
                }
                break;

            case ($diffInterval->h > 0):
                $unit = 'hour';
                $delta = $diffInterval->h;
                break;

            case ($diffInterval->i > 0):
                $unit = 'minute';
                $delta = $diffInterval->i;
                break;

            default:
                $delta = $diffInterval->s;
                $unit = 'second';
                break;
        }

        if ($delta == 0) {
            $delta = 1;
        }

        $txt = $delta . ' ' . $unit;
        $txt .= $delta == 1 ? '' : 's';
        if($unit == 'second' && $delta<=59) {
           return 'Just now';
        }

        // Greater than 3 days
        // [xx] [Month] [year, only displays if not current year'] at [time in 24 clock].
        if(($unit == 'day' && $delta > 3) || ($unit == 'week') || ($unit == 'month') || ($unit == 'year')) {
           $timestamp = $this->getTimestamp();
           $curYear = date('Y');
           $y = ($curYear == date('Y', $timestamp)) ? '': date('Y', $timestamp);
           $date = date('j F '.$y, $timestamp);
           $time = date('H:i', $timestamp);
           $txt = rtrim($date).' at '.$time;
           return $txt;
        }
        if ($absolute) {
            return $txt;
        }

        $isFuture = $diffInterval->invert === 1;

        if ($isNow) {
            if ($isFuture) {
                return $txt . ' from now';
            }

            return $txt . ' ago';
        }

        if ($isFuture) {
            return $txt . ' after';
        }

        return $txt . ' before';
    }
Run Code Online (Sandbox Code Playgroud)

Poi*_*oiz 7

您可以扩展碳类,然后使用您的子类代替碳,或者只需diffForHumansCustom()使用方法创建特征并在您的类中使用它

扩展碳\碳:

<?php

    namespace App\Http\Controllers\Helpers;

    use Carbon\Carbon;

    class CarbonCopy extends Carbon {

        public function diffForHumansCustom(Carbon $other = null, $absolute = false) {
            // YOUR UNIQUE IMPLEMENTATION, CODE & LOGIC...
        }

    }
Run Code Online (Sandbox Code Playgroud)

使用Trait代替:

<?php

    namespace App\Http\Controllers\Helpers;

    use Carbon\Carbon;

    trait CarbonT {     

        public function diffForHumansCustom(Carbon $other = null, $absolute = false) {
            // YOUR UNIQUE IMPLEMENTATION, CODE & LOGIC...
        }

    }
Run Code Online (Sandbox Code Playgroud)

控制器内部的使用:作为特征

<?php
    namespace App\Http\Controllers;
    use App\Http\Controllers\Helpers\CarbonT;
    use Carbon\Carbon;
    use Illuminate\Http\Request;
    use App\Http\Requests;
    use App\User;

    class TestController extends Controller {

        use CarbonT;

        public function carbonRelatedOperation(){
            $cbnDate    = Carbon::createFromFormat("Y-m-d H:i:s", "2016-05-02 11:11:11");
            $customDiff = $this->diffForHumansCustom($cbnDate);

            dd( $customDiff );

        }
    }
Run Code Online (Sandbox Code Playgroud)

控制器内部的使用:作为碳的子类

<?php
    namespace App\Http\Controllers;
    use App\Http\Controllers\Helpers\CarbonCopy;
    use Carbon\Carbon;
    use Illuminate\Http\Request;
    use App\Http\Requests;
    use App\User;

    class TestController extends Controller {

        public function carbonRelatedOperation(){
            $cbnDate    = Carbon::createFromFormat("Y-m-d H:i:s", "2016-05-02 11:11:11");
            $cbCopy     = new CarbonCopy();

            dd( $cbCopy->diffForHumansCustom($cbnDate) );

        }
    }
Run Code Online (Sandbox Code Playgroud)


Sph*_*olt 6

对于 2019 年来到这里的任何人,我发现添加Carbon::macro函数之类的东西的更简洁的解决方案是使用 LaravelServiceProvider

1)创建您的服务提供者 php artisan make:provider CarbonServiceProvider

碳服务提供者

<?php

namespace App\Providers;

use Carbon\Carbon;
use Illuminate\Support\ServiceProvider;

class CarbonServiceProvider extends ServiceProvider
{
    /**
     * Register services.
     */
    public function register()
    {
    }

    /**
     * Bootstrap services.
     */
    public function boot()
    {
        Carbon::macro('easterDate', function ($year) {
            return Carbon::createMidnightDate($year, 3, 21)->addDays(easter_days($year));
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

2) 注册您的服务提供商 config/app.php

应用程序/配置

<?php

return [

    'providers' => [

        ...

        /*
         * Application Service Providers...
         */
        App\Providers\AppServiceProvider::class,
        App\Providers\AuthServiceProvider::class,
        App\Providers\BroadcastServiceProvider::class,
        App\Providers\EventServiceProvider::class,
        App\Providers\RouteServiceProvider::class,
        App\Providers\DatabaseServiceProvider::class,
        App\Providers\CarbonServiceProvider::class,

        ...
    ],
];
Run Code Online (Sandbox Code Playgroud)

3) 您现在可以从应用程序的任何位置访问您的宏。

示例控制器

<?php

namespace App\Http\Controllers;

use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class ExampleController extends Controller
{
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        dd(Carbon::easterDate(2015));
    }
}
Run Code Online (Sandbox Code Playgroud)

在示例中,这应该返回

Carbon @1428192000 {#2663 ?
  date: 2015-04-05 00:00:00.0 UTC (+00:00)
}
Run Code Online (Sandbox Code Playgroud)

享受!