1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Albert221\Blog; |
4
|
|
|
|
5
|
|
|
use Albert221\Blog\Controller\PostController; |
6
|
|
|
use Albert221\Blog\ServiceProvider\HttpServiceProvider; |
7
|
|
|
use Albert221\Blog\ServiceProvider\TwigServiceProvider; |
8
|
|
|
use League\Container\Container; |
9
|
|
|
use League\Container\ReflectionContainer; |
10
|
|
|
use League\Route\RouteCollection; |
11
|
|
|
use Zend\Diactoros\Request; |
12
|
|
|
use Zend\Diactoros\Response; |
13
|
|
|
use Zend\Diactoros\Response\SapiEmitter; |
14
|
|
|
use Zend\Diactoros\ServerRequest; |
15
|
|
|
|
16
|
|
|
class App |
17
|
|
|
{ |
18
|
|
|
/** |
19
|
|
|
* @var Container |
20
|
|
|
*/ |
21
|
|
|
protected $container; |
22
|
|
|
|
23
|
|
|
public function __construct() |
24
|
|
|
{ |
25
|
|
|
$this->container = new Container; |
26
|
|
|
$this->container->delegate(new ReflectionContainer); |
27
|
|
|
|
28
|
|
|
$this->container->add('baseDir', dirname(__DIR__)); |
29
|
|
|
|
30
|
|
|
$this->container->addServiceProvider(new HttpServiceProvider); |
31
|
|
|
$this->container->addServiceProvider(new TwigServiceProvider); |
32
|
|
|
|
33
|
|
|
$this->container->add(PostController::class) |
|
|
|
|
34
|
|
|
->withMethodCall('setTwig', ['twig']); |
35
|
|
|
} |
36
|
|
|
|
37
|
|
|
/** |
38
|
|
|
* Sends response. |
39
|
|
|
*/ |
40
|
|
|
public function run() |
41
|
|
|
{ |
42
|
|
|
/** @var RouteCollection $route */ |
43
|
|
|
$route = $this->container->get('route'); |
44
|
|
|
/** @var ServerRequest $request */ |
45
|
|
|
$request = $this->container->get('request'); |
46
|
|
|
/** @var Response $response */ |
47
|
|
|
$response = $this->container->get('response'); |
48
|
|
|
/** @var SapiEmitter $emitter */ |
49
|
|
|
$emitter = $this->container->get('emitter'); |
50
|
|
|
|
51
|
|
|
$response = $route->dispatch($request, $response); |
52
|
|
|
|
53
|
|
|
$emitter->emit($response); |
54
|
|
|
} |
55
|
|
|
} |
Let’s take a look at an example:
In the above example, the authenticate() method works fine as long as you just pass instances of MyUser. However, if you now also want to pass a different implementation of User which does not have a getDisplayName() method, the code will break.
Available Fixes
Change the type-hint for the parameter:
Add an additional type-check:
Add the method to the interface: