PHPackages                             phpgears/immutability - 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. phpgears/immutability

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

phpgears/immutability
=====================

Object immutability guard for PHP

0.2.6(5y ago)27.2k4MITPHPPHP ^7.1CI failing

Since Sep 15Pushed 5y ago1 watchersCompare

[ Source](https://github.com/phpgears/immutability)[ Packagist](https://packagist.org/packages/phpgears/immutability)[ Docs](https://github.com/phpgears/immutability)[ RSS](/packages/phpgears-immutability/feed)WikiDiscussions master Synced 4d ago

READMEChangelogDependencies (16)Versions (14)Used By (4)

[![PHP version](https://camo.githubusercontent.com/d0b5687c6812c5d52d86a548e09db527eeb7860f82adbb677de00a36ddbed1b4/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f5048502d253345253344372e312d3838393242462e7376673f7374796c653d666c61742d737175617265)](http://php.net)[![Latest Version](https://camo.githubusercontent.com/90b4cbb36bf914d4ac8d9e86f7c37fd933d5fec606285c0babce6ec9c5c1701b/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f767072652f70687067656172732f696d6d75746162696c6974792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/phpgears/immutability)[![License](https://camo.githubusercontent.com/75454f6c48741d7d255c051821e56be94103d8ab8cc2713bdf6821170dc8c35d/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f70687067656172732f696d6d75746162696c6974792e7376673f7374796c653d666c61742d737175617265)](https://github.com/phpgears/immutability/blob/master/LICENSE)

[![Build Status](https://camo.githubusercontent.com/77baf0db0043681983cea24a41fb7116f3b1c55d09c169f0663e7d59c39e0c59/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f636f6d2f70687067656172732f696d6d75746162696c6974792e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.com/github/phpgears/immutability)[![Style Check](https://camo.githubusercontent.com/c5242014111c3a841f831897401af37674c7424e654c3d6efef9ff1408341f5b/68747470733a2f2f7374796c6563692e696f2f7265706f732f3134383834303932372f736869656c64)](https://styleci.io/repos/148840927)[![Code Quality](https://camo.githubusercontent.com/d5194f43a5fc0ff11a7368bed937b190722f007cf99cfacffa57eba934f30f6d/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f70687067656172732f696d6d75746162696c6974792e7376673f7374796c653d666c61742d737175617265)](https://scrutinizer-ci.com/g/phpgears/immutability)[![Code Coverage](https://camo.githubusercontent.com/6337106ad1e274c96cb7a5ef613a761b241be92d534632c42920385daf26ad10/68747470733a2f2f696d672e736869656c64732e696f2f636f766572616c6c732f70687067656172732f696d6d75746162696c6974792e7376673f7374796c653d666c61742d737175617265)](https://coveralls.io/github/phpgears/immutability)

[![Total Downloads](https://camo.githubusercontent.com/5f7e7a86e178600cd45944c6bca607ee5100598ba91a60f3a45e9ffa52fc38e8/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f70687067656172732f696d6d75746162696c6974792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/phpgears/immutability/stats)[![Monthly Downloads](https://camo.githubusercontent.com/aa96b94c07ed014a4a5eb458522f69a7d6bc8d3e42f113bd197326a7739ef60c/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f646d2f70687067656172732f696d6d75746162696c6974792e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/phpgears/immutability/stats)

Object immutability guard for PHP
=================================

[](#object-immutability-guard-for-php)

Truly object immutability in PHP is an impossible task by the nature of the language itself, carefully checking and protecting properties and methods visibility is the closest we can get at this moment in time

Crafting an object to make it as immutable as can be requires expertise, dedication and focus so no mutating mechanism slips through developer's hands into the object, that is the reason behind this library, provide a way to help with the tedious task of ensuring object immutability

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

[](#installation)

### Composer

[](#composer)

```
composer require phpgears/immutability

```

Usage
-----

[](#usage)

Require composer autoload file

```
require './vendor/autoload.php';
```

`Gears\Immutability\ImmutabilityBehaviour` trait enforces you to avoid public properties and mutable methods in your class by calling `assertImmutable` method on object construction, `__wakeup` method and `unserialize` methods if Serializable interface is implemented

This mentioned behaviour let alone would run your objects completely useless, you must provide an implementation of the abstract method `getAllowedInterfaces`, returning a list of interfaces whose public methods will be allowed in your class. Although you can also provide class names, as it can prove useful in some special cases, it is *highly discouraged* and should be used sparsely

Few PHP magic methods are allowed to be defined as public, namely `__construct`, `__destruct`, `__get`, `__isset`, `__sleep`, `__wakeup`, `__serialize`, `__unserialize`, `__toString`, `__set_state`, `__clone`, `__debugInfo`

```
use Gears\Immutability\ImmutabilityBehaviour;

interface MyInterface extends \Serializable
{
    /**
     * @return string
     */
    public function getParameter(): string;
}

final class MyClass implements MyInterface
{
    use ImmutabilityBehaviour;

    protected function __construct()
    {
        $this->assertImmutable();
    }

    /**
     * Static methods are allowed.
     */
    public static function instance(): self
    {
        return new self();
    }

    /**
     * Method allowed because it's defined in the interface.
     */
    public function getParameter(): string
    {
        return '';
    }

    /**
     * Method allowed because it's defined in the \Serializable.
     */
    public function serialize(): string
    {
        return '';
    }

    /**
     * Method allowed because it's defined in the \Serializable.
     */
    public function unserialize($serialized): void
    {
        $this->assertImmutable();

        // unserialize
    }

    /**
     * {@inheritdoc}
     */
    protected function getAllowedInterfaces(): array
    {
        return [MyInterface::class];
    }
}
```

As a general rule, your immutable classes should be declared final. In case you really need inheritance, at least your implementation of `getAllowedInterfaces` method has to be declared final for every instantiable class

Although not mandatory it is advised to make your constructors *protected* and force developers to create static named constructors

From now on you can focus on those methods defined in your interfaces and make sure they do not mutate your object, with the confidence no other developer would mutate your object by accident or intentionally

### Example

[](#example)

If you want to have a look at a working example implementations of immutable objects have a look at [phpgears/identity](https://github.com/phpgears/identity), [phpgears/dto](https://github.com/phpgears/dto) or [phpgears/cqrs](https://github.com/phpgears/cqrs)

Contributing
------------

[](#contributing)

Found a bug or have a feature request? [Please open a new issue](https://github.com/phpgears/immutability/issues). Have a look at existing issues before.

See file [CONTRIBUTING.md](https://github.com/phpgears/immutability/blob/master/CONTRIBUTING.md)

License
-------

[](#license)

See file [LICENSE](https://github.com/phpgears/immutability/blob/master/LICENSE) included with the source code for a copy of the license terms.

###  Health Score

29

—

LowBetter than 59% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity21

Limited adoption so far

Community13

Small or concentrated contributor base

Maturity54

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 ~66 days

Total

13

Last Release

2002d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/4c50421f1ab4148354dc2dd5dcaba168656b17ea913b310d112deb39a6f73ca1?d=identicon)[juliangut](/maintainers/juliangut)

---

Top Contributors

[![juliangut](https://avatars.githubusercontent.com/u/1104131?v=4)](https://github.com/juliangut "juliangut (41 commits)")

---

Tags

objectimmutability

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/phpgears-immutability/health.svg)

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

###  Alternatives

[myclabs/deep-copy

Create deep copies (clones) of your objects

8.9k849.8M169](/packages/myclabs-deep-copy)[symfony/property-access

Provides functions to read and write from/to an object or array using a simple string notation

2.8k295.3M2.5k](/packages/symfony-property-access)[cuyz/valinor

Dependency free PHP library that helps to map any input into a strongly-typed structure.

1.5k9.2M108](/packages/cuyz-valinor)[yzen.dev/plain-to-class

Class-transformer to transform your dataset into a structured object

16293.9k6](/packages/yzendev-plain-to-class)[jasny/dotkey

Dot notation access for objects and arrays

14219.5k6](/packages/jasny-dotkey)[peridot-php/object-path

A string syntax to fetch values from array and object hierarchies

1053.6k1](/packages/peridot-php-object-path)

PHPackages © 2026

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