<?php

interface Text
{
    public function render(string $extrinsicState);
}

class Word implements Text
{
    private $name;

    public function __construct(string $name)
    {
        $this->name = $name;
    }

    public function render(string $font)
    {
        return sprintf('Word %s with font %s', $this->name, $font);
    }
}

class Character implements Text
{
    /**
     * Any state stored by the concrete flyweight must be independent of its context.
     * For flyweights representing characters, this is usually the corresponding character code.
     */
    private $name;

    public function __construct(string $name)
    {
        $this->name = $name;
    }

    public function render(string $font)
    {
         // Clients supply the context-dependent information that the flyweight needs to draw itself
         // For flyweights representing characters, extrinsic state usually contains e.g. the font.

        return sprintf('Character %s with font %s', $this->name, $font);
    }
}


/**
 * A factory manages shared flyweights. Clients should not instantiate them directly,
 * but let the factory take care of returning existing objects or creating new ones.
 */
class TextFactory implements Countable
{
    /**
     * @var Text[]
     */
    private $charPool = [];

    public function get(string $name)
    {
        if (!isset($this->charPool[$name])) {
            $this->charPool[$name] = $this->create($name);
        }

        return $this->charPool[$name];
    }

    private function create(string $name)
    {
        if (strlen($name) == 1) {
            return new Character($name);
        } else {
            return new Word($name);
        }
    }

    public function count()
    {
        return count($this->charPool);
    }
}


// USAGE
$characters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'];

$fonts = ['Arial', 'Times New Roman', 'Verdana', 'Helvetica'];

$factory = new TextFactory();

for ($i = 0; $i <= 10; $i++) 
{
    foreach ($characters as $char) 
    {
        foreach ($fonts as $font) 
        {
            $flyweight = $factory->get($char);
            $rendered = $flyweight->render($font);
        }
    }
}

foreach ($fonts as $word) 
{
    $flyweight = $factory->get($word);
    $rendered = $flyweight->render('foobar');
}