Many times I needed to cast database column value to specific data format or some object instance. Doing this by creating getFooAttribute|setFooAttribute methods can be cumbersome especially if same casting logic have to be used within few models or even more widely within application.
allow user to define as many custom castings as needed
isDirty support (add ability to check if data within custom casting has changed somehow)
allow user to use different data formats (not only json)
allow user to create target class instance in other way than calling new SomeClass($rawinput) (target class may does not support creating its instance with raw input passed directly to the constructor)
To achieve possibility to create custom casts in totally user-defined way some proxy class is needed (idea of "Casts"). This proxy class should define logic behind getting and storing data (reading from database, then storing to the database). Cause this data mostly is stored as json, the default set method just json_serialize given data.
Summary
I think this functionality may be written easily (maybe not this way, but that's some idea, dont you think?).
No problem to create a fork and pull request.
Long story short
Many times I needed to cast database column value to specific data format or some object instance. Doing this by creating
getFooAttribute
|setFooAttribute
methods can be cumbersome especially if same casting logic have to be used within few models or even more widely within application.To achieve that I've created really simple package that should achieve that https://github.com/johnylemon/laravel-cast
Goals:
isDirty
support (add ability to check if data within custom casting has changed somehow)SomeClass($rawinput)
(target class may does not support creating its instance with raw input passed directly to the constructor)Coding time
The Laravel/Lumen logic for
castAttribute
/setAttribute
are written nearly perfectly for this functionality (my package duplicates only one condition (https://github.com/johnylemon/laravel-cast/blob/7d2ec1cf060535451953237b45df761825649116/src/Traits/CustomCasts.php#L81 to keep compatibility)The problem is with the
getDirty
method which have to be overwritten to achieve some additional logic (https://github.com/johnylemon/laravel-cast/blob/7d2ec1cf060535451953237b45df761825649116/src/Traits/CustomCasts.php#L136)To achieve possibility to create custom casts in totally user-defined way some proxy class is needed (idea of "Casts"). This proxy class should define logic behind getting and storing data (reading from database, then storing to the database). Cause this data mostly is stored as json, the default
set
method justjson_serialize
given data.Summary
I think this functionality may be written easily (maybe not this way, but that's some idea, dont you think?). No problem to create a fork and pull request.