Open axyr opened 6 years ago
Have the same issue. I created a Pseudomodel class which uses HasAttributes and HasTimestamps traits and all the methods needed to make it work. The goal for me is to have accesors, mutators and type casting (relations are more complex here).
Making this traits standalone must allow us to use it without define anything else. Anyway, I think get/set/__unset methods must not be included in any trait.
+1 "Models" don't always need to be backed by a database. Sometimes a standalone class can be useful to model something. HasAttributes could make such models more eloquent.
After working with Yii2 for quite a while (where we have Model
class for the same purpose), it seems to me quite annoying that Laravel is missing such a simple and needed feature. AFAIU, Taylor has his own opinion on that - but it definitely doesn't 'make developers happy' :(
Maybe, we should think about making it as a separate package - since a similar PR was rejected by Taylor...https://github.com/laravel/framework/pull/22946
I know it's not quite the same but maybe https://github.com/calebporzio/sushi might work for these use-cases?
I know it's not quite the same but maybe https://github.com/calebporzio/sushi might work for these use-cases?
Looks like this guy was thinking about something in a similar direction, but I don't think his package covers my (and most common) scenarios. There is still need of a different solution, as to me.
FWIW, we maintain an Elasticsearch integration for Laravel which provides Models with (near) feature parity to Eloquent. I used most of the Eloquent traits, which is working, but I'll admit there were some annoyances with the default assumption of Eloquent everywhere.
If you're interested in how this works, check out the Elasticsearch Model source - maybe it helps in implementation. I wouldn't hang my hopes too high this will ever be resolved, though -- Laravel is pretty settled on the topic.
Related to https://github.com/laravel/ideas/issues/965
I regularly have models that do not come from a database, but i want to behave like an Eloquent model, by having accessors to format attributes or add calculations to them.
Some use cases are:
Using the HasAttributes trait on a POPO is also very convenient to access arrays with
$model->attribute
instead of$array['key']
, which involves a lot ofisset()
orarray_get()
calls.Unfortunately pulling in HasAttributes alone is not enough.
I had to make a seperate trait like this, to pull in HasAttributes behaviour on a plain object:
Which is - among others - used in a model to display json stored data like this:
Example use:
The problem I have is that to use HasAttributes, I need to pull in other traits as well and adding the methods
getDates
,getIncrementing
,__get
and__set
.How would you think of refactoring
HasAttributes
, so it can used standalone to add 'attributes' behaviour to arbitrary models?