fuuber/util-types

提供了一种简单的类型系统,优先使用原生PHP类型,同时允许使用如'asFloat()'、'asInt()'等对象多态方法和类型检查助手。

0.1 2020-08-24 14:17 UTC

This package is auto-updated.

Last update: 2024-08-25 02:36:51 UTC


README

一个小型库,允许通过类方法在对象和标量值之间进行类型多态,例如asBool(): boolasInt(): intasFloat(): float__toString(): stringasString()以完成。

此库不打算直接替代原生PHP类型使用。该库的使用场景非常有限,例如,如果您需要实现一个简单的字节码虚拟机、数据库ORM或类似功能。在ORM中,当对象转换为整数时返回其主键可能很方便。这将允许类似以下操作:

    $father = Person::load(42); // $father is an object that implements the 'asInt(): int' method

    // The 'Fubber\Util\Type::toInt()' would be called inside the 'where()' method
    $table->where('father = :father', [ 'father' => $father ]);

基本用法

您可以使用'Type::assert*'方法代替function foo(int $bar)

function foo($bar) {
    Type::assertInt($bar);
    ...

您可以使用Type::toNumeric($foo) + Type::toNumeric($bar)代替$foo + $bar

在布尔测试时,您将使用Type::toBool($foo)方法。

可注入的类型转换

有时您需要将此功能实现到没有'asInt()'、'asFloat()'、'asString()'或'asBool()'方法的类中。在这种情况下,您可以声明一个function ClassName__asBool(ClassName $instance): bool { ... }

这也适用于命名空间类。示例

/**
 * Declaring a converter for Some\Other\Namespace\SomeClass
 * to integer
 */
namespace Some\Other\Namespace {
    function SomeClass__asInt(SomeClass $value): int {
        return $value->id;
    }
}

/**
 * Usage Examples
 */
namespace {

    $instance = new Some\Other\Namespace\SomeClass();

    if (Fubber\Util\Type::isInt($instance)) {
        echo "- it is an integer\n";
    }

    echo (10 + Fubber\Util\Type::toInt($instance))." is 10x!\n";

}

理由

由于我们需要在正在构建的Fubber\Table ORM中使用此库,因此创建了此库。特别是与CSV文件后端相关的功能。显然,我们可以将实现细节保留在Fubber\Table库中,但这样我们就必须将令人惊叹的Fubber\Util\Comparator库也保留在内 - 以此类推。

如果您想使用它,请随意使用。它没有依赖项。