Skip to content

Commit 49836a9

Browse files
committed
BC: Remove dependencies between application context and request context. This was a bad design, use dependency injection instead (see examples)
1 parent 787836d commit 49836a9

10 files changed

+70
-75
lines changed

example/api/Tasks.php

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,13 +3,20 @@
33
/**
44
* This is a sample tasks management class.
55
*/
6-
class Tasks extends \PhpBg\MiniHttpd\Controller\AbstractController
6+
final class Tasks extends \PhpBg\MiniHttpd\Controller\AbstractController
77
{
88
use \PhpBg\MiniHttpd\Middleware\ContextTrait;
99

1010
// Initial tasks
1111
public $tasks = ['task1', 'task2'];
1212

13+
private $loop;
14+
15+
public function __construct(\React\EventLoop\LoopInterface $loop)
16+
{
17+
$this->loop = $loop;
18+
}
19+
1320
/**
1421
* Simple add task example
1522
*/
@@ -30,7 +37,7 @@ public function add(\Psr\Http\Message\ServerRequestInterface $request)
3037
public function addAsync(\Psr\Http\Message\ServerRequestInterface $request)
3138
{
3239
return new React\Promise\Promise(function($resolve, $reject) use ($request) {
33-
$this->getContext($request)->applicationContext->loop->addTimer(2, function() use ($resolve, $reject, $request) {
40+
$this->loop->addTimer(2, function() use ($resolve, $reject, $request) {
3441
try {
3542
$task = $this->getFromPost($request, 'task', null, new \Zend\Validator\NotEmpty());
3643
} catch (\PhpBg\MiniHttpd\Model\ValidateException $e) {

example/bare-minimal-json-server.php

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
// Application context will be accessible everywhere
1010
// @See \PhpBg\MiniHttpd\Middleware\ContextTrait to retrieve it easily
1111
$applicationContext = new \PhpBg\MiniHttpd\Model\ApplicationContext();
12+
$applicationContext->loop = $loop;
1213

1314
// Default renderer
1415
$applicationContext->defaultRenderer = new \PhpBg\MiniHttpd\Renderer\Json();

example/full-featured-server.php

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010

1111
$loop = React\EventLoop\Factory::create();
1212
$jsonRenderer = new \PhpBg\MiniHttpd\Renderer\Json();
13-
$taskController = new Tasks();
13+
$taskController = new Tasks($loop);
1414
$routes = [
1515
// Redirection example
1616
'/' => new \PhpBg\MiniHttpd\Model\Route(function () {
@@ -43,8 +43,6 @@
4343
// You may require loop for async tasks
4444
$applicationContext->loop = $loop;
4545

46-
// You can put your configuration directives in options
47-
$applicationContext->options = [];
4846
$applicationContext->routes = $routes;
4947

5048
// Public path is where static files are served from (optional)

src/Middleware/AutoPhtml.php

Lines changed: 34 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -43,36 +43,43 @@ public function __invoke(ServerRequestInterface $request, callable $next)
4343
$result = $next($request);
4444
$context = $this->getContext($request);
4545
$renderer = $context->getRenderer();
46-
if ($renderer instanceof Phtml && is_object($context->route->handler)) {
47-
$rc = new \ReflectionClass(get_class($context->route->handler));
48-
$controllerFilePath = $rc->getFileName();
49-
$controllerFilePathinfo = pathinfo($controllerFilePath);
46+
if (! isset($renderer)) {
47+
return $result;
48+
}
49+
if (! $renderer instanceof Phtml) {
50+
return $result;
51+
}
52+
if (! is_object($context->route->handler)) {
53+
return $result;
54+
}
55+
$rc = new \ReflectionClass(get_class($context->route->handler));
56+
$controllerFilePath = $rc->getFileName();
57+
$controllerFilePathinfo = pathinfo($controllerFilePath);
5058

51-
// PHTML view file
52-
$phtmlFile = "{$controllerFilePathinfo['dirname']}/{$controllerFilePathinfo['filename']}.phtml";
53-
if (!array_key_exists('viewFilePath', $context->renderOptions)) {
54-
$context->renderOptions['viewFilePath'] = $phtmlFile;
55-
}
59+
// PHTML view file
60+
$phtmlFile = "{$controllerFilePathinfo['dirname']}/{$controllerFilePathinfo['filename']}.phtml";
61+
if (!array_key_exists('viewFilePath', $context->renderOptions)) {
62+
$context->renderOptions['viewFilePath'] = $phtmlFile;
63+
}
5664

57-
// JS file
58-
$jsFile = "{$controllerFilePathinfo['dirname']}/{$controllerFilePathinfo['filename']}.js";
59-
if (!isset($context->renderOptions['inlineScripts'])) {
60-
$context->renderOptions['inlineScripts'] = [];
61-
}
62-
if (is_file($jsFile)) {
63-
//TODO async file get contents?
64-
$context->renderOptions['inlineScripts'][] = file_get_contents($jsFile);
65-
}
65+
// JS file
66+
$jsFile = "{$controllerFilePathinfo['dirname']}/{$controllerFilePathinfo['filename']}.js";
67+
if (!isset($context->renderOptions['inlineScripts'])) {
68+
$context->renderOptions['inlineScripts'] = [];
69+
}
70+
if (is_file($jsFile)) {
71+
//TODO async file get contents?
72+
$context->renderOptions['inlineScripts'][] = file_get_contents($jsFile);
73+
}
6674

67-
// CSS file
68-
$cssFile = "{$controllerFilePathinfo['dirname']}/{$controllerFilePathinfo['filename']}.css";
69-
if (!isset($context->renderOptions['inlineCss'])) {
70-
$context->renderOptions['inlineCss'] = [];
71-
}
72-
if (is_file($cssFile)) {
73-
//TODO async file get contents?
74-
$context->renderOptions['inlineCss'][] = file_get_contents($cssFile);
75-
}
75+
// CSS file
76+
$cssFile = "{$controllerFilePathinfo['dirname']}/{$controllerFilePathinfo['filename']}.css";
77+
if (!isset($context->renderOptions['inlineCss'])) {
78+
$context->renderOptions['inlineCss'] = [];
79+
}
80+
if (is_file($cssFile)) {
81+
//TODO async file get contents?
82+
$context->renderOptions['inlineCss'][] = file_get_contents($cssFile);
7683
}
7784

7885
return $result;

src/Middleware/Context.php

Lines changed: 1 addition & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,6 @@
2626

2727
namespace PhpBg\MiniHttpd\Middleware;
2828

29-
use PhpBg\MiniHttpd\Model\ApplicationContext;
3029
use PhpBg\MiniHttpd\Model\RequestContext;
3130
use Psr\Http\Message\ServerRequestInterface;
3231

@@ -39,17 +38,9 @@ class Context
3938

4039
protected $applicationContext;
4140

42-
/**
43-
* @param ApplicationContext $applicationContext
44-
*/
45-
public function __construct(ApplicationContext $applicationContext)
46-
{
47-
$this->applicationContext = $applicationContext;
48-
}
49-
5041
public function __invoke(ServerRequestInterface $request, callable $next)
5142
{
52-
$context = new RequestContext($this->applicationContext);
43+
$context = new RequestContext();
5344
$request = $this->setContext($request, $context);
5445
return $next($request);
5546
}

src/Middleware/Render.php

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,7 @@ protected function doRenderException(ServerRequestInterface $request, \Exception
116116
protected function getRenderer(ServerRequestInterface $request): RendererInterface
117117
{
118118
$context = $this->getContext($request);
119-
return $context->getRenderer();
119+
$renderer = $context->getRenderer();
120+
return $renderer ?? $this->defaultRenderer;
120121
}
121122
}

src/Middleware/Route.php

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,16 +35,22 @@ class Route
3535
{
3636
use ContextTrait;
3737

38+
protected $routes;
39+
40+
public function __construct(array $routes)
41+
{
42+
$this->routes = $routes;
43+
}
44+
3845
public function __invoke(ServerRequestInterface $request, callable $next)
3946
{
4047
$pathDecoded = $this->getContext($request)->uriPathDecoded;
41-
$routes = $this->getContext($request)->applicationContext->routes;
42-
if (isset($routes[$pathDecoded])) {
43-
if (!$routes[$pathDecoded] instanceof \PhpBg\MiniHttpd\Model\Route) {
48+
if (isset($this->routes[$pathDecoded])) {
49+
if (!$this->routes[$pathDecoded] instanceof \PhpBg\MiniHttpd\Model\Route) {
4450
throw new \RuntimeException("Route $pathDecoded does not extend " . \PhpBg\MiniHttpd\Model\Route::class);
4551
}
4652

47-
$this->getContext($request)->route = $routes[$pathDecoded];
53+
$this->getContext($request)->route = $this->routes[$pathDecoded];
4854
}
4955

5056
return $next($request);

src/Model/ApplicationContext.php

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -41,12 +41,6 @@ class ApplicationContext
4141
*/
4242
public $loop;
4343

44-
/**
45-
* This is where you can put your application configuration
46-
* @var mixed
47-
*/
48-
public $options;
49-
5044
/**
5145
* Array of <uri paths> => <Route>
5246
* @var Route[]
@@ -59,6 +53,12 @@ class ApplicationContext
5953
*/
6054
public $publicPath;
6155

56+
/**
57+
* Root path of the application
58+
* @var string
59+
*/
60+
public $rootPath;
61+
6262
/**
6363
* @var LoggerInterface
6464
*/

src/Model/RequestContext.php

Lines changed: 3 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -35,11 +35,6 @@
3535
*/
3636
class RequestContext
3737
{
38-
/**
39-
* @var ApplicationContext
40-
*/
41-
public $applicationContext;
42-
4338
/**
4439
* @var ResponseInterface
4540
*/
@@ -67,11 +62,6 @@ class RequestContext
6762
*/
6863
public $renderOptions = [];
6964

70-
public function __construct(ApplicationContext $context)
71-
{
72-
$this->applicationContext = $context;
73-
}
74-
7565
/**
7666
* Return the response that will be returned
7767
* Remember that because of PSR-7, responses are immutable so @see RequestContext::setResponse()
@@ -99,16 +89,10 @@ public function setResponse(ResponseInterface $response): ResponseInterface
9989
/**
10090
* Return renderer instance to use
10191
*
102-
* @return RendererInterface
92+
* @return RendererInterface | null
10393
*/
104-
public function getRenderer(): RendererInterface
94+
public function getRenderer()
10595
{
106-
// Use route renderer if any
107-
if (isset($this->route->renderer)) {
108-
return $this->route->renderer;
109-
}
110-
111-
// Otherwise use default renderer
112-
return $this->applicationContext->defaultRenderer;
96+
return $this->route->renderer ?? null;
11397
}
11498
}

src/ServerFactory.php

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,8 @@ public static function createDefaultStack(ApplicationContext $applicationContext
6161
// Log all incoming requests
6262
$middlewares[] = new LogRequest($applicationContext->logger);
6363

64-
// Make application context and request context available to all middlewares. Allow data exchanging between middlewares
65-
$middlewares[] = new Context($applicationContext);
64+
// Make request context available to all middlewares. Allow data exchanging between middlewares
65+
$middlewares[] = new Context();
6666

6767
// Decode once uri path
6868
$middlewares[] = new UriPath();
@@ -90,7 +90,7 @@ public static function createDefaultStack(ApplicationContext $applicationContext
9090
$middlewares[] = new LogError($applicationContext->logger);
9191

9292
// Calculate route to be run
93-
$middlewares[] = new Route();
93+
$middlewares[] = new Route($applicationContext->routes);
9494

9595
// Auto render PHTML files
9696
$middlewares[] = new AutoPhtml();

0 commit comments

Comments
 (0)