In Laravel I have the following model:
class Product extends Model {}
which contains the function:
public function setThumbnailAttribute($value) {}
I have multiple models which should contain the same setThumbnailAttribute()
function. What is the correct way to do this using Laravel or basic PHP functionality?
Use polymorphism if this models have multiple realizations of this method. However, if method universal for models, choose second.
class Product extends AbstractThumbnailedModel
{
public function setThumbnailAttribute(Thumbnail $thumb)
{
// implement setter for Product
}
}
class AnotherProduct extends AbstractThumbnailedModel
{
public function setThumbnailAttribute(Thumbnail $thumb)
{
// implement setter for AnotherProduct
}
}
abstract class AbstractThumbnailModel extends Model
{
abstract public function setThumbnailAttribute(Thumbnail $thumb);
}
Use traits. Create trait Thumbnailed and use it when needed in models.
trait Thumbnailed
{
public function setThumbnailedAttribute(Thumbnail $thumb)
{
// here implementaition which will share with needed models
}
}
class Product extends Model
{
use Thumbnailed;
// Use it!
}
class AnotherProduct extends Model
{
use Thumbnailed;
// same method implementation. Just use it!
}
P.S. Sorry for Google translate
Create a base model that extends Model, and add the function to this.
use Illuminate\Database\Eloquent\Model;
class BaseModel extends Model
{
public function setThumbnailAttribute($value)
{
// code here
}
}
You can then extend any of your models using the new base models to have access to this function.
class Product extends BaseModel
{
}
This same logic can be applied to controllers as well, on the basis of accessing a global function.