States allows you to create PHP classes following the State Pattern in PHP.

Related tags

Laravel states
Overview

Teknoo Software - States library

Latest Stable Version Latest Unstable Version Total Downloads License PHPStan

States allows you to create PHP classes following the State Pattern in PHP. This can be a cleaner way for an object to change its behavior at runtime without resorting to large monolithic conditional statements and this improve maintainability and workflows writing.

Features

  • Create Several States : Split classes in states to avoid ununderstable large monolithic statements.
  • Inherit States and Classes : Complete and factorize states thanks to inheritance. Stated classes can be also inherited.
  • Automate States Switching : Define states switching rules based on object's properties.
  • Implement Every Where: Thanks to traits and interfaces, use this pattern on your existant code. Compatible with Doctrine.

Quick Example

name;
        };
    }

    public function displayDate(): \Closure
    {
        return function(\DateTime $now): string {
            return $now->format('m d, Y');
        };
    }
}

class French extends AbstractState
{
    public function sayHello(): \Closure
    {
        return function(): string {
            return 'Bonjour, '.$this->name;
        };
    }

    public function displayDate(): \Closure
    {
        return function(\DateTime $now): string {
            return $now->format('d m Y');
        };
    }
}

class Person implements ProxyInterface, AutomatedInterface
{
    use ProxyTrait;
    use AutomatedTrait;

    private string $name;

    private string $country;

    public function __construct()
    {
        $this->initializeStateProxy();
    }

    protected static function statesListDeclaration(): array
    {
        return [
            English::class,
            French::class
        ];
    }

    protected function listAssertions(): array
    {
        return [
            (new Property([English::class]))
                ->with('country', new IsEqual('en')),
            (new Property([French::class]))
                ->with('country', new IsEqual('fr')),
        ];
    }

    public function setName(string $name): Person
    {
        $this->name = $name;

        return $this;
    }

    public function setCountry(string $country): Person
    {
        $this->country = $country;
        $this->updateStates();

        return $this;
    }
}

$frenchMan = new Person();
$frenchMan->setCountry('fr');
$frenchMan->setName('Roger');

$englishMan = new Person();
$englishMan->setCountry('en');
$englishMan->setName('Richard');

$now = new \DateTime('2022-07-01');

foreach ([$frenchMan, $englishMan] as $man) {
    echo $man->sayHello().PHP_EOL;
    echo 'Date: '.$man->displayDate($now).PHP_EOL;
}

//Display
//Bonjour, Roger
//Date: 01 07 2022
//Good morning, Richard
//Date: 07 01, 2022

Full Example

An example of using this library is available in the folder : Demo.

Support this project

This project is free and will remain free, but it is developed on my personal time. If you like it and help me maintain it and evolve it, don't hesitate to support me on Patreon. Thanks :) Richard.

Installation & Requirements

To install this library with composer, run this command :

composer require teknoo/states

This library requires :

* PHP 8.1+
* A PHP autoloader (Composer is recommended)
* Teknoo/Immutable (for Automated features).

News from Teknoo State 6.0

This library requires PHP 8.1 or newer. Some change causes bc breaks :

  • Replace StateInterface::VISIBILITY_* by Enum Visibility in same namespace.
  • Use readonly behavior on immutables objects' classes.
  • Prevent bug of mutability on automated features with Property and ConstraintsSet.
  • ProxyInterface::DEFAULT_STATE_NAME is now final

News from Teknoo State 5.0

This library requires PHP 8.0 or newer. Some change causes bc breaks :

  • Constructor Property Promotion
  • Non-capturing catches
  • Some optimisations on array functions to limit O(n)

News from Teknoo State 4.0

This library requires PHP 7.4 or newer. Some change causes bc breaks :

  • PHP 7.4 is the minimum required
  • Most methods have been updated to include type hints where applicable. Please check your extension points to make sure the function signatures are correct. _ All files use strict typing. Please make sure to not rely on type coercion.
  • Switch to typed properties
  • Remove some PHP useless DockBlocks
  • Replace array_merge by "..." operators
  • Enable PHPStan in QA Tools and disable PHPMd
  • Add PHPStan extension dedicated to support Stated classes analyze and avoid false positive.

Quick How-to to implement your first stated class

Quick How-to to learn how to use this library : Startup.

Behavior Documentation

Documentation to explain how this library works : Behavior.

Evolutions in 3.x versions

From the version 3.2, the internal api has been redesigned to

  • Following #East programming rules.
  • Remove all public "getter" able to return the internal state of the object.
  • Clean dead code and simplify the behavior of the library.
  • Method are bound and executed by states managing object instead of object itself, but result is injected into the object.
  • This behavior allows developers to execute several implementations for a called method (but only one result must be injected).
  • Import from the extension teknoo/states-life-cyclable all automated feature. This implementation follows also the #east programming.
  • teknoo/states-life-cyclable is deprecated and not compatible with this library since 3.2.

From the version 3.1, this library provide base implementation for doctrine from teknoo/statesBundle.

  • teknoo/statesBundle is deprecated and not compatible with this library since 3.1.

From the version 3.0, this library has been redesigned to

  • States's method are now builders of closure : They must return a closure, bindable with \Closure::call(). The Reflection API is no longer used to get a closure.
  • The library uses \Closure::call() instead of \Closure::rebindTo(), more efficient.
  • States's class must be referenced declared in the proxy class, via the static method statesListDeclaration().
  • Factories and Loaders are removed, they have become useless.
  • Proxy standard can be now directly instantiate. Integrated proxy are also removed.

From the version 2.0, this library has been redesigned to

  • Reuse all composer's autoloader features instead internal autoloader.
  • Reduce the number of necessary components to the internal functioning of this library (Dependency Injector, Closure Injector).
  • Forbid the usage of slows functions like call_user_func.
  • Use Scalar Type Hinting to use PHP Engine's check instead if statements.

Credits

Richard Déloge - [email protected] - Lead developer. Teknoo Software - https://teknoo.software

About Teknoo Software

Teknoo Software is a PHP software editor, founded by Richard Déloge. Teknoo Software's goals : Provide to our partners and to the community a set of high quality services or software, sharing knowledge and skills.

License

States is licensed under the MIT License - see the licenses folder for details

Contribute :)

You are welcome to contribute to this project. Fork it on Github

You might also like...
A simple laravel state machine to handle model transitions, based on a pre-defined list of rules
A simple laravel state machine to handle model transitions, based on a pre-defined list of rules

A simple state machine that allows transitioning model states based on pre-defined rules. Installation You can install the package via composer: compo

A university system that creates a timetable programm for subjects,classes and teachers which is used to create a programm for each semester. All this served as a website.

Timetable-System-Generator A university system that creates a timetable programm for subjects,classes and teachers which is used to create a programm

Collection of classes you can use to standardize data formats in your Laravel application.
Collection of classes you can use to standardize data formats in your Laravel application.

Laravel Formatters This package is a collection of classes you can use to standardize data formats in your Laravel application. It uses the Service Co

Foreman is a Laravel scaffolding application that automates common tasks you typically perform with each new Laravel app you create
Foreman is a Laravel scaffolding application that automates common tasks you typically perform with each new Laravel app you create

Foreman is a Laravel scaffolding application that automates common tasks you typically perform with each new Laravel app you create. The directives you want Forman to perform are outlined in a JSON based template file.

A package to implement repository pattern for laravel models

Laravel Model UUID A simple package to use Repository Pattern approach for laravel models . Repository pattern Repositories are classes or components

Repository Pattern implementation for Laravel

This is a Simple Repository Pattern implementation for Laravel Projects and an easily way to build Eloquent queries from API requests.

Auto-generated Interface and Repository file via Repository pattern in Laravel

Auto-generated Repository Pattern in Laravel A repository is a separation between a domain and a persistent layer. The repository provides a collectio

Laravel Design Pattern Generator (api generator)
Laravel Design Pattern Generator (api generator)

Laravel Design Pattern Generator (api generator) you can create your restful api easily by using this library and you can filter, sort and include elo

Fast and simple implementation of a REST API based on the Laravel Framework, Repository Pattern, Eloquent Resources, Translatability, and Swagger.

Laravel Headless What about? This allows a fast and simple implementation of a REST API based on the Laravel Framework, Repository Pattern, Eloquent R

Owner
Teknoo Software
A PHP software company
Teknoo Software
A Laravel package providing a list of the countries, states, cities, currencies and timezones

A Laravel package to provide a list of the countries, cities, timezones, currencies and phone numbers formatting/validation helpers. The package can b

Najm Njeim 492 Dec 24, 2022
A simple Laravel Package to sort Countries, States and Cities

Laravel Location ▲ Introduction ?? This Package offers a simple way to get Countries, Cities and States that you may need for your Application, most e

Michael Okoh 197 Jan 1, 2023
Need some filters? This package is based on the Repository Design Pattern to let you create specific queries easily.

DevMakerLab/Laravel-Filters Need some filters? This package is based on the Repository Design Pattern to let you create specific queries easily. Insta

DevMakerLab 19 Feb 20, 2022
Collection of the Laravel/Eloquent Model classes that allows you to get data directly from a Magento 2 database.

Laragento LAravel MAgento Micro services Magento 2 has legacy code based on abandoned Zend Framework 1 with really ugly ORM on top of outdated Zend_DB

Egor Shitikov 87 Nov 26, 2022
Livewire component that provides you with a modal that supports multiple child modals while maintaining state.

About LivewireUI Modal LivewireUI Modal is a Livewire component that provides you with a modal that supports multiple child modals while maintaining s

Livewire UI 806 Jan 6, 2023
Livewire component that provides you with a modal that supports multiple child modals while maintaining state.

About Wire Elements Modal Wire Elements Modal is a Livewire component that provides you with a modal that supports multiple child modals while maintai

Wire Elements 806 Jan 6, 2023
This tool gives you the ability to set the default collapse state for Nova 4.0 menu items.

Nova Menu Collapsed This tool gives you the ability to set the default collapse state for Nova 4.0 menu items. Requirements php: >=8.0 laravel/nova: ^

Artem Stepanenko 10 Nov 17, 2022
🏭This package lets you create factory classes for your Laravel project.

Laravel Factories Reloaded ?? This package generates class-based model factories, which you can use instead of the ones provided by Laravel. Laravel 8

Christoph Rumpel 372 Dec 27, 2022
🖖Repository Pattern in Laravel. The package allows to filter by request out-of-the-box, as well as to integrate customized criteria and any kind of filters.

Repository Repository Pattern in Laravel. The package allows to filter by request out-of-the-box, as well as to integrate customized criteria and any

Awes.io 160 Dec 26, 2022
Active State Helper for Laravel Blade

laravel-activehelper Active State Helper for Laravel Blade Lightweight and simple Introduction Basically we do like this. <li class="sidebar {{ Reques

Ahmad Irsyadul Ibad 4 Sep 25, 2022