danielefavi/fluent-api

Class designed for fluent API interface: you can invoke the same method statically and non-statically.

1.0.1 2022-01-15 06:09 UTC

This package is auto-updated.

Last update: 2024-12-15 12:33:03 UTC


README

PHP package for fluent API interfaces: you can invoke a method both statically and non-statically.

Installation

composer require danielefavi/fluent-api

Usage

1) Import the FluentApi class in the file you need it.

use DanieleFavi\FluentApi\FluentApi;

2) Extend your class with FluentApi class.

class FluentMath extends FluentApi
{

}

3) Create your methods that can be invoked statically and non-statically.

Declare the functions that can be called statically or non-statically with an underscore _.

In the example below the functions add and subtract can be invoked statically or non-statically.

class FluentMath extends FluentApi
{
    private $result = 0;

    protected function _add($num)
    {
        $this->result += $num;

        return $this;
    }

    protected function _subtract($num)
    {
        $this->result -= $num;

        return $this;
    }

    public function result()
    {
        return $this->result;
    }
}

4) Example of usage

$res1 = FluentMath::add(5)
    ->add(3)
    ->subtract(2)
    ->add(8)
    ->result();

$res2 = FluentMath::subtract(1)
    ->add(10)
    ->result();

// $res1 equals to 14
// $res2 equals to 9