Difference between #41 and #42 of
Yii3 - How to start

Revision #42 has been created by rackycz rackycz on Apr 1, 2026, 2:18:12 PM with the memo:

invoke
« previous (#41) next (#43) »

Changes

Title unchanged

Yii3 - How to start

Category unchanged

Tutorials

Yii version unchanged

3.0

Tags unchanged

Content changed

[...]
var_dump(array_map('strtoupper', $array));
var_dump(array_map([$instance, 'go'], $array));
var_dump(array_map(function($a) use ($instance) { return $instance->go($a); }, ['a','B',1,'1']));
```

## Theory around __invoke():
 
- If a class implements the `__invoke()` method it is a `callable-` or `invokable-object`.
 
- Its instance can be used as an anonymous function, callable or closure.
 
- `__invoke()` implements the main (or the only) functionality of the object.
 
 
- Why not to use `$instance->myMethod()` instead? You would need to implement an API and others would have to know it. Calling `$instance()` is a "universal anonymous API". Plus modern middleware or handlers often need to be passed as "callables".
 
- Usual anonymous functions can only do a simple task. When you use `$instance()`, you are backed with a large object which can do much more. It can also use traits, state or OOP benefits.
 
- Method `__invoke($a ,$b)` can take input parameters. But the application must know about them, which brings me back to interfaces. I am confused a little. So the invoke-params should probably be mostly provided by the DI I guess.
 
- But you still can use method instead of invokation. For example in file `config/common/routes.php` you can use both:
 
  - `->action(Web\HomePage\Action::class)` // \__invoke() needed
 
  - `->action([Web\HomePage\Action::class, 'run'])`
 
- Invokable objects are often used for middleware as it fits naturally into dispatcher and pipeline systems. Middleware can then be stateful. But the same aplies to interface-based approaches, you only need to specify the method.
 
 
## Hash annotations for class attributes
PHP 8 introduces annotations like this (not only for class attributes):

- `#[Column(type: 'primary')]`
- `#[Column(type: 'string(255)', nullable: true)]`
- `#[Entity(repository: UserRepository::class)]`
[...]
2 0
5 followers
Viewed: 61 405 times
Version: 3.0
Category: Tutorials
Tags:
Written by: rackycz rackycz
Last updated by: rackycz rackycz
Created on: Oct 8, 2025
Last updated: 7 days ago
Update Article

Revisions

View all history