archetype icon indicating copy to clipboard operation
archetype copied to clipboard

How to add methods?

Open ekosynth opened this issue 2 years ago • 1 comments

Hi, when using PHPFile, is there a way to add methods to a class?

ekosynth avatar Sep 13 '22 15:09 ekosynth

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

ajthinking avatar Sep 14 '22 06:09 ajthinking