我有一个名为“ DeltaBody”的特征。该特征在某些模型中使用,并且在逻辑上起作用。但是在特征部分,代码看起来像这样:
<?php
namespace App\Traits;
trait DeltaBody{
public function getSafeCaption(){
if($this->richCheck()){
return $this->deltaToText();
}else{
return $this->body;
}
}
现在注意:
$this->body
现在可以了,因为此特征在我的Post and Comments模型中。偶然地,他们两个都有一个数据库列“ body”。假设我将来会介绍另一个模型,而我会拥有“满足感”而不是“身体”。现在,我无法使用我的特征,因为它引用了:
$this->body
所以我想将其更改为可以覆盖的内容。
有没有办法让我说出我的特质声明:
var bodyName = 'body';
然后在我使用DeltaBody后以某种方式将特质中的bodyName覆盖或设置为模型中的“内容”;
这样特征中的代码将是
$this->bodyName //calls $this->content since bodyName is set to 'content'?
谢谢!
答案 0 :(得分:1)
要使您的特征在潜在的不相关对象之间更加可重用,在您的案例模型中,您需要确保在该特征内定义了这些方法:
newQuery()
编辑:我假设$products = OtherProduct::newQuery();
// Search for a product based on col3
if ($request->has('col1')) {
$products->where('col1', $request->input('col1'));
}
// Search for a product based on col2
if ($request->has('col2')) {
$products->where('col2', $request->input('col2'));
}
// Search for a product based on col3
if ($request->has('col3')) {
$products->where('col3', $request->input('col3'));
}
// Continue for all of the filters.
// Get the results and return them.
return $products->orderBy('id', 'DESC');->get();
和<?php
namespace App\Traits;
trait DeltaBody
{
public function getSafeCaption()
{
if ($this->richCheck()) {
return $this->deltaToText();
} else {
return $this->getContent();
}
}
/**
* Make sure your model defines this method
*/
abstract protected function deltaToText();
/**
* Make sure your model defines this method
*/
abstract protected function richCheck();
/**
* Let the model decide which property to use(body, content)
*/
abstract protected function getContent();
}
在特征中不存在不,如果确实存在,则将其忽略。
如果您不想在每个模型中定义richCheck
,则可以使用另一种方法,即假设PHP 7,则在每个模型中定义一个属性:
deltaToText
然后选择您的模型:
getContent