0

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?

John Smith
  • 6,129
  • 12
  • 68
  • 123
  • 1
    I would implement it as a simple base `Pixel` class, and then extend that with `CachedPixel` that also accepts a [PSR-6](https://www.php-fig.org/psr/psr-6/) compatible caching object as part of the constructor. The cache object itself then contains any necessary configuration. Also I would _strongly_ suggest not using the `final` keyword unless you have exceedingly good reasons to not allow a class to be extended. The same, but to a lesser extent, for the `private` keyword. – Sammitch Jun 07 '22 at 20:43
  • I misused the "final", I meant "readonly" – John Smith Jun 07 '22 at 20:50

0 Answers0