Download the PHP package apie/type-converter without Composer
On this page you can find all versions of the php package apie/type-converter. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Download apie/type-converter
More information about apie/type-converter
Files in apie/type-converter
Package type-converter
Short Description Converts objects from specific type to an other type.
License MIT
Informations about the package type-converter
Apie type converter
Apie is a suite of composer packages to work with domain objects. It tries to aim to follow a Domain-objects-first approach and not a database first approach that you find in many PHP frameworks nowadays.
This type converter package is written outside the monorepo and provides a simple tooling to convert objects into other objects.
Usage
Easiest usage:
This is not a very useful example. Normally you try to convert a DTO to a domain object or the other way around.
More serious example:
Creating your own converters
It's very easy to create your own converters. All you need to do is make a class that implements ConverterInterface. In case you use phpstan for static code analysis a small phpdoc can be added to make phpstan understand the type conversion.
Customizing the TypeConverter
DefaultConvertsFactory creates an instance of TypeConverter with sensible defaults. You can configure everything by just calling the constructor. Remember that all default converters require to be added manually too.
Complex converters
In the example above we can convert a string value object to string, but how do we make it the other way around?
We could make a converter for every value object, but that would mean many similar classes.
Luckily we have a better solution by providing the wanted type as second argument.
It is also possible to get the TypeConverter instance to make recursive conversions.
Converter preference
If multiple converters could perform the conversion, then the most accurate one is the one that gets the priority.
If I would try to convert '1' IntToStringConverter and FloatToStringConverter would apply, but since int is more accurate it uses IntToStringConverter.