What you need to do is create a class that will manage your groups.
Register your mylib
with the class ClassGroup
, so when you call $this->mylib
, it will return instance of ClassGroup
.
With the magic method and singleton
method, you can now call based on group and even with shared singleton instance
Class Example:
class ClassGroup
{
private static array $instance = [];
private bool $shared = false;
public function __construct(bool $shared = false)
{
$this->shared = $shared;
}
public function __get(string $group): ?object
{
return $this->shared
? self::getInstance($group)
: self::groups($group);
}
public function __call(string $method, array $arguments): ?object
{
return $this->shared
? self::getInstance($method, $arguments)
: self::groups($method, $arguments);
}
public function singleton(): self
{
$this->shared = true;
return $this;
}
private static function getInstance(string $method, array $arguments): ?object
{
if(!isset(self::$instance[$method])){
self::$instance[$method] = self::groups($method, $arguments);
}
return self::$instance[$method];
}
private static function groups(string $group, array $arguments): ?object
{
return match($group)
{
'testA' => new TextClassA(...$arguments),
'testB' => new TextClassB(...$arguments),
default => null
};
}
}
Usages examples:
$this->mylib->testA->fooMethod();
$this->mylib->testA('foo', 'bar')->fooMethod();
// For shared instance
$this->mylib->singleton()->testA->fooMethod();
$this->mylib->singleton()->testA('foo', 'bar')->fooMethod();