You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Currently route placeholders are injected in controllers. This was wrongly called "request attribute" in the documentation.
This adds the ability to inject (actual) request attributes in controller parameters too.
Route placeholders take priority over request attributes.
Example:
```php
$app->add(function ($request, $response, $next) {
$request = $request->withAttribute('name', 'Bob');
return $next($request, $response);
});
$app->get('/', function ($name, ResponseInterface $response) {
$response->getBody()->write('Hello ' . $name);
return $response;
});
```
Will show `Hello Bob`.
Copy file name to clipboardExpand all lines: README.md
+21-4Lines changed: 21 additions & 4 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -54,9 +54,10 @@ By default, Slim controllers have a strict signature: `$request, $response, $arg
54
54
55
55
Controller parameters can be any of these things:
56
56
57
-
- request or response injection (parameters must be named `$request` or `$response`)
58
-
- request attribute injection
59
-
- service injection (by type-hint)
57
+
- the request or response (parameters must be named `$request` or `$response`)
58
+
- route placeholders
59
+
- request attributes
60
+
- services (injected by type-hint)
60
61
61
62
You can mix all these types of parameters together too. They will be matched by priority in the order of the list above.
62
63
@@ -72,7 +73,7 @@ $app->get('/', function (ResponseInterface $response, ServerRequestInterface $re
72
73
73
74
As you can see, the order of the parameters doesn't matter. That allows to skip injecting the `$request` if it's not needed for example.
74
75
75
-
#### Request attribute injection
76
+
#### Route placeholder injection
76
77
77
78
```php
78
79
$app->get('/hello/{name}', function ($name, ResponseInterface $response) {
@@ -83,6 +84,22 @@ $app->get('/hello/{name}', function ($name, ResponseInterface $response) {
83
84
84
85
As you can see above, the route's URL contains a `name` placeholder. By simply adding a parameter **with the same name** to the controller, PHP-DI will directly inject it.
$app->get('/', function ($name, ResponseInterface $response) {
96
+
$response->getBody()->write('Hello ' . $name);
97
+
return $response;
98
+
});
99
+
```
100
+
101
+
As you can see above, a middleware sets a `name` attribute. By simply adding a parameter **with the same name** to the controller, PHP-DI will directly inject it.
102
+
86
103
#### Service injection
87
104
88
105
To inject services into your controllers, you can write them as classes. But if you want to write a micro-application using closures, you don't have to give up dependency injection either.
0 commit comments