Download the PHP package nette/php-generator without Composer
On this page you can find all versions of the php package nette/php-generator. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package php-generator
<!---->
Are you looking for a tool to generate PHP code for PHP files?
✅ Supports all the latest PHP features like [property hooks](#property-hooks), [enums](#enums), [attributes](#attributes), etc.
✅ Allows you to easily modify [existing classes](#generating-from-existing-ones)
✅ Output compliant with [PSR-12 / PER coding style](#printer-and-psr-compliance)
✅ Highly mature, stable, and widely used library
<!---->
Installation
Download and install the library using the Composer tool:
PhpGenerator 4.1 is compatible with PHP 8.0 to 8.4. Documentation can be found on the library's website.
<!---->
Support Me
Do you like PHP Generator? Are you looking forward to the new features?
Thank you!
<!---->
Classes
Let's start with an example of creating a class using ClassType:
This will return:
To generate the code, you can also use a so-called printer, which, unlike echo $class
, can be further configured:
You can add constants (class Constant) and properties (class Property):
This will generate:
And you can add methods:
The result is:
Promoted parameters introduced in PHP 8.0 can be passed to the constructor:
The result is:
Readonly properties and classes be marked using the setReadOnly()
function.
If an added property, constant, method, or parameter already exists, an exception is thrown.
Class members can be removed using removeProperty()
, removeConstant()
, removeMethod()
, or removeParameter()
.
You can also add existing Method
, Property
, or Constant
objects to the class:
You can also clone existing methods, properties, and constants under a different name using cloneWithName()
:
<!---->
Interfaces or Traits
You can create interfaces and traits (classes InterfaceType and TraitType):
Using a trait:
The result is:
<!---->
Enums
You can easily create enums introduced in PHP 8.1 like this (class EnumType):
The result is:
You can also define scalar equivalents and create a "backed" enum:
For each case, you can add a comment or attributes using addComment()
or addAttribute()
.
<!---->
Anonymous Classes
Pass null
as the name, and you have an anonymous class:
The result is:
<!---->
Global Functions
The code for functions is generated by the class GlobalFunction:
The result is:
<!---->
Anonymous Functions
The code for anonymous functions is generated by the class Closure:
The result is:
<!---->
Short Arrow Functions
You can also output a short anonymous function using the printer:
The result is:
<!---->
Method and Function Signatures
Methods are represented by the class Method. You can set visibility, return value, add comments, attributes, etc.:
Individual parameters are represented by the class Parameter. Again, you can set all conceivable properties:
To define the so-called variadics parameters (or also the splat, spread, ellipsis, unpacking or three dots operator), use setVariadic()
:
This generates:
<!---->
Method and Function Bodies
The body can be passed all at once to the setBody()
method or gradually (line by line) by repeatedly calling addBody()
:
The result is:
You can use special placeholders for easy variable insertion.
Simple placeholders ?
The result is:
Placeholder for variadic ...?
The result is:
You can also use named parameters for PHP 8 with ...?:
The placeholder is escaped with a backslash \?
The result is:
<!---->
Printer and PSR Compliance
The Printer class is used for generating PHP code:
It can generate code for all other elements, offering methods like printFunction()
, printNamespace()
, etc.
There's also the PsrPrinter
class, which outputs in accordance with PSR-2 / PSR-12 / PER coding style:
Need custom behavior? Create your own version by inheriting the Printer
class. You can reconfigure these variables:
How and why does the standard Printer
differ from PsrPrinter
? Why isn't there just one printer, the PsrPrinter
, in the package?
The standard Printer
formats the code as we do throughout Nette. Since Nette was established much earlier than PSR, and also because PSR took years to deliver standards on time, sometimes even several years after introducing a new feature in PHP, it resulted in a coding standard that differs in a few minor aspects.
The major difference is the use of tabs instead of spaces. We know that by using tabs in our projects, we allow for width customization, which is essential for people with visual impairments.
An example of a minor difference is placing the curly brace on a separate line for functions and methods, always. The PSR recommendation seems illogical to us and leads to reduced code clarity.
<!---->
Types
Every type or union/intersection type can be passed as a string; you can also use predefined constants for native types:
The same applies to the setReturnType()
method.
<!---->
Literals
Using Literal
, you can pass any PHP code, for example, for default property values or parameters, etc:
Result:
You can also pass parameters to Literal
and have them formatted into valid PHP code using placeholders:
A literal representing the creation of a new object can easily be generated using the new
method:
<!---->
Attributes
With PHP 8, you can add attributes to all classes, methods, properties, constants, enum cases, functions, closures, and parameters. You can also use literals as parameter values.
Result:
<!---->
Property Hooks
You can also define property hooks (represented by the class PropertyHook) for get and set operations, a feature introduced in PHP 8.4:
This generates:
Properties and property hooks can be abstract or final:
<!---->
Asymmetric Visibility
PHP 8.4 introduces asymmetric visibility for properties. You can set different access levels for reading and writing.
The visibility can be set using either the setVisibility()
method with two parameters, or by using setPublic()
, setProtected()
, or setPrivate()
with the mode
parameter that specifies whether the visibility applies to getting or setting the property. The default mode is 'get'.
This generates:
<!---->
Namespace
Classes, traits, interfaces, and enums (hereafter referred to as classes) can be grouped into namespaces represented by the PhpNamespace class:
If the class already exists, an exception is thrown.
You can define use clauses:
To simplify a fully qualified class, function, or constant name based on defined aliases, use the simplifyName
method:
Conversely, you can convert a simplified class, function, or constant name back to a fully qualified name using the resolveName
method:
<!---->
Class Names Resolving
When a class is part of a namespace, it's rendered slightly differently: all types (e.g., type hints, return types, parent class name, implemented interfaces, used traits, and attributes) are automatically resolved (unless you turn it off, see below). This means you must use fully qualified class names in definitions, and they will be replaced with aliases (based on use clauses) or fully qualified names in the resulting code:
Result:
Auto-resolving can be turned off this way:
<!---->
PHP Files
Classes, functions, and namespaces can be grouped into PHP files represented by the PhpFile class:
Result:
Please note: No additional code can be added to the files outside of functions and classes.
<!---->
Generating from Existing Ones
In addition to being able to model classes and functions using the API described above, you can also have them automatically generated using existing ones:
By default, function and method bodies are empty. If you also want to load them, use this method
(requires the nikic/php-parser
package to be installed):
<!---->
Loading from PHP Files
You can also load functions, classes, interfaces, and enums directly from a string containing PHP code. For example, to create a ClassType
object:
When loading classes from PHP code, single-line comments outside method bodies are ignored (e.g., for properties, etc.), as this library doesn't have an API to work with them.
You can also directly load an entire PHP file, which can contain any number of classes, functions, or even namespaces:
The file's initial comment and strict_types
declaration are also loaded. However, all other global code is ignored.
It requires nikic/php-parser
to be installed.
(If you need to manipulate global code in files or individual statements in method bodies, it's better to use the nikic/php-parser
library directly.)
<!---->
Class Manipulator
The ClassManipulator class provides tools for manipulating classes.
The inheritMethod()
method copies a method from a parent class or implemented interface into your class. This allows you to override the method or extend its signature:
The inheritProperty()
method copies a property from a parent class into your class. This is useful when you want to have the same property in your class, but possibly with a different default value:
The implement()
method automatically implements all methods and properties from the given interface or abstract class:
<!---->
Variable Dumping
The Dumper
class converts a variable into parseable PHP code. It provides a better and clearer output than the standard var_export()
function.