xp-framework/reflection

Typesafe implementations

Opened this issue · 0 comments

A typical usecase is to load classes from a given package by a given name:

use lang\reflection\Package;

$type= (new Package('xp.xar.instruction'))->type(ucfirst($name).'Instruction');

This loads e.g. the class ExtractInstruction, which extends an abstract base class called Instruction (or implements an interface of that name). However, the above does not guarantee this from a type perspective, a class NotInstruction may exist that does not fulfill this contract.

Instead of having to add a check (using isSubclassOf(), e.g.), a new API should encapsulate this:

use lang\reflection\Implementations;
use xp\xar\Instruction;

$type= (new Package('xp.xar.instruction'))->implementationsOf(Instruction::class)->type(ucfirst($name).'Instruction');
$type= Implementations::of(Instruction::class)->type('xp.xar.instruction.'.ucfirst($name).'Instruction');
$type= Implementations::of(Instruction::class)->in('xp.xar.instruction')->type(ucfirst($name).'Instruction');