spatie/laravel-model-status 问题修复 & 功能扩展

解决BUG、新增功能、兼容多环境部署,快速响应你的开发需求

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

spatie/laravel-model-status

Composer 安装命令:

composer require spatie/laravel-model-status

包简介

A package to enable assigning statuses to Eloquent Models

README 文档

README

Latest Version on Packagist GitHub Workflow Status Check & fix styling Total Downloads

Imagine you want to have an Eloquent model hold a status. It's easily solved by just adding a status field to that model and be done with it. But in case you need a history of status changes or need to store some extra info on why a status changed, just adding a single field won't cut it.

This package provides a HasStatuses trait that, once installed on a model, allows you to do things like this:

// set a status
$model->setStatus('pending', 'needs verification');

// set a status using an enum
$model->setStatus(UserStatus::pending);

// set another status
$model->setStatus('accepted');

// specify a reason
$model->setStatus('rejected', 'My rejection reason');

// get the current status
$model->status(); // returns an instance of \Spatie\ModelStatus\Status

// get the previous status
$latestPendingStatus = $model->latestStatus('pending');

$latestPendingStatus->reason; // returns 'needs verification'

Support us

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products.

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall.

Installation

You can install the package via composer:

composer require spatie/laravel-model-status

You must publish the migration with:

php artisan vendor:publish --provider="Spatie\ModelStatus\ModelStatusServiceProvider" --tag="migrations"

Migrate the statuses table:

php artisan migrate

Optionally you can publish the config-file with:

php artisan vendor:publish --provider="Spatie\ModelStatus\ModelStatusServiceProvider" --tag="config"

This is the contents of the file which will be published at config/model-status.php

return [

    /*
     * The class name of the status model that holds all statuses.
     *
     * The model must be or extend `Spatie\ModelStatus\Status`.
     */
    'status_model' => Spatie\ModelStatus\Status::class,

    /*
     * The name of the column which holds the ID of the model related to the statuses.
     *
     * You can change this value if you have set a different name in the migration for the statuses table.
     */
    'model_primary_key_attribute' => 'model_id',

];

Usage

Add the HasStatuses trait to a model you like to use statuses on.

use Spatie\ModelStatus\HasStatuses;

class YourEloquentModel extends Model
{
    use HasStatuses;
}

Set a new status

You can set a new status like this:

$model->setStatus('status-name');

A reason for the status change can be passed as a second argument.

$model->setStatus('status-name', 'optional reason');

setStatus and forceSetStatus also accept enums:

enum UserStatus: string
{
    case pending = 'pending';
    case accepted = 'accepted';
}

$model->setStatus(UserStatus::pending);

Backed enums are stored using their value. Unit enums are stored using their case name.

Restrict statuses to an enum

You can restrict which statuses a model accepts by overriding the statusEnumClass method:

class YourEloquentModel extends Model
{
    use HasStatuses;

    public function statusEnumClass(): ?string
    {
        return UserStatus::class;
    }
}

When statusEnumClass() returns an enum class, setStatus(...) only accepts statuses that belong to that enum. forceSetStatus(...) always bypasses this validation.

Retrieving statuses

You can get the current status of model:

$model->status; // returns a string with the name of the latest status

$model->status(); // returns the latest instance of `Spatie\ModelStatus\Status`

$model->latestStatus(); // equivalent to `$model->status()`

$model->statusEnum(); // returns the latest enum case when statusEnumClass() is configured, otherwise null

statusEnum() also returns null when there is no status yet, or when the latest stored status does not map to the configured enum.

You can also get latest status of a given name:

$model->latestStatus('pending'); // returns an instance of `Spatie\ModelStatus\Status` that has the name `pending`

Get all available status names for the model.

$statusNames = $model->getStatusNames(); // returns a collection of all available status names.

The following examples will return statusses of type status 1 or status 2, whichever is latest.

$lastStatus = $model->latestStatus(['status 1', 'status 2']);

// or alternatively...
$lastStatus = $model->latestStatus('status 1', 'status 2');

All associated statuses of a model can be retrieved like this:

$allStatuses = $model->statuses;

This will check if the model has status:

$model->setStatus('status1');

$isStatusExist = $model->hasStatus('status1'); // return true
$isStatusExist = $model->hasStatus('status2'); // return false

Retrieving models with a given latest state

The currentStatus scope will return models that have a status with the given name.

$allPendingModels = Model::currentStatus('pending');

//or array of statuses
$allPendingModels = Model::currentStatus(['pending', 'initiated']);
$allPendingModels = Model::currentStatus('pending', 'initiated');

Retrieving models without a given state

The otherCurrentStatus scope will return all models that do not have a status with the given name, including any model that does not have any statuses associated with them.

$allNonPendingModels = Model::otherCurrentStatus('pending');

You can also provide an array of status names to exclude from the query.

$allNonInitiatedOrPendingModels = Model::otherCurrentStatus(['initiated', 'pending']);

// or alternatively...
$allNonInitiatedOrPendingModels = Model::otherCurrentStatus('initiated', 'pending');

Validating a status before setting it

You can add custom validation when setting a status by overwriting the isValidStatus method:

public function isValidStatus(string $name, ?string $reason = null): bool
{
    ...

    if (! $condition) {
        return false;
    }

    return true;
}

If isValidStatus returns false a Spatie\ModelStatus\Exceptions\InvalidStatus exception will be thrown.

You may bypass validation with the forceSetStatus method:

$model->forceSetStatus('invalid-status-name');

Check if status has been assigned

You can check if a specific status has been set on the model at any time by using the hasEverHadStatus method:

$model->hasEverHadStatus('status 1');

Check if status has never been assigned

You can check if a specific status has never been set on the model at any time by using the hasNeverHadStatus method:

$model->hasNeverHadStatus('status 1');

Delete status from model

You can delete any given status that has been set on the model at any time by using the deleteStatus method:

Delete single status from model:

$model->deleteStatus('status 1');

Delete multiple statuses from model at once:

$model->deleteStatus(['status 1', 'status 2']);

Events

TheSpatie\ModelStatus\Events\StatusUpdated event will be dispatched when the status is updated.

namespace Spatie\ModelStatus\Events;

use Illuminate\Database\Eloquent\Model;
use Spatie\ModelStatus\Status;

class StatusUpdated
{
    /** @var \Spatie\ModelStatus\Status|null */
    public $oldStatus;

    /** @var \Spatie\ModelStatus\Status */
    public $newStatus;

    /** @var \Illuminate\Database\Eloquent\Model */
    public $model;

    public function __construct(?Status $oldStatus, Status $newStatus, Model $model)
    {
        $this->oldStatus = $oldStatus;

        $this->newStatus = $newStatus;

        $this->model = $model;
    }
}

Custom model and migration

You can change the model used by specifying a class name in the status_model key of the model-status config file.

You can change the column name used in the status table (model_id by default) when using a custom migration where you changed that. In that case, simply change the model_primary_key_attribute key of the model-status config file.

Testing

This package contains integration tests that are powered by orchestral/testbench.

You can run all tests with:

composer test

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you've found a bug regarding security please mail security@spatie.be instead of using the issue tracker.

Credits

License

The MIT License (MIT). Please see License File for more information.

spatie/laravel-model-status 适用场景与选型建议

spatie/laravel-model-status 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 1.87M 次下载、GitHub Stars 达 1.05k, 最近一次更新时间为 2018 年 02 月 06 日, 在 PHP 生态内属于活跃度较高的组件。

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

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

围绕 spatie/laravel-model-status 我们能提供哪些服务?
定制开发 / 二次开发

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

BUG 修复 & 性能优化

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

项目外包 & 长期维护

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

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

统计信息

  • 总下载量: 1.87M
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 1057
  • 点击次数: 25
  • 依赖项目数: 20
  • 推荐数: 0

GitHub 信息

  • Stars: 1053
  • Watchers: 14
  • Forks: 85
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2018-02-06