A parameter of constructor is "constants", is there a design-pattern / elegant solution?

49 views Asked by At

This is mostly an imaginary problem, no real life situation, but it's simply do depict with. In this example we cache a point to a directory. I used to have

common.php

define('PATH_TO_CACHE', '/var/www/cache');

pixel.php

class Pixel
{
    private int $x, $y;

    public function __construct(int $x, int $y)
    {
        $this->x = $x;
        $this->y = $y;
    }

    public function draw()
    {
        // drawing...
        file_put_contents(PATH_TO_CACHE.'/test.php', var_export([$this->x, $this->y], true));
    }
}

$a = new Pixel(1,4);
$b = new Pixel(4,1);
$c = new Pixel(1,1);

this is so far very simple, but that way it's not so flexible, our code is tight to PATH_TO_CACHE. After refactoring:

class Pixel
{
    private readonly int $x, $y;
    private readonly string $pathToCache;

    public function __construct(int $x, int $y, string $pathToCache)
    {
        $this->x = $x;
        $this->y = $y;
        $this->pathToCache = $pathToCache;
    }

    public function draw()
    {
        // drawing...
        file_put_contents($this->pathToCache.'/test.php', var_export([$this->x, $this->y], true));
    }
}

this is then fully independent now, but how do we instantiate Pixel?

$a = new Pixel(1,4, '/var/www/cache');
$b = new Pixel(4,1, '/var/www/cache');
$c = new Pixel(1,1, '/var/www/cache');

now let me not summarize why it is bad, starting out from redundancy nightmare. But I cant figure a real solution. How to do it? And let's try keep this object immutable. And Pixel itself cant have that constants, since what if this Pixel can be reused among totally different projects?

0

There are 0 answers