archetype
archetype copied to clipboard
How to add methods?
Hi, when using PHPFile, is there a way to add methods to a class?
Hi, you could do it like this:
use PhpParser\BuilderFactory;
PHPFile::load(App\Dummy::class)
->astQuery()
->class()
->insertStmt(
(new BuilderFactory)->method('myMethod')->getNode()
)
->commit()
->end()
See details on how to use BuilderFactory here.
As an alternative, it is also possible to provide a snippets file, and extract the method body from that. This can be useful if the method is long since constructing the AST with the BuilderFactory can get quite cumbersome. This technique is used internally when adding relationship methods to LaravelFiles