{"id":13594119,"url":"https://github.com/nette/php-generator","last_synced_at":"2025-05-15T00:00:27.844Z","repository":{"id":14969350,"uuid":"17694277","full_name":"nette/php-generator","owner":"nette","description":"🐘 Generates neat PHP code for you. Supports new PHP 8.4 features.","archived":false,"fork":false,"pushed_at":"2025-03-31T00:33:54.000Z","size":917,"stargazers_count":2187,"open_issues_count":6,"forks_count":146,"subscribers_count":62,"default_branch":"master","last_synced_at":"2025-05-07T23:30:21.516Z","etag":null,"topics":["code-generator","nette","nette-framework","php","php-generator"],"latest_commit_sha":null,"homepage":"https://doc.nette.org/php-generator","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"other","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nette.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":"license.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"github":"dg","custom":"https://nette.org/donate"}},"created_at":"2014-03-13T03:52:52.000Z","updated_at":"2025-05-07T15:49:32.000Z","dependencies_parsed_at":"2023-02-19T11:31:22.614Z","dependency_job_id":"7ff5c9c2-c336-4b96-a998-c07dd363378d","html_url":"https://github.com/nette/php-generator","commit_stats":{"total_commits":605,"total_committers":32,"mean_commits":18.90625,"dds":0.06280991735537189,"last_synced_commit":"c511194b601d1daf57626d28b1f4538aabc2e8d9"},"previous_names":[],"tags_count":76,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nette%2Fphp-generator","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nette%2Fphp-generator/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nette%2Fphp-generator/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nette%2Fphp-generator/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nette","download_url":"https://codeload.github.com/nette/php-generator/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254050896,"owners_count":22006377,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["code-generator","nette","nette-framework","php","php-generator"],"created_at":"2024-08-01T16:01:28.907Z","updated_at":"2025-05-15T00:00:27.650Z","avatar_url":"https://github.com/nette.png","language":"PHP","readme":"[![Nette PHP Generator](https://github.com/nette/php-generator/assets/194960/8a2c83bd-daea-475f-994c-9c951de88501)](https://doc.nette.org/en/php-generator)\n\n[![Latest Stable Version](https://poser.pugx.org/nette/php-generator/v/stable)](https://github.com/nette/php-generator/releases) [![Downloads this Month](https://img.shields.io/packagist/dm/nette/php-generator.svg)](https://packagist.org/packages/nette/php-generator)\n\n \u003c!----\u003e\n\nAre you looking for a tool to generate PHP code for [classes](#classes), [functions](#global-functions), or complete [PHP files](#php-files)?\n\n\u003ch3\u003e\n\n✅ Supports all the latest PHP features like [property hooks](#property-hooks), [enums](#enums), [attributes](#attributes), etc.\u003cbr\u003e\n✅ Allows you to easily modify [existing classes](#generating-from-existing-ones)\u003cbr\u003e\n✅ Output compliant with [PSR-12 / PER coding style](#printer-and-psr-compliance)\u003cbr\u003e\n✅ Highly mature, stable, and widely used library\n\n\u003c/h3\u003e\n\n \u003c!----\u003e\n\nInstallation\n------------\n\nDownload and install the library using the [Composer](https://doc.nette.org/en/best-practices/composer) tool:\n\n```shell\ncomposer require nette/php-generator\n```\n\nPhpGenerator 4.1 is compatible with PHP 8.0 to 8.4. Documentation can be found on the [library's website](https://doc.nette.org/php-generator).\n\n \u003c!----\u003e\n\n[Support Me](https://github.com/sponsors/dg)\n--------------------------------------------\n\nDo you like PHP Generator? Are you looking forward to the new features?\n\n[![Buy me a coffee](https://files.nette.org/icons/donation-3.svg)](https://github.com/sponsors/dg)\n\nThank you!\n\n \u003c!----\u003e\n\nClasses\n-------\n\nLet's start with an example of creating a class using [ClassType](https://api.nette.org/php-generator/master/Nette/PhpGenerator/ClassType.html):\n\n```php\n$class = new Nette\\PhpGenerator\\ClassType('Demo');\n\n$class\n\t-\u003esetFinal()\n\t-\u003esetExtends(ParentClass::class)\n\t-\u003eaddImplement(Countable::class)\n\t-\u003eaddComment(\"Class description.\\nSecond line\\n\")\n\t-\u003eaddComment('@property-read Nette\\Forms\\Form $form');\n\n// generate code simply by typecasting to string or using echo:\necho $class;\n```\n\nThis will return:\n\n```php\n/**\n * Class description\n * Second line\n *\n * @property-read Nette\\Forms\\Form $form\n */\nfinal class Demo extends ParentClass implements Countable\n{\n}\n```\n\nTo generate the code, you can also use a so-called printer, which, unlike `echo $class`, can be [further configured](#printer-and-psr-compliance):\n\n```php\n$printer = new Nette\\PhpGenerator\\Printer;\necho $printer-\u003eprintClass($class);\n```\n\nYou can add constants (class [Constant](https://api.nette.org/php-generator/master/Nette/PhpGenerator/Constant.html)) and properties (class [Property](https://api.nette.org/php-generator/master/Nette/PhpGenerator/Property.html)):\n\n```php\n$class-\u003eaddConstant('ID', 123)\n\t-\u003esetProtected() // constant visibility\n\t-\u003esetType('int')\n\t-\u003esetFinal();\n\n$class-\u003eaddProperty('items', [1, 2, 3])\n\t-\u003esetPrivate() // or setVisibility('private')\n\t-\u003esetStatic()\n\t-\u003eaddComment('@var int[]');\n\n$class-\u003eaddProperty('list')\n\t-\u003esetType('?array')\n\t-\u003esetInitialized(); // outputs '= null'\n```\n\nThis will generate:\n\n```php\nfinal protected const int ID = 123;\n\n/** @var int[] */\nprivate static $items = [1, 2, 3];\n\npublic ?array $list = null;\n```\n\nAnd you can add [methods](#method-and-function-signatures):\n\n```php\n$method = $class-\u003eaddMethod('count')\n\t-\u003eaddComment('Count it.')\n\t-\u003esetFinal()\n\t-\u003esetProtected()\n\t-\u003esetReturnType('?int') // return types for methods\n\t-\u003esetBody('return count($items ?: $this-\u003eitems);');\n\n$method-\u003eaddParameter('items', []) // $items = []\n\t-\u003esetReference()           // \u0026$items = []\n\t-\u003esetType('array');        // array \u0026$items = []\n```\n\nThe result is:\n\n```php\n/**\n * Count it.\n */\nfinal protected function count(array \u0026$items = []): ?int\n{\n\treturn count($items ?: $this-\u003eitems);\n}\n```\n\nPromoted parameters introduced in PHP 8.0 can be passed to the constructor:\n\n```php\n$method = $class-\u003eaddMethod('__construct');\n$method-\u003eaddPromotedParameter('name');\n$method-\u003eaddPromotedParameter('args', [])\n\t-\u003esetPrivate();\n```\n\nThe result is:\n\n```php\npublic function __construct(\n\tpublic $name,\n\tprivate $args = [],\n) {\n}\n```\n\nReadonly properties and classes be marked using the `setReadOnly()` function.\n\n------\n\nIf an added property, constant, method, or parameter already exists, an exception is thrown.\n\nClass members can be removed using `removeProperty()`, `removeConstant()`, `removeMethod()`, or `removeParameter()`.\n\nYou can also add existing `Method`, `Property`, or `Constant` objects to the class:\n\n```php\n$method = new Nette\\PhpGenerator\\Method('getHandle');\n$property = new Nette\\PhpGenerator\\Property('handle');\n$const = new Nette\\PhpGenerator\\Constant('ROLE');\n\n$class = (new Nette\\PhpGenerator\\ClassType('Demo'))\n\t-\u003eaddMember($method)\n\t-\u003eaddMember($property)\n\t-\u003eaddMember($const);\n```\n\nYou can also clone existing methods, properties, and constants under a different name using `cloneWithName()`:\n\n```php\n$methodCount = $class-\u003egetMethod('count');\n$methodRecount = $methodCount-\u003ecloneWithName('recount');\n$class-\u003eaddMember($methodRecount);\n```\n\n \u003c!----\u003e\n\nInterfaces or Traits\n--------------------\n\nYou can create interfaces and traits (classes [InterfaceType](https://api.nette.org/php-generator/master/Nette/PhpGenerator/InterfaceType.html) and [TraitType](https://api.nette.org/php-generator/master/Nette/PhpGenerator/TraitType.html)):\n\n```php\n$interface = new Nette\\PhpGenerator\\InterfaceType('MyInterface');\n$trait = new Nette\\PhpGenerator\\TraitType('MyTrait');\n```\n\nUsing a trait:\n\n```php\n$class = new Nette\\PhpGenerator\\ClassType('Demo');\n$class-\u003eaddTrait('SmartObject');\n$class-\u003eaddTrait('MyTrait')\n\t-\u003eaddResolution('sayHello as protected')\n\t-\u003eaddComment('@use MyTrait\u003cFoo\u003e');\necho $class;\n```\n\nThe result is:\n\n```php\nclass Demo\n{\n\tuse SmartObject;\n\t/** @use MyTrait\u003cFoo\u003e */\n\tuse MyTrait {\n\t\tsayHello as protected;\n\t}\n}\n```\n\n \u003c!----\u003e\n\nEnums\n-----\n\nYou can easily create enums introduced in PHP 8.1 like this (class [EnumType](https://api.nette.org/php-generator/master/Nette/PhpGenerator/EnumType.html)):\n\n```php\n$enum = new Nette\\PhpGenerator\\EnumType('Suit');\n$enum-\u003eaddCase('Clubs');\n$enum-\u003eaddCase('Diamonds');\n$enum-\u003eaddCase('Hearts');\n$enum-\u003eaddCase('Spades');\n\necho $enum;\n```\n\nThe result is:\n\n```php\nenum Suit\n{\n\tcase Clubs;\n\tcase Diamonds;\n\tcase Hearts;\n\tcase Spades;\n}\n```\n\nYou can also define scalar equivalents and create a \"backed\" enum:\n\n```php\n$enum-\u003eaddCase('Clubs', '♣');\n$enum-\u003eaddCase('Diamonds', '♦');\n```\n\nFor each *case*, you can add a comment or [attributes](#attributes) using `addComment()` or `addAttribute()`.\n\n \u003c!----\u003e\n\nAnonymous Classes\n-----------------\n\nPass `null` as the name, and you have an anonymous class:\n\n```php\n$class = new Nette\\PhpGenerator\\ClassType(null);\n$class-\u003eaddMethod('__construct')\n\t-\u003eaddParameter('foo');\n\necho '$obj = new class ($val) ' . $class . ';';\n```\n\nThe result is:\n\n```php\n$obj = new class ($val) {\n\n\tpublic function __construct($foo)\n\t{\n\t}\n};\n```\n\n \u003c!----\u003e\n\nGlobal Functions\n----------------\n\nThe code for functions is generated by the class [GlobalFunction](https://api.nette.org/php-generator/master/Nette/PhpGenerator/GlobalFunction.html):\n\n```php\n$function = new Nette\\PhpGenerator\\GlobalFunction('foo');\n$function-\u003esetBody('return $a + $b;');\n$function-\u003eaddParameter('a');\n$function-\u003eaddParameter('b');\necho $function;\n\n// or use the PsrPrinter for output compliant with PSR-2 / PSR-12 / PER\n// echo (new Nette\\PhpGenerator\\PsrPrinter)-\u003eprintFunction($function);\n```\n\nThe result is:\n\n```php\nfunction foo($a, $b)\n{\n\treturn $a + $b;\n}\n```\n\n \u003c!----\u003e\n\nAnonymous Functions\n-------------------\n\nThe code for anonymous functions is generated by the class [Closure](https://api.nette.org/php-generator/master/Nette/PhpGenerator/Closure.html):\n\n```php\n$closure = new Nette\\PhpGenerator\\Closure;\n$closure-\u003esetBody('return $a + $b;');\n$closure-\u003eaddParameter('a');\n$closure-\u003eaddParameter('b');\n$closure-\u003eaddUse('c')\n\t-\u003esetReference();\necho $closure;\n\n// or use the PsrPrinter for output compliant with PSR-2 / PSR-12 / PER\n// echo (new Nette\\PhpGenerator\\PsrPrinter)-\u003eprintClosure($closure);\n```\n\nThe result is:\n\n```php\nfunction ($a, $b) use (\u0026$c) {\n\treturn $a + $b;\n}\n```\n\n \u003c!----\u003e\n\nShort Arrow Functions\n---------------------\n\nYou can also output a short anonymous function using the printer:\n\n```php\n$closure = new Nette\\PhpGenerator\\Closure;\n$closure-\u003esetBody('$a + $b');\n$closure-\u003eaddParameter('a');\n$closure-\u003eaddParameter('b');\n\necho (new Nette\\PhpGenerator\\Printer)-\u003eprintArrowFunction($closure);\n```\n\nThe result is:\n\n```php\nfn($a, $b) =\u003e $a + $b\n```\n\n \u003c!----\u003e\n\nMethod and Function Signatures\n------------------------------\n\nMethods are represented by the class [Method](https://api.nette.org/php-generator/master/Nette/PhpGenerator/Method.html). You can set visibility, return value, add comments, [attributes](#attributes), etc.:\n\n```php\n$method = $class-\u003eaddMethod('count')\n\t-\u003eaddComment('Count it.')\n\t-\u003esetFinal()\n\t-\u003esetProtected()\n\t-\u003esetReturnType('?int');\n```\n\nIndividual parameters are represented by the class [Parameter](https://api.nette.org/php-generator/master/Nette/PhpGenerator/Parameter.html). Again, you can set all conceivable properties:\n\n```php\n$method-\u003eaddParameter('items', []) // $items = []\n\t-\u003esetReference()           // \u0026$items = []\n\t-\u003esetType('array');        // array \u0026$items = []\n\n// function count(\u0026$items = [])\n```\n\nTo define the so-called variadics parameters (or also the splat, spread, ellipsis, unpacking or three dots operator), use `setVariadic()`:\n\n```php\n$method = $class-\u003eaddMethod('count');\n$method-\u003esetVariadic(true);\n$method-\u003eaddParameter('items');\n```\n\nThis generates:\n\n```php\nfunction count(...$items)\n{\n}\n```\n\n \u003c!----\u003e\n\nMethod and Function Bodies\n--------------------------\n\nThe body can be passed all at once to the `setBody()` method or gradually (line by line) by repeatedly calling `addBody()`:\n\n```php\n$function = new Nette\\PhpGenerator\\GlobalFunction('foo');\n$function-\u003eaddBody('$a = rand(10, 20);');\n$function-\u003eaddBody('return $a;');\necho $function;\n```\n\nThe result is:\n\n```php\nfunction foo()\n{\n\t$a = rand(10, 20);\n\treturn $a;\n}\n```\n\nYou can use special placeholders for easy variable insertion.\n\nSimple placeholders `?`\n\n```php\n$str = 'any string';\n$num = 3;\n$function = new Nette\\PhpGenerator\\GlobalFunction('foo');\n$function-\u003eaddBody('return substr(?, ?);', [$str, $num]);\necho $function;\n```\n\nThe result is:\n\n```php\nfunction foo()\n{\n\treturn substr('any string', 3);\n}\n```\n\nPlaceholder for variadic `...?`\n\n```php\n$items = [1, 2, 3];\n$function = new Nette\\PhpGenerator\\GlobalFunction('foo');\n$function-\u003esetBody('myfunc(...?);', [$items]);\necho $function;\n```\n\nThe result is:\n\n```php\nfunction foo()\n{\n\tmyfunc(1, 2, 3);\n}\n```\n\nYou can also use named parameters for PHP 8 with `...?:`\n\n```php\n$items = ['foo' =\u003e 1, 'bar' =\u003e true];\n$function-\u003esetBody('myfunc(...?:);', [$items]);\n\n// myfunc(foo: 1, bar: true);\n```\n\nThe placeholder is escaped with a backslash `\\?`\n\n```php\n$num = 3;\n$function = new Nette\\PhpGenerator\\GlobalFunction('foo');\n$function-\u003eaddParameter('a');\n$function-\u003eaddBody('return $a \\? 10 : ?;', [$num]);\necho $function;\n```\n\nThe result is:\n\n```php\nfunction foo($a)\n{\n\treturn $a ? 10 : 3;\n}\n```\n\n \u003c!----\u003e\n\nPrinter and PSR Compliance\n--------------------------\n\nThe [Printer](https://api.nette.org/php-generator/master/Nette/PhpGenerator/Printer.html) class is used for generating PHP code:\n\n```php\n$class = new Nette\\PhpGenerator\\ClassType('Demo');\n// ...\n\n$printer = new Nette\\PhpGenerator\\Printer;\necho $printer-\u003eprintClass($class); // same as: echo $class\n```\n\nIt can generate code for all other elements, offering methods like `printFunction()`, `printNamespace()`, etc.\n\nThere's also the `PsrPrinter` class, which outputs in accordance with PSR-2 / PSR-12 / PER coding style:\n\n```php\n$printer = new Nette\\PhpGenerator\\PsrPrinter;\necho $printer-\u003eprintClass($class);\n```\n\nNeed custom behavior? Create your own version by inheriting the `Printer` class. You can reconfigure these variables:\n\n```php\nclass MyPrinter extends Nette\\PhpGenerator\\Printer\n{\n\t// length of the line after which the line will break\n\tpublic int $wrapLength = 120;\n\t// indentation character, can be replaced with a sequence of spaces\n\tpublic string $indentation = \"\\t\";\n\t// number of blank lines between properties\n\tpublic int $linesBetweenProperties = 0;\n\t// number of blank lines between methods\n\tpublic int $linesBetweenMethods = 2;\n\t// number of blank lines between 'use statements' groups for classes, functions, and constants\n\tpublic int $linesBetweenUseTypes = 0;\n\t// position of the opening curly brace for functions and methods\n\tpublic bool $bracesOnNextLine = true;\n\t// place one parameter on one line, even if it has an attribute or is supported\n\tpublic bool $singleParameterOnOneLine = false;\n\t// omits namespaces that do not contain any class or function\n\tpublic bool $omitEmptyNamespaces = true;\n\t// separator between the right parenthesis and return type of functions and methods\n\tpublic string $returnTypeColon = ': ';\n}\n```\n\nHow and why does the standard `Printer` differ from `PsrPrinter`? Why isn't there just one printer, the `PsrPrinter`, in the package?\n\nThe 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](https://doc.nette.org/en/contributing/coding-standard) that differs in a few minor aspects.\nThe 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](https://doc.nette.org/en/contributing/coding-standard#toc-tabs-instead-of-spaces).\nAn 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](https://doc.nette.org/en/contributing/coding-standard#toc-wrapping-and-braces).\n\n \u003c!----\u003e\n\nTypes\n-----\n\nEvery type or union/intersection type can be passed as a string; you can also use predefined constants for native types:\n\n```php\nuse Nette\\PhpGenerator\\Type;\n\n$member-\u003esetType('array'); // or Type::Array;\n$member-\u003esetType('?array'); // or Type::nullable(Type::Array);\n$member-\u003esetType('array|string'); // or Type::union(Type::Array, Type::String)\n$member-\u003esetType('Foo\u0026Bar'); // or Type::intersection(Foo::class, Bar::class)\n$member-\u003esetType(null); // removes the type\n```\n\nThe same applies to the `setReturnType()` method.\n\n \u003c!----\u003e\n\nLiterals\n--------\n\nUsing `Literal`, you can pass any PHP code, for example, for default property values or parameters, etc:\n\n```php\nuse Nette\\PhpGenerator\\Literal;\n\n$class = new Nette\\PhpGenerator\\ClassType('Demo');\n\n$class-\u003eaddProperty('foo', new Literal('Iterator::SELF_FIRST'));\n\n$class-\u003eaddMethod('bar')\n\t-\u003eaddParameter('id', new Literal('1 + 2'));\n\necho $class;\n```\n\nResult:\n\n```php\nclass Demo\n{\n\tpublic $foo = Iterator::SELF_FIRST;\n\n\tpublic function bar($id = 1 + 2)\n\t{\n\t}\n}\n```\n\nYou can also pass parameters to `Literal` and have them formatted into valid PHP code using [placeholders](#method-and-function-bodies):\n\n```php\nnew Literal('substr(?, ?)', [$a, $b]);\n// generates for example: substr('hello', 5);\n```\n\nA literal representing the creation of a new object can easily be generated using the `new` method:\n\n```php\nLiteral::new(Demo::class, [$a, 'foo' =\u003e $b]);\n// generates for example: new Demo(10, foo: 20)\n```\n\n \u003c!----\u003e\n\nAttributes\n----------\n\nWith PHP 8, you can add attributes to all classes, methods, properties, constants, enum cases, functions, closures, and parameters. You can also use [literals](#literals) as parameter values.\n\n```php\n$class = new Nette\\PhpGenerator\\ClassType('Demo');\n$class-\u003eaddAttribute('Table', [\n\t'name' =\u003e 'user',\n\t'constraints' =\u003e [\n\t\tLiteral::new('UniqueConstraint', ['name' =\u003e 'ean', 'columns' =\u003e ['ean']]),\n\t],\n]);\n\n$class-\u003eaddProperty('list')\n\t-\u003eaddAttribute('Deprecated');\n\n$method = $class-\u003eaddMethod('count')\n\t-\u003eaddAttribute('Foo\\Cached', ['mode' =\u003e true]);\n\n$method-\u003eaddParameter('items')\n\t-\u003eaddAttribute('Bar');\n\necho $class;\n```\n\nResult:\n\n```php\n#[Table(name: 'user', constraints: [new UniqueConstraint(name: 'ean', columns: ['ean'])])]\nclass Demo\n{\n\t#[Deprecated]\n\tpublic $list;\n\n\n\t#[Foo\\Cached(mode: true)]\n\tpublic function count(\n\t\t#[Bar]\n\t\t$items,\n\t) {\n\t}\n}\n```\n\n \u003c!----\u003e\n\nProperty Hooks\n--------------\n\nYou can also define property hooks (represented by the class [PropertyHook](https://api.nette.org/php-generator/master/Nette/PhpGenerator/PropertyHook.html)) for get and set operations, a feature introduced in PHP 8.4:\n\n```php\n$class = new Nette\\PhpGenerator\\ClassType('Demo');\n$prop = $class-\u003eaddProperty('firstName')\n    -\u003esetType('string');\n\n$prop-\u003eaddHook('set', 'strtolower($value)')\n    -\u003eaddParameter('value')\n\t    -\u003esetType('string');\n\n$prop-\u003eaddHook('get')\n\t-\u003esetBody('return ucfirst($this-\u003efirstName);');\n\necho $class;\n```\n\nThis generates:\n\n```php\nclass Demo\n{\n    public string $firstName {\n        set(string $value) =\u003e strtolower($value);\n        get {\n            return ucfirst($this-\u003efirstName);\n        }\n    }\n}\n```\n\nProperties and property hooks can be abstract or final:\n\n```php\n$class-\u003eaddProperty('id')\n    -\u003esetType('int')\n    -\u003eaddHook('get')\n        -\u003esetAbstract();\n\n$class-\u003eaddProperty('role')\n    -\u003esetType('string')\n    -\u003eaddHook('set', 'strtolower($value)')\n        -\u003esetFinal();\n```\n\n \u003c!----\u003e\n\nAsymmetric Visibility\n---------------------\n\nPHP 8.4 introduces asymmetric visibility for properties. You can set different access levels for reading and writing.\nThe 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'.\n\n```php\n$class = new Nette\\PhpGenerator\\ClassType('Demo');\n\n$class-\u003eaddProperty('name')\n    -\u003esetType('string')\n    -\u003esetVisibility('public', 'private'); // public for read, private for write\n\n$class-\u003eaddProperty('id')\n    -\u003esetType('int')\n    -\u003esetProtected('set'); // protected for write\n\necho $class;\n```\n\nThis generates:\n\n```php\nclass Demo\n{\n    public private(set) string $name;\n\n    protected(set) int $id;\n}\n```\n\n \u003c!----\u003e\n\nNamespace\n---------\n\nClasses, traits, interfaces, and enums (hereafter referred to as classes) can be grouped into namespaces represented by the [PhpNamespace](https://api.nette.org/php-generator/master/Nette/PhpGenerator/PhpNamespace.html) class:\n\n```php\n$namespace = new Nette\\PhpGenerator\\PhpNamespace('Foo');\n\n// create new classes in the namespace\n$class = $namespace-\u003eaddClass('Task');\n$interface = $namespace-\u003eaddInterface('Countable');\n$trait = $namespace-\u003eaddTrait('NameAware');\n\n// or insert an existing class into the namespace\n$class = new Nette\\PhpGenerator\\ClassType('Task');\n$namespace-\u003eadd($class);\n```\n\nIf the class already exists, an exception is thrown.\n\nYou can define use clauses:\n\n```php\n// use Http\\Request;\n$namespace-\u003eaddUse(Http\\Request::class);\n// use Http\\Request as HttpReq;\n$namespace-\u003eaddUse(Http\\Request::class, 'HttpReq');\n// use function iter\\range;\n$namespace-\u003eaddUseFunction('iter\\range');\n```\n\nTo simplify a fully qualified class, function, or constant name based on defined aliases, use the `simplifyName` method:\n\n```php\necho $namespace-\u003esimplifyName('Foo\\Bar'); // 'Bar', because 'Foo' is the current namespace\necho $namespace-\u003esimplifyName('iter\\range', $namespace::NameFunction); // 'range', due to the defined use-statement\n```\n\nConversely, you can convert a simplified class, function, or constant name back to a fully qualified name using the `resolveName` method:\n\n```php\necho $namespace-\u003eresolveName('Bar'); // 'Foo\\Bar'\necho $namespace-\u003eresolveName('range', $namespace::NameFunction); // 'iter\\range'\n```\n\n \u003c!----\u003e\n\nClass Names Resolving\n---------------------\n\n**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).\nThis 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:\n\n```php\n$namespace = new Nette\\PhpGenerator\\PhpNamespace('Foo');\n$namespace-\u003eaddUse('Bar\\AliasedClass');\n\n$class = $namespace-\u003eaddClass('Demo');\n$class-\u003eaddImplement('Foo\\A') // will be simplified to A\n\t-\u003eaddTrait('Bar\\AliasedClass'); // will be simplified to AliasedClass\n\n$method = $class-\u003eaddMethod('method');\n$method-\u003eaddComment('@return ' . $namespace-\u003esimplifyType('Foo\\D')); // we manually simplify in comments\n$method-\u003eaddParameter('arg')\n\t-\u003esetType('Bar\\OtherClass'); // will be translated to \\Bar\\OtherClass\n\necho $namespace;\n\n// or use the PsrPrinter for output in accordance with PSR-2 / PSR-12 / PER\n// echo (new Nette\\PhpGenerator\\PsrPrinter)-\u003eprintNamespace($namespace);\n```\n\nResult:\n\n```php\nnamespace Foo;\n\nuse Bar\\AliasedClass;\n\nclass Demo implements A\n{\n\tuse AliasedClass;\n\n\t/**\n\t * @return D\n\t */\n\tpublic function method(\\Bar\\OtherClass $arg)\n\t{\n\t}\n}\n```\n\nAuto-resolving can be turned off this way:\n\n```php\n$printer = new Nette\\PhpGenerator\\Printer; // or PsrPrinter\n$printer-\u003esetTypeResolving(false);\necho $printer-\u003eprintNamespace($namespace);\n```\n\n \u003c!----\u003e\n\nPHP Files\n---------\n\nClasses, functions, and namespaces can be grouped into PHP files represented by the [PhpFile](https://api.nette.org/php-generator/master/Nette/PhpGenerator/PhpFile.html) class:\n\n```php\n$file = new Nette\\PhpGenerator\\PhpFile;\n$file-\u003eaddComment('This file is auto-generated.');\n$file-\u003esetStrictTypes(); // adds declare(strict_types=1)\n\n$class = $file-\u003eaddClass('Foo\\A');\n$function = $file-\u003eaddFunction('Foo\\foo');\n\n// or\n// $namespace = $file-\u003eaddNamespace('Foo');\n// $class = $namespace-\u003eaddClass('A');\n// $function = $namespace-\u003eaddFunction('foo');\n\necho $file;\n\n// or use the PsrPrinter for output in accordance with PSR-2 / PSR-12 / PER\n// echo (new Nette\\PhpGenerator\\PsrPrinter)-\u003eprintFile($file);\n```\n\nResult:\n\n```php\n\u003c?php\n\n/**\n * This file is auto-generated.\n */\n\ndeclare(strict_types=1);\n\nnamespace Foo;\n\nclass A\n{\n}\n\nfunction foo()\n{\n}\n```\n\n**Please note:** No additional code can be added to the files outside of functions and classes.\n\n \u003c!----\u003e\n\nGenerating from Existing Ones\n-----------------------------\n\nIn addition to being able to model classes and functions using the API described above, you can also have them automatically generated using existing ones:\n\n```php\n// creates a class identical to the PDO class\n$class = Nette\\PhpGenerator\\ClassType::from(PDO::class);\n\n// creates a function identical to the trim() function\n$function = Nette\\PhpGenerator\\GlobalFunction::from('trim');\n\n// creates a closure based on the provided one\n$closure = Nette\\PhpGenerator\\Closure::from(\n\tfunction (stdClass $a, $b = null) {},\n);\n```\n\nBy default, function and method bodies are empty. If you also want to load them, use this method\n(requires the `nikic/php-parser` package to be installed):\n\n```php\n$class = Nette\\PhpGenerator\\ClassType::from(Foo::class, withBodies: true);\n\n$function = Nette\\PhpGenerator\\GlobalFunction::from('foo', withBody: true);\n```\n\n \u003c!----\u003e\n\nLoading from PHP Files\n----------------------\n\nYou can also load functions, classes, interfaces, and enums directly from a string containing PHP code. For example, to create a `ClassType` object:\n\n```php\n$class = Nette\\PhpGenerator\\ClassType::fromCode(\u003c\u003c\u003cXX\n\t\u003c?php\n\n\tclass Demo\n\t{\n\t\tpublic $foo;\n\t}\n\tXX);\n```\n\nWhen 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.\n\nYou can also directly load an entire PHP file, which can contain any number of classes, functions, or even namespaces:\n\n```php\n$file = Nette\\PhpGenerator\\PhpFile::fromCode(file_get_contents('classes.php'));\n```\n\nThe file's initial comment and `strict_types` declaration are also loaded. However, all other global code is ignored.\n\nIt requires `nikic/php-parser` to be installed.\n\n*(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.)*\n\n \u003c!----\u003e\n\nClass Manipulator\n-----------------\n\nThe [ClassManipulator](https://api.nette.org/php-generator/master/Nette/PhpGenerator/ClassManipulator.html) class provides tools for manipulating classes.\n\n```php\n$class = new Nette\\PhpGenerator\\ClassType('Demo');\n$manipulator = new Nette\\PhpGenerator\\ClassManipulator($class);\n```\n\nThe `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:\n\n```php\n$method = $manipulator-\u003einheritMethod('bar');\n$method-\u003esetBody('...');\n```\n\nThe `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:\n\n```php\n$property = $manipulator-\u003einheritProperty('foo');\n$property-\u003esetValue('new value');\n```\n\nThe `implement()` method automatically implements all methods and properties from the given interface or abstract class:\n\n```php\n$manipulator-\u003eimplement(SomeInterface::class);\n// Now your class implements SomeInterface and includes all its methods\n```\n\n \u003c!----\u003e\n\nVariable Dumping\n----------------\n\nThe `Dumper` class converts a variable into parseable PHP code. It provides a better and clearer output than the standard `var_export()` function.\n\n```php\n$dumper = new Nette\\PhpGenerator\\Dumper;\n\n$var = ['a', 'b', 123];\n\necho $dumper-\u003edump($var); // outputs ['a', 'b', 123]\n```\n","funding_links":["https://github.com/sponsors/dg","https://nette.org/donate"],"categories":["PHP"],"sub_categories":[],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnette%2Fphp-generator","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnette%2Fphp-generator","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnette%2Fphp-generator/lists"}