fsmdev/constants-collection

1.0.3 2021-06-14 06:02 UTC

This package is auto-updated.

Last update: 2024-09-14 12:53:04 UTC


README

英文 | 俄语

一个简单的PHP类,允许您创建常量集合,分配属性,获取属性和常量的数组。

安装

composer require fsmdev/constants-collection

使用

常量集合

Fsmdev\ConstantsCollection\ConstantsCollection 继承您的类并定义常量。

use Fsmdev\ConstantsCollection\ConstantsCollection;

class PostStatus extends ConstantsCollection
{
    const EDITED = 1;
    const PUBLISHED = 2;
    const DELETED = 3;
}

示例

$post = new Post();
$post->status = PostStatus::PUBLISHED;
class Post
{
    public function isPublished()
    {
        return $this->status == PostStatus::PUBLISHED;
    }
}

要获取常量的数组,请使用 valuesArray 方法

valuesArray () : array

属性

可以为每个常量设置命名属性。为此,需要在一个类中定义一个函数,该函数根据以下模式构建:properties + PropertyName (camel case)。该方法必须返回一个数组,其键是常量的值,值是属性的值。

# class PostStatus

protected static function propertiesName()
{
    return [
        self::EDITED => 'Edited',
        self::PUBLISHED => 'Published',
        self::DELETED => 'Deleted',
    ];
}

protected static function propertiesIndicatorClass()
{
    return [
        self::EDITED => 'text-warning',
        self::PUBLISHED => 'text-success',
        self::DELETED => 'text-danger',
    ];
}

可以使用 property 静态方法获取属性

property ( mixed $value [, string $property = 'name' ] ) : mixed

示例(Blade)

Status:
<span class="{{ PostStatus::property($post->status, 'indicator_class') }}">
    {{ PostStatus::property($post->status) }}
</span>

您可以使用 propertiesArray 静态方法获取属性数组

propertiesArray ( [ string $property = 'name' ] ) : array

通过属性获取值

value ( mixed $value [, string $property = 'name' ] ) : mixed
$status = PostStatus::value('Edited');

Packagist.org

https://packagist.org.cn/packages/fsmdev/constants-collection