PhpGenerator 3.4: body and soul
PhpGenerator can create a model of a class or function based on existing one. This makes it easy to create, for example, proxy classes. However, the latest version 3.4 goes even further.
It can also copy the bodies of methods and functions, i.e. their code.
Let's remember a way to create a class model from an existing class:
use Nette\PhpGenerator\ClassType; $class = ClassType::from(Nette\Application\UI\Control::class); echo $class;
The rendered class is fairly accurate copy of the original class, including phpDoc comments, etc. It differs from the original in only two ways:
- it omits traits
- method's body is missing
The omission of traits is due to insufficient abilities of PHP class reflection, for which reason it is very complicated to find out to which traits the properties and methods belong to. However, support may be added in a future release.
However, what version 3.4 brought is the ability to load classes and functions including code in their bodies. This is done as follows:
$class = ClassType::withBodiesFrom(Nette\Application\UI\Control::class); $function = Nette\PhpGenerator\GlobalFunction::withBodyFrom('dump');
This functionality uses the library
needs to be installed:
composer require nikic/php-parser