定制 php-fp/php-fp-either 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

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

php-fp/php-fp-either

最新稳定版本:1.0.0

Composer 安装命令:

composer require php-fp/php-fp-either

包简介

An implementation of the Either monad in PHP.

README 文档

README

Intro

When you throw an exception in PHP, you effectively perform a GOTO: your position in the program's execution jumps to the appropriate exception handler, and execution continues. This is fine, but it obviously means that your original function has a side-effect: calling it will fundamentally alter the program flow. What we need is a functional way of accomplishing the same thing.

Enter, the Either monad. Either has two constructors, Left and Right. These work very similarly to Maybe's Just and Nothing: map, ap, and chain work as you'd expect on the Right instance, but are effectively no-ops on the Left. However, the difference is that Left, unlike Nothing, holds a value.

This means that, typically, your left branch will hold the 'exception', and the right will hold the value. If an exception happens, all future computations are ignored, and the exception can be handled in a pure way. For example:

<?php

use PhpFp\Either\Constructor\{Left, Right};

$login = function ($username, $password)
{
    if ($username != 'foo') {
        return new Left(
            'Invalid username'
        );
    }

    if ($password != 'bar') {
        return new Left(
            'Incorrect password'
        );
    }

    return new Right(['hello' => 'world']);
}

$prop = function ($k)
{
    return function ($xs) use ($k)
    {
        return isset ($xs[$k])
            ? new Right($xs[$k])
            : new Left('No such key.');
    };
};

$id = function ($x)
{
    return $x;
};

// Some examples...
$badUsername = $login('fur', 'bar')->chain($prop('id'));
$badPassword = $login('foo', 'bear')->chain($prop('id'));
$badKey = $login('foo', 'bar')->chain($prop('brian'));
$good = $login('foo', 'bar')->chain($prop('id'));

assert($badUsername->either($id, $id) === 'Invalid username');
assert($badPassword->either($id, $id) === 'Incorrect password');
assert($badKey->either($id, $id) === 'No such key.');
assert($good->either($id, $id) === 'world');

As the above shows, a failure is carried through the computation and all further operations (with the only (for now) exception of bimap below), and must be handled by either, the function for retrieving the inner value.

Of course, exceptions are the usual analogy, but Either is a more general type, and is helpful in most computations with two potential values. What if a user can input via a file or stdin? We could use Either String File, map over the instance with a File -> String function, then extract the value once we know they're both acceptable.

API

In the following type signatures, constructors and static functions are written as one would see in pure languages such as Haskell. The others contain a pipe, where the type before the pipe represents the type of the current Either instance, and the type after the pipe represents the function.

of :: a -> Either e a

This is the applicative constructor for the Either monad. It returns the given value wrapped in a Right instance:

<?php

use PhpFp\Either\Either;

$id = function ($x) { return $x; };

assert(Either::of('test')->either($id, $id) == 'test');

left :: a -> Left e a

Standard constructor for Left instances.

<?php

use PhpFp\Either\Either;
use PhpFp\Either\Constructor\Left;

$either = Either::left('test');

assert($either instanceof Either);
assert($either instanceof Left);

right :: a -> Right e a

Standard constructor for Right instances. Typically you should call Either::of instead.

<?php

use PhpFp\Either\Either;
use PhpFp\Either\Constructor\Right;

$either = Either::right('test');

assert($either instanceof Either);
assert($either instanceof Right);

tryCatch :: (-> a) -> Either e a

Sometimes, you will have a piece of exception-throwing code that you wish to wrap in an Either, and this function can help. If an exception occurs, it will be wrapped and returned in a Left. Otherwise, the returned value will be wrapped in a Right:

<?php

use PhpFp\Either\Either;

$id = function ($x) { return $x; };

$f = function () { throw new \Exception; };
$g = function () { return 'hello'; };

assert(Either::tryCatch($f)->either($id, $id) instanceof \Exception);
assert(Either::tryCatch($g)->either($id, $id) === 'hello');

ap :: Either e (a -> b) | Either e a -> Either e b

Apply an Either-wrapped argument to an Either-wrapped function, where a Left function will behave as identity.

<?php

use PhpFp\Either\Constructor\{Left, Right};

$id = function ($x) { return $x; };

$addTwo = Either::of(
    function ($x)
    {
        return $x + 2;
    }
);

$a = new Right(5);
$b = new Left(4);

assert($addTwo->ap($a)->either($id , $id) === 7);
assert($addTwo->ap($b)->either($id, $id) === 4);

bimap :: Either e a | (e -> f) -> (a -> b) -> Either f b

Sometimes, it can be useful to define computations to be performed on the Left values, and this is the way to do so. For this function, you supply left and right transformations, and the appropriate one will be used:

<?php

use PhpFp\Either\Constructor\{Left, Right};

$addOne = function ($x) { return $x + 1; };
$subOne = function ($x) { return $x - 1; };
$id = function ($x) { return $x; };

assert (Either::right(2)->bimap($addOne, $subOne)->either($id, $id) === 1);
assert (Either::left(2)->bimap($addOne, $subOne)->either($id, $id) === 3);

chain :: Either e a | (a -> Either f b) -> Either f b

The standard monadic binding function (Haskell's >>=). This is for mapping with a function that returns an Either value: instead of using map and getting Either e (Either e a), you get Either e a and the two levels are "flattened". The introduction has a good example, but here's a smaller one:

<?php

use PhpFp\Either\Constructor\{Left, Right};

$f = function ($x)
{
    return Either::of($x * 2);
}

$id = function ($x) { return $x; };

assert(Either::right(8)->chain($f)->either($id, $id) === 16);
assert(Either::left(8)->chain($f)->either($id, $id) === 8);

map :: Either e a | (a -> b) -> Either e b

This is the standard functor map, which transforms the inner value. As with the other Either operations, remember that this has no impact on a Left value, which can only be transformed with bimap:

<?php

use PhpFp\Either\Constructor\{Left, Right};

$f = function ($x) { return $x - 5; };
$id = function ($x) { return $x; };

assert(Either::right(8)->map($f)->either($id, $id) === 3);
assert(Either::left(8)->map($f)->either($id, $id) === 8);

either :: Either e a | (e -> b) -> (a -> b) -> b

This is the function that should be used to get the value out of the Either monad. Strictly, if you're being well-behaved and watching your types, the two supplied functions, while potentially accepting differently-typed inputs for Left and Right, should return values of the same type:

<?php

use PhpFp\Either\Constructor\{Left, Right};

$left = function ($x) { return (int) $x; };
$right = function ($x) { $x; };

assert(Either::left('7')->either($left, $right) === 7);
assert(Either::right(2)->either($left, $right) === 2);

Contributing

Similarly to the others, I'm aware of at least a couple of typeclasses that could be added to this implementation, so feel free to submit issues or PRs if you'd like to see others included.

However, the much more pressing concern is with the documentation: if something isn't crystal clear, please leave an issue or submit a suggested fix in order to make this as clear and descriptive as possible!

php-fp/php-fp-either 适用场景与选型建议

php-fp/php-fp-either 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 24.25k 次下载、GitHub Stars 达 46, 最近一次更新时间为 2016 年 07 月 27 日, 在 PHP 生态内属于活跃度较高的组件。

它主要适用于以下技术方向: 「functional」 「monad」 「either」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。

我们在过去多个企业项目中使用过 php-fp/php-fp-either 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 php-fp/php-fp-either 我们能提供哪些服务?
定制开发 / 二次开发

基于 php-fp/php-fp-either 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

  • 总下载量: 24.25k
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 47
  • 点击次数: 11
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 46
  • Watchers: 2
  • Forks: 4
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2016-07-27