Laravel: create a dynamic property

喜欢而已 提交于 2019-12-22 06:49:10

问题


I have a decent-size codebase built at this point. I have a couple of tables with matching Eloquent models that are storing addresses in the form ### Street, City, ST, xzipx. These are represented in the database by a single varchar field called address.

Now here's my issue. I want to add a new feature that allows items to be compared by whether they are in the same city, state, etc. The way to do this as my database is currently configured is to tokenize the address string. This is fine, but a little annoying to have to do it every time.

The ideal solution would be to restructure the database, and associated models, to split the address field into street, city, state, and zip. The only problem there, would be that everywhere else, where I'm currently accessing the address using $model->address, I would have to construct it from the pieces. This happens a lot throughout the code, so even creating a helper function as below:

public function address(){
  return $this->street.", ".$this->city.", ".$this->state." ".$this->zip;
}

would mandate replacing all instances of $model->address with $model->address(), which would still be cumbersome. The ideal solution would be to create a dynamic property, like how Laravel creates them using for relationships. Is this possible?

Or is there a better solution?


回答1:


You could define an accessor for the address property:

class YourClass {
    public function getAddressAttribute()
    {
        return $this->street.", ".$this->city.", ".$this->state." ".$this->zip;
    }
}

Then, $object->address should return what you need. If you want it to be included on the model's array and JSON forms, you'll need to add it to the $appends property of the model.

class YourClass {
    protected $appends = array('address');
    public function getAddressAttribute()
    {
        return $this->street.', '.$this->city.', '.$this->state.' '.$this->zip;
    }
}

EDIT: for setting, you would have to set up a mutator, like so:

public function setAddressAttribute($value)
{
    // assume $this->handlesParsingAddress parses and returns an assoc array
    $parsed = $this->handlesParsingAddress($value);
    $this->street = $parsed['street'];
    $this->city = $parsed['city'];
    $this->state = $parsed['state'];
    $this->zip = $parsed['zip'];        
}


来源:https://stackoverflow.com/questions/25125724/laravel-create-a-dynamic-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!