Skip to content

Commit e9bb0b1

Browse files
committed
readme: updated
1 parent 7051954 commit e9bb0b1

File tree

1 file changed

+104
-96
lines changed

1 file changed

+104
-96
lines changed

readme.md

Lines changed: 104 additions & 96 deletions
Original file line numberDiff line numberDiff line change
@@ -11,19 +11,13 @@ Nette PHP Generator
1111
Introduction
1212
------------
1313

14-
Generate PHP code, classes, namespaces etc. with a simple programmatical API.
14+
Do you need to generate PHP code of classes, functions, namespaces, etc.? This library with a friendly API will help you.
1515

16-
Documentation can be found on the [website](https://doc.nette.org/php-generator).
16+
Documentation can be found on the [website](https://doc.nette.org/php-generator). If you like it, **[please make a donation now](https://github.com/sponsors/dg)**. Thank you!
1717

18-
If you like Nette, **[please make a donation now](https://nette.org/donate)**. Thank you!
18+
Installation:
1919

20-
21-
Installation
22-
------------
23-
24-
The recommended way to install is via Composer:
25-
26-
```
20+
```shell
2721
composer require nette/php-generator
2822
```
2923

@@ -33,10 +27,11 @@ composer require nette/php-generator
3327
- PhpGenerator 2.6 is compatible with PHP 5.6 to 7.3
3428

3529

36-
Usage
37-
-----
3830

39-
Usage is very easy. Let's start with a straightforward example of generating class:
31+
Classes
32+
-------
33+
34+
Let's start with a straightforward example of generating class using [ClassType](https://api.nette.org/3.0/Nette/PhpGenerator/ClassType.html):
4035

4136
```php
4237
$class = new Nette\PhpGenerator\ClassType('Demo');
@@ -51,10 +46,6 @@ $class
5146

5247
// to generate PHP code simply cast to string or use echo:
5348
echo $class;
54-
55-
// or use printer:
56-
$printer = new Nette\PhpGenerator\Printer;
57-
echo $printer->printClass($class);
5849
```
5950

6051
It will render this result:
@@ -72,24 +63,39 @@ final class Demo extends ParentClass implements Countable
7263
}
7364
```
7465

75-
We can add constants and properties:
66+
We can also use a printer to generate the code, which, unlike `echo $class`, we will be able to further configure:
7667

7768
```php
78-
$class->addConstant('ID', 123);
69+
$printer = new Nette\PhpGenerator\Printer;
70+
echo $printer->printClass($class);
71+
```
72+
73+
We can add constants ([Constant](https://api.nette.org/3.0/Nette/PhpGenerator/Constant.html)) and properties ([Property](https://api.nette.org/3.0/Nette/PhpGenerator/Property.html)):
74+
75+
```php
76+
$class->addConstant('ID', 123)
77+
->setPrivate(); // constant visiblity
7978

8079
$class->addProperty('items', [1, 2, 3])
81-
->setPrivate()
80+
->setPrivate() // or setVisibility('private')
8281
->setStatic()
8382
->addComment('@var int[]');
83+
84+
$class->addProperty('list')
85+
->setType('array') // or setType(Type::ARRAY)
86+
->setNullable()
87+
->setInitialized(); // prints '= null'
8488
```
8589

8690
It generates:
8791

8892
```php
89-
const ID = 123;
93+
private const ID = 123;
9094

9195
/** @var int[] */
9296
private static $items = [1, 2, 3];
97+
98+
public ?array $list = null;
9399
```
94100

95101
And we can add methods with parameters:
@@ -100,11 +106,13 @@ $method = $class->addMethod('count')
100106
->addComment('@return int')
101107
->setFinal()
102108
->setProtected()
109+
->setReturnType('int') // method return type
110+
->setReturnNullable() // nullable return type
103111
->setBody('return count($items ?: $this->items);');
104112

105113
$method->addParameter('items', []) // $items = []
106-
->setReference() // &$items = []
107-
->setType('array'); // array &$items = []
114+
->setReference() // &$items = []
115+
->setType('array'); // array &$items = []
108116
```
109117

110118
It results in:
@@ -114,7 +122,7 @@ It results in:
114122
* Count it.
115123
* @return int
116124
*/
117-
final protected function count(array &$items = [])
125+
final protected function count(array &$items = []): ?int
118126
{
119127
return count($items ?: $this->items);
120128
}
@@ -124,49 +132,6 @@ If the property, constant, method or parameter already exist, it will be overwri
124132

125133
Members can be removed using `removeProperty()`, `removeConstant()`, `removeMethod()` or `removeParameter()`.
126134

127-
PHP Generator supports all new PHP 7.3 and 7.4 features:
128-
129-
```php
130-
use Nette\PhpGenerator\Type;
131-
132-
$class = new Nette\PhpGenerator\ClassType('Demo');
133-
134-
$class->addConstant('ID', 123)
135-
->setPrivate(); // constant visiblity
136-
137-
$class->addProperty('items')
138-
->setType(Type::ARRAY) // typed properites
139-
->setNullable()
140-
->setInitialized();
141-
142-
$method = $class->addMethod('getValue')
143-
->setReturnType(Type::INT) // method return type
144-
->setReturnNullable() // nullable return type
145-
->setBody('return count($this->items);');
146-
147-
$method->addParameter('id')
148-
->setType(Type::ARRAY) // scalar type hint
149-
->setNullable(); // nullable type hint
150-
151-
echo $class;
152-
```
153-
154-
Result:
155-
156-
```php
157-
class Demo
158-
{
159-
private const ID = 123;
160-
161-
public ?array $items = null;
162-
163-
public function getValue(?int $id): ?int
164-
{
165-
return count($this->items);
166-
}
167-
}
168-
```
169-
170135
You can also add existing `Method`, `Property` or `Constant` objects to the class:
171136

172137
```php
@@ -188,7 +153,7 @@ $methodRecount = $methodCount->cloneWithName('recount');
188153
$class->addMember($methodRecount);
189154
```
190155

191-
Tabs versus spaces
156+
Tabs versus Spaces
192157
------------------
193158

194159
The generated code uses tabs for indentation. If you want to have the output compatible with PSR-2 or PSR-12, use `PsrPrinter`:
@@ -201,8 +166,17 @@ $printer = new Nette\PhpGenerator\PsrPrinter;
201166
echo $printer->printClass($class); // 4 spaces indentation
202167
```
203168

204-
It can be used also for functions, closures, namespaces etc.
205169

170+
Interface or Trait
171+
------------------
172+
173+
You can create interfaces and traits in a similar way, just change the type:
174+
175+
```php
176+
$class = new Nette\PhpGenerator\ClassType('DemoInterface');
177+
$class->setInterface();
178+
// or $class->setTrait();
179+
```
206180

207181
Literals
208182
--------
@@ -235,21 +209,13 @@ class Demo
235209
}
236210
```
237211

238-
Interface or Trait
239-
------------------
240-
241-
```php
242-
$class = new Nette\PhpGenerator\ClassType('DemoInterface');
243-
$class->setInterface();
244-
// or $class->setTrait();
245-
```
246-
247-
Trait Resolutions and Visibility
248-
--------------------------------
212+
Using Traits
213+
------------
249214

250215
```php
251216
$class = new Nette\PhpGenerator\ClassType('Demo');
252-
$class->addTrait('SmartObject', ['sayHello as protected']);
217+
$class->addTrait('SmartObject');
218+
$class->addTrait('MyTrait', ['sayHello as protected']);
253219
echo $class;
254220
```
255221

@@ -258,7 +224,8 @@ Result:
258224
```php
259225
class Demo
260226
{
261-
use SmartObject {
227+
use SmartObject;
228+
use MyTrait {
262229
sayHello as protected;
263230
}
264231
}
@@ -267,6 +234,8 @@ class Demo
267234
Anonymous Class
268235
---------------
269236

237+
Give `null` as the name and you have an anonymous class:
238+
270239
```php
271240
$class = new Nette\PhpGenerator\ClassType(null);
272241
$class->addMethod('__construct')
@@ -289,7 +258,7 @@ $obj = new class ($val) {
289258
Global Function
290259
---------------
291260

292-
Code of function:
261+
Code of functions will generate class [GlobalFunction](https://api.nette.org/3.0/Nette/PhpGenerator/GlobalFunction.html):
293262

294263
```php
295264
$function = new Nette\PhpGenerator\GlobalFunction('foo');
@@ -314,7 +283,7 @@ function foo($a, $b)
314283
Closure
315284
-------
316285

317-
Code of closure:
286+
Code of closures will generate class [Closure](https://api.nette.org/3.0/Nette/PhpGenerator/Closure.html):
318287

319288
```php
320289
$closure = new Nette\PhpGenerator\Closure;
@@ -337,7 +306,7 @@ function ($a, $b) use (&$c) {
337306
}
338307
```
339308

340-
Arrow function
309+
Arrow Function
341310
--------------
342311

343312
You can also print closure as arrow function using printer:
@@ -355,13 +324,32 @@ echo (new Nette\PhpGenerator\Printer)->printArrowFunction($closure);
355324
Result:
356325

357326
```php
358-
fn ($a, $b) => $a + $b;
327+
fn ($a, $b) => $a + $b
359328
```
360329

361330
Method and Function Body Generator
362331
----------------------------------
363332

364-
You can use special placeholders for handy way to generate method or function body.
333+
The body can be passed to the `setBody()` method at once or sequentially (line by line) by repeatedly calling `addBody()`:
334+
335+
```php
336+
$function = new Nette\PhpGenerator\GlobalFunction('foo');
337+
$function->addBody('$a = rand(10, 20);');
338+
$function->addBody('return $a;');
339+
echo $function;
340+
```
341+
342+
Result
343+
344+
```php
345+
function foo()
346+
{
347+
$a = rand(10, 20);
348+
return $a;
349+
}
350+
```
351+
352+
You can use special placeholders for handy way to inject variables.
365353

366354
Simple placeholders:
367355

@@ -422,16 +410,17 @@ function foo($a)
422410
Namespace
423411
---------
424412

425-
Classes, traits and interfaces (hereinafter classes) can be grouped into namespaces:
413+
Classes, traits and interfaces (hereinafter classes) can be grouped into namespaces ([PhpNamespace](https://api.nette.org/3.0/Nette/PhpGenerator/PhpNamespace.html)):
426414

427415
```php
428416
$namespace = new Nette\PhpGenerator\PhpNamespace('Foo');
429417

418+
// create new classes in the namespace
430419
$class = $namespace->addClass('Task');
431420
$interface = $namespace->addInterface('Countable');
432421
$trait = $namespace->addTrait('NameAware');
433422

434-
// or
423+
// or insert an existing class into the namespace
435424
$class = new Nette\PhpGenerator\ClassType('Task');
436425
$namespace->add($class);
437426
```
@@ -441,11 +430,16 @@ If the class already exists, it will be overwritten.
441430
You can define use-statements:
442431

443432
```php
444-
$namespace->addUse(Http\Request::class); // use Http\Request;
445-
$namespace->addUse(Http\Request::class, 'HttpReq'); // use Http\Request as HttpReq;
433+
// use Http\Request;
434+
$namespace->addUse(Http\Request::class);
435+
// use Http\Request as HttpReq;
436+
$namespace->addUse(Http\Request::class, 'HttpReq');
446437
```
447438

448-
**IMPORTANT NOTE:** when the class is part of the namespace, it is rendered slightly differently: all types (ie. type hints, return types, parent class name,
439+
Class Names Resolving
440+
---------------------
441+
442+
**When the class is part of the namespace, it is rendered slightly differently**: all types (ie. type hints, return types, parent class name,
449443
implemented interfaces and used traits) are automatically *resolved* (unless you turn it off, see below).
450444
It means that you have to **use full class names** in definitions and they will be replaced
451445
with aliases (according to the use-statements) or fully qualified names in the resulting code:
@@ -500,7 +494,7 @@ echo $printer->printNamespace($namespace);
500494
PHP Files
501495
---------
502496

503-
PHP files can contains multiple classes, namespaces and comments:
497+
Classes and namespaces can be grouped into PHP files represented by the class [PhpFile](https://api.nette.org/3.0/Nette/PhpGenerator/PhpFile.html):
504498

505499
```php
506500
$file = new Nette\PhpGenerator\PhpFile;
@@ -563,11 +557,10 @@ $function = Nette\PhpGenerator\GlobalFunction::withBodyFrom('dump');
563557
```
564558

565559

566-
Variables dumper
560+
Variables Dumper
567561
----------------
568562

569-
The Dumper returns a parsable PHP string representation of a variable. It provides a better function that you can use instead of `var_export()`
570-
with more readable output.
563+
The Dumper returns a parsable PHP string representation of a variable. Provides better and clearer output that native functon `var_export()`.
571564

572565
```php
573566
$dumper = new Nette\PhpGenerator\Dumper;
@@ -576,3 +569,18 @@ $var = ['a', 'b', 123];
576569

577570
echo $dumper->dump($var); // prints ['a', 'b', 123]
578571
```
572+
573+
Custom Printer
574+
--------------
575+
576+
Need to customize printer behavior? Create your own by inheriting the `Printer` class. You can reconfigure these variables:
577+
578+
```php
579+
class MyPrinter extends Nette\PhpGenerator\Printer
580+
{
581+
protected $indentation = "\t";
582+
protected $linesBetweenProperties = 0;
583+
protected $linesBetweenMethods = 1;
584+
protected $returnTypeColon = ': ';
585+
}
586+
```

0 commit comments

Comments
 (0)