mqlo/nameable-cast

此包最适合与Laravel、Lumen的mqlo/nameable包配合使用

v2.5 2021-02-19 17:04 UTC

This package is auto-updated.

Last update: 2021-10-06 18:33:51 UTC


README

  • $nameable->name(), $nameable->value();
  • 'name' => $this->name(), 'value' => $this->value().

此包最适合与mqlo/nameable包配合使用,适用于Laravel和Lumen。

示例 #1

帖子

    /**
     * @property PostStatus $status
    */
    class Post extends Model
    {
        protected $casts = [
            'status' => PostStatusCast::class,
        ];
    ...
    }

帖子状态

    use Mqlo\Nameable\Nameable;

    class PostStatus extends Nameable
    {
        public const DRAFT = 'draft';
        public const PUBLISHED = 'published';

        protected static array $all = [
            self::DRAFT => 'Draft',
            self::PUBLISHED => 'Published',
        ];

        public static function draft(): self
        {
            return new self(self::DRAFT);
        }

        public static function published(): self
        {
            return new self(self::PUBLISHED);
        }

        public function isDraft(): bool
        {
            return $this->name === self::DRAFT;
        }
        
        public function isPublished(): bool
        {
            return $this->name === self::PUBLISHED;
        }
    }

帖子状态转换

    use Mqlo\NameableCast\NameableCast;

    class PostStatusCast extends NameableCast
    {
        protected function nameableClass(): string
        {
            return PostStatus::class;
        }
    }

帖子创建

    $post = new Post();
    $post->status = PostStatus::draft();
    $post->save();

    //or
    
    $post = Post::create(['status' => PostStatus::DRAFT]);

    //validation
    $this->validate($request, [
        'title' => 'required|string|max:255',
        'status' => 'required|in:' . implode(',', PostStatus::all(false))
    ]);

使用

    echo $post->status->isDraft() ? 'This post draft.' : '...'; 

    PostStatus::all(true); // with descriptions
    PostStatus::all(false); // without descriptions

    return $post;
        
    [
        ...,
        'status' => [
            'name' => 'draft',
            'label' => 'Draft'
        ]
    ]

示例表

  • 令牌
id 类型 过期时间
1 邮箱确认 2020-10-01 19:00:00
2 密码重置 2020-10-01 19:30:00
... ... ...
  • 帖子
id 标题 状态
1 帖子 1 草稿
2 帖子 2 已发布
... ... ...