PHP objects are in one hell of a state too

In my previous article, I presented the design pattern “State”. It’s time to introduce a method to implement it in your PHP projects.

I wrote the library “States” which allows to easily implement this behavior to your objects, without having to use a third-party PHP extension.

We can install it easily with the following command:

composer require teknoo/states


In the States library, “” classes are called “” and require the implementation of the interface “”. A trait is provided to avoid writing it yourself.

The states are represented by classes implementing the interface “”. A trait is also available. States classes must be listed in the class, in the static method “statesListDeclaration”.

Methods of these states will be methods called by our object “”. The keywords “”, “” and “” will represent the object (or instance) or class and not the class / object.

The visibility of ’s attributes, of ’s methods and all methods in states are preserved. A element will be accessible only to the methods of the class and to its children, elements only to the methods of the class.

Children classes of the class inherit of states from their parents classes. It is possible to extend or redefine them.


By following our pseudo code of the previous article, we can write this implementation:


This library provides also a mechanism to select “automatically” the appropriate state(s) according to the attributes of the object. The selection is made using a list of assertions to be defined via the static method .

The selection is not executed automatically, however, only when calling the method . It can be called at any time, in the constructor, before or after each call, in a method of the class or its states, or from an external method or function.

We can adapt our class to speak the language of the native country when its interlocutor does not specify the required language.

With this last evolution, our object will automatically speak the language of user’s country. It is possible to go further, the library implement other assertions, based on digital operations, or on .

This evolution also implements a variant. The interlocutor tells it, via the method , the required language, it is no longer passed as a parameter. The method and methods are directly implemented in states and are accessible if the state is enabled.

Written by

Engineer / Software architect freelance — https://teknoo.software — #php #web

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store