PHPackages                             grifart/enum - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. grifart/enum

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

grifart/enum
============

Provides bullet proof enums with behaviours.

0.2.1(6y ago)22276.3k↓10.3%3[3 issues](https://github.com/grifart/enum/issues)1MITPHPPHP &gt;=7.1.0

Since Nov 2Pushed 3y ago4 watchersCompare

[ Source](https://github.com/grifart/enum)[ Packagist](https://packagist.org/packages/grifart/enum)[ RSS](/packages/grifart-enum/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (2)Dependencies (4)Versions (8)Used By (1)

grifart/enum
============

[](#grifartenum)

Enumeration value object. Enumerate values and behaviour with type-safety.

Repositories [gitlab.grifart.cz](https://gitlab.grifart.cz/jkuchar1/grifart-enum)and [github.com](https://github.com/grifart/enum). [![pipeline status](https://camo.githubusercontent.com/5c74bfab5e809abffe7a25c91870c992ee04930990f8ecc07d5694a5da4e9c9e/68747470733a2f2f6769746c61622e677269666172742e637a2f6a6b7563686172312f677269666172742d656e756d2f6261646765732f6d61737465722f706970656c696e652e737667)](https://gitlab.grifart.cz/jkuchar1/grifart-enum/commits/master)

Sponsored by [grifart.com](https://grifart.com).

Do you like video 📺 instead of reading? Here is one in [english](http://bit.ly/better-enum-for-php) and one in [czech](http://bit.ly/lepsi-enum-pro-php).

Introduction
------------

[](#introduction)

Enums represent predefined set of values. The available values are defined statically by each enum class. Each value is represented by an instance of this class in a flyweight manner.

- This enum allows you to add individual behaviour for every enum value (as in Java). This allows you to transform your `switch`es/`if`s into more readable composition. (see example bellow)
- Checks enum annotations if phpdoc-declared methods are properly declared (will generate docblock for you when not specified or incorrect)
- `===`, `==` and usage of `switch`es is supported
- string or integer scalar keys are supported
- Easily access scalar value of enum `DayOfWeek::MONDAY()->toScalar()` or `(string) DayOfWeek::MONDAY()`

Also includes:

- It is type safe. By annotating your enumeration type, you are guaranteed that there will be no other values then you declared. `function translateTo(DayOfWeek $day) { ...`
- You can get a list of all the possible values `Enum::getAvailableValues()`

Installation
------------

[](#installation)

```
composer require grifart/enum
```

This library uses [**semantic versioning 2.0**](https://semver.org/spec/v2.0.0.html). You can safely use `^` constrain in you `composer.json`.

Requirements
------------

[](#requirements)

This library requires PHP 7.1 and later.

Project status &amp; release process
------------------------------------

[](#project-status--release-process)

While this library is still under development, it is well tested and should be stable enough to use in production environments.

The current releases are numbered 0.x.y. When a non-breaking change is introduced (adding new methods, optimizing existing code, etc.), y is incremented.

When a breaking change is introduced, a new 0.x version cycle is always started.

It is therefore safe to lock your project to a given release cycle, such as 0.1.\*.

If you need to upgrade to a newer release cycle, check the release history for a list of changes introduced by each further 0.x.0 version.

Overview
--------

[](#overview)

### Static methods

[](#static-methods)

- fromScalar() - returns enum instance (value) for given scalar
- getAvailableValues() - returns all values for given type
- provideInstances() - implement to return enum instances or automatically implemented by `Grifart\Enum\AutoInstances` trait.

### Instance methods

[](#instance-methods)

- toScalar() - return scalar value identifier
- equals() - returns true if the same enum value is passed
- scalarEquals() - returns true if passed scalar value is equal to current value

### Simplest enumeration

[](#simplest-enumeration)

```
/**
 * @method static DayOfWeek MONDAY()
 * @method static DayOfWeek TUESDAY()
 */
final class DayOfWeek extends \Grifart\Enum\Enum
{
    use Grifart\Enum\AutoInstances;
    private const MONDAY = 'monday';
    private const TUESDAY = 'tuesday';
}

$monday = DayOfWeek::MONDAY();
function process(DayOfWeek $day): void { /* ... */ }
```

### Values with behaviour

[](#values-with-behaviour)

This way conditions can be replaced by composition.

This example originally comes from loyalty program domain, [continue to full code sample with context](tests/Example/LoyaltyProgramExample/example.phpt).

```
/**
 * @method static ExpirationType ASSIGNMENT()
 * @method static ExpirationType FIXED()
 */
abstract class ExpirationType extends \Grifart\Enum\Enum
{
	protected const ASSIGNMENT = 'assignment';
	protected const FIXED = 'fixed';

	abstract public function computeExpiration(Offer $offer): \DateTimeImmutable;

	protected static function provideInstances() : array {
		return [
			new class(self::ASSIGNMENT) extends ExpirationType {
				public function computeExpiration(Offer $offer): \DateTimeImmutable {
					return /* behaviour A */;
				}
			},
			new class(self::FIXED) extends ExpirationType {
				public function computeExpiration(Offer $offer): \DateTimeImmutable {
					return /* behaviour B */;
				}
			},
		];
	}
}
```

### Migrating from class constants \[[source code](tests/Example/MigratingLegacyCode/readme.md)\]

[](#migrating-from-class-constants-source-code)

This guide show how to migrate from classes with constants to `\Grifart\Enum` in few simple steps. [Continue to example](tests/Example/MigratingLegacyCode/readme.md)

### Adding behaviour to values \[[source code](tests/Example/AddingBehaviourToEnum/readme.md)\]

[](#adding-behaviour-to-valuessource-code)

This guide show how to slowly add behaviour to enum values. Step by step. [Continue to example](tests/Example/AddingBehaviourToEnum/readme.md)

### Complex showcase: order lifecycle tracking \[[source code](tests/Example/OrderState/readme.md)\]

[](#complex-showcase-order-lifecycle-tracking-source-code)

This example contains 5 ways of implementing order state. [Continue to example](tests/Example/OrderState/readme.md).

Big thanks
----------

[](#big-thanks)

- [David Grudl](https://github.com/dg) for making [Nette Tester](https://github.com/nette/tester)
- [Ondřej Mirtes](https://github.com/ondrejmirtes) for making [PHP Stan](https://github.com/phpstan/phpstan).

More reading
------------

[](#more-reading)

- [consistence/consistence enum](https://github.com/consistence/consistence/blob/master/docs/Enum/enums.md)
- [myclabs/php-enum](https://github.com/myclabs/php-enum)
- [Java enum](https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html) (see planet example)
- [great talk about "crafting wicked domain models" from Jimmy Bogard](https://vimeo.com/43598193)
- [more my notes on DDD topic](https://gitlab.grifart.cz/jkuchar1/eventsourcing-cqrs-simple-app/blob/master/README.md)

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance17

Infrequent updates — may be unmaintained

Popularity44

Moderate usage in the ecosystem

Community13

Small or concentrated contributor base

Maturity53

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~128 days

Recently: every ~84 days

Total

7

Last Release

2351d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/939d12e9a77e30f843e33a785f81d8ee45b71bf2db88c0d32c0d36571c71a58d?d=identicon)[jkuchar](/maintainers/jkuchar)

---

Top Contributors

[![jkuchar](https://avatars.githubusercontent.com/u/133822?v=4)](https://github.com/jkuchar "jkuchar (101 commits)")

---

Tags

compositiondddddd-styleenumenumerationlibraryphp

###  Code Quality

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

![Health badge](/badges/grifart-enum/health.svg)

```
[![Health](https://phpackages.com/badges/grifart-enum/health.svg)](https://phpackages.com/packages/grifart-enum)
```

###  Alternatives

[phamda/phamda

Auto-curried function library

1922.8k](/packages/phamda-phamda)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
