Laravel:创建动态属性 [英] Laravel: create a dynamic property
问题描述
我现在已经构建了一个体面的代码库.我有几个带有匹配的Eloquent模型的表,这些表以### Street, City, ST, xzipx
的形式存储地址.这些在数据库中由单个
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.
理想的解决方案是重组数据库和相关模型,将address
字段拆分为street
,city
,state
和zip
.唯一的问题是,在其他任何地方(我当前正在使用$model->address
访问该地址),我将不得不从头开始构造它.在整个代码中,这种情况经常发生,因此即使创建如下的帮助器函数,也是如此:
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;
}
将强制使用$model->address()
替换$model->address
的所有实例,这仍然很麻烦.理想的解决方案是创建一个动态属性,例如Laravel如何使用它们创建关系.这可能吗?
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?
推荐答案
您可以为address
属性定义访问器:
You could define an accessor for the address
property:
class YourClass {
public function getAddressAttribute()
{
return $this->street.", ".$this->city.", ".$this->state." ".$this->zip;
}
}
然后,$object->address
应该返回您需要的内容.如果希望将其包含在模型的数组和JSON表单中,则需要将其添加到模型的$appends
属性中.
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;
}
}
要进行设置,您将必须设置一个变幅器,像这样:
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'];
}
这篇关于Laravel:创建动态属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!