Enum Function in PHP
As is known, there is no built-in PHP type of transfers, and projects with a complex subject area, this fact creates a lot of problems. When in the next Symfony-project, there is a need in the transfers, it was decided to create its implementation.
From the transfers required flexibility and the possibility of using different components of the application. Tasks that should solve the enumeration, the following:
be able to get a list of enumerated values
integration with the Doctrine for the enumeration type as a field
integration with the Form for transfers as a field in the form to select the desired item
integration with Twig translation enumeration values
There are several implementations of transfers, for example, myclabs /? Php-an enum , sometimes quite bizarre , including – SplEnum . But when integrated with other parts of the application (doctrine, twig) problems, especially when using Doctrine.
Feature Doctrine type system is that all types must inherit from class Type, which has a private final Constructor. Those. we can not inherit from it and overload the constructor to take a value transfers. However, this problem has been to get around, though, and a few non-standard way.
Enum – the base class listings
Specific Enum might look like this:
class Format extends Enum
public static $WEB;
public static $GOST;
Format::$WEB = new Format(‘web’);
Format::$GOST = new Format(‘gost’);
Unfortunately, in php you can not use the expressions for the static fields, so the creation of objects have to endure beyond the class.
Thanks to a private constructor, Enum can not be inherited inherited from Type doctrine. But how were the Type-E is done to enumerate? The answer came in the process of studying how Doctrine generates proxy classes for the entities. In each entity Doctrine generates a proxy class that inherits from the entity class, which implements the lazy loading everything else. Well, we will do the same – for each class Enum will create a proxy class that derives from Type, and implements the logic necessary to determine the type. These classes can then be stored in the cache and load when necessary.
DoctrineEnumAbstractType, which implemented basic logic Type
DoctrineEnumProxyClassGenerator, which generates proxy classes for transfers.
At each transfer ProxyClassGenerator generates a proxy class that can then be used in Doctrine, to the field of entities were these listings.
The result is a Enum, which can be used with different components of the Symfony-applications – Doctrine, Form, Twig. I hope that this implementation can somebody or be inspired to search for new solutions.