Download the PHP package ahmedashraf093/better-eloquent-state-machine without Composer

On this page you can find all versions of the php package ahmedashraf093/better-eloquent-state-machine. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package better-eloquent-state-machine

Latest Version on Packagist Total Downloads

Eloquent State Machine

Introduction

This package provides a very simple and easy API to reliably manage your state machines (the ever changing state of your models) within your eloquent models all in one file. using a simple one liners to do all the validation, logging and execution of your state transitions.

based on the work of asantibanez's state machine laravel-eloquent-state-machines

Examples

Model with two status fields

Transitioning from one state to another

Checking available transitions

Checking current state

Checking transitions history

Features

Demo

You can check a demo and examples here

demo

Installation

You can install the package via composer:

Next, you must export the package migrations

Finally, prepare required database tables

Usage

Defining our StateMachine

Imagine we have a SalesOrder model which has a status field for tracking the different stages our sales order can be in the system: REGISTERED, APPROVED, PROCESSED or DECLINED.

We can manage and centralize all of these stages and transitions within a StateMachine class. To define one, we can use the php artisan make:state-machine command.

For example, we can create a StatusStateMachine for our SalesOrder model

After running the command, we will have a new StateMachine class created in the App\StateMachines directory. The class will have the following code.

Inside this class, we can define our states and allowed transitions

Wildcards are allowed to allow any state change

We can define the default/starting state too

The StateMachine class allows recording each one of the transitions automatically for you. To enable this behavior, we must set recordHistory() to return true;

Registering our StateMachine

Once we have defined our StateMachine, we can register it in our SalesOrder model, in a $stateMachine attribute. Here, we set the bound model field and state machine class that will control it.

State Machine Methods

When registering $stateMachines in our model, each state field will have it's own custom method to interact with the state machine and transitioning methods. The HasStateMachines trait defines one method per each field mapped in $stateMachines. Eg.

For

We will have an accompanying method

with which we can use to check our current state, history and apply transitions.

Note: the field "status" will be kept intact and in sync with the state machine

Transitioning States

To transition from one state to another, we can use the transitionTo method. Eg:

You can also pass in $customProperties if needed

A $responsible can be also specified. By default, auth()->user() will be used

When applying the transition, the state machine will verify if the state transition is allowed according to the transitions() states we've defined. If the transition is not allowed, a Ashraf\EloquentStateMachine\Exceptions\TransitionNotAllowed exception will be thrown.

Querying History

If recordHistory() is set to true in our State Machine, each state transition will be recorded in the package StateHistory model using the state_histories table that was exported when installing the package.

With recordHistory() turned on, we can query the history of states our field has transitioned to. Eg:

As seen above, we can check whether or not our field has transitioned to one of the queried states.

We can also get the latest snapshot or all snapshots for a given state

The full history of transitioned states is also available

The history() method returns an Eloquent relationship that can be chained with the following scopes to further down the results.

Using Query Builder

The HasStateMachines trait introduces a helper method when querying your models based on the state history of each state machine. You can use the whereHas{FIELD_NAME} (eg: whereHasStatus, whereHasFulfillment) to add constraints to your model queries depending on state transitions, responsible and custom properties.

The whereHas{FIELD_NAME} method accepts a closure where you can add the following type of constraints:

The $from and $to parameters can be either a status name as a string or an array of status names.

Getting Custom Properties

When applying transitions with custom properties, we can get our registered values using the getCustomProperty($key) method. Eg.

This method will reach for the custom properties of the current state. You can get custom properties of previous states using the snapshotWhen($state) method.

Getting Responsible

Similar to custom properties, you can retrieve the $responsible object that applied the state transition.

This method will reach for the responsible of the current state. You can get responsible of previous states using the snapshotWhen($state) method.

Note: responsible can be null if not specified and when the transition happens in a background job. This is because no auth()->user() is available.

Advanced Usage

Tracking Attribute Changes

When recordHistory() is active, model state transitions are recorded in the state_histories table. Each transition record contains information about the attributes that changed during the state transition. You can get information about what has changed via the changedAttributesNames() method. This method will return an array of the attributes names that changed. With these attributes names, you can then use the methods changedAttributeOldValue($attributeName) and changedAttributeNewValue($attributeName) to get the old and new values respectively.

Adding Validations

Using closure functions

Using closure function to do per state validation before transitioning to the next state.

here is an example of a state machine that allows any user to approve a sales order but only users can decline it.

the arrow function

will be called before transitioning to the next state and will be passed the model and the responsible for the transition. the bool value returned by the function will determine if the transition will be allowed or not.

a more complex example would be to allow only users with a specific role to approve a sales order.

Get available transitions

using the ->stateMachine->availableTransitions() method you can get all the available transitions from the current state with all validation applied.

different validations can be applied to the same transition depending on the responsible for the transition.

Adding Hooks

We can also add custom hooks/callbacks that will be executed before/after a transition is applied. To do so, we must override the beforeTransitionHooks() and afterTransitionHooks() methods in our state machine accordingly.

Both transition hooks methods must return a keyed array with the state as key, and an array of callbacks/closures to be executed.

NOTE: The keys for beforeTransitionHooks() must be the $from states.

NOTE: The keys for afterTransitionHooks() must be the $to states.

Example

Testing

Changelog

Please see CHANGELOG for more information what has changed recently.

Contributing

Please see CONTRIBUTING for details.

Security

If you discover any security related issues, please email [email protected] instead of using the issue tracker.

Credits

License

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


All versions of better-eloquent-state-machine with dependencies

PHP Build Version
Package Version
Requires php Version ^7.3|^7.4|^8.0
illuminate/support Version ^6.0|^7.0|^8.0|^9.0|^10.0
javoscript/laravel-macroable-models Version ^1.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package ahmedashraf093/better-eloquent-state-machine contains the following files

Loading the files please wait ....