What is more correct to use for multiple inheritance in the below case? Is the second method follows the SOLID principle correctly? Or any common design pattern can be used instead?
This is a simplified concept code. Many class needs to extend the Image class like BicycleImage, BusImage. Some of them needs to addNoise() but not every one. Also more "state changing" classes are needed like sharpenEdges, increaseIntesity, etc. Which not every child class use.
Base class:
<?php
abstract class Image
{
private $pixels;
public function setPixel(int $x, int $y, int $intensity): void
{
$this->pixels[$x][$y] = $intensity;
}
public function saveImage(): void {}
}
Trait method:
trait RandomNoiseTrait
{
public function addNoise(): void
{
$this->setPixel(mt_rand(1, 100), mt_rand(1, 100), mt_rand(1, 100));
}
}
class CarImage extends Image
{
use RandomNoiseTrait;
public function drawCar(): void {}
}
$carImage = new CarImage();
$carImage->drawCar();
$carImage->addNoise();
$carImage->saveImage();
Object injected to separate object which alters the injected objects state:
class CarImage extends Image
{
public function drawCar(): void {}
}
class RandomNoise
{
private $image;
public function __construct(Image $image)
{
$this->image = $image;
}
public function addNoise(): void
{
$this->image->setPixel(mt_rand(1, 100), mt_rand(1, 100), mt_rand(1, 100));
}
}
$carImage = new CarImage();
$carImage->drawCar();
$noise = new RandomNoise($carImage);
$noise->addNoise();
$carImage->saveImage();