Skip to content

Commit cef3a93

Browse files
committed
master - extracted application construction in static method, done some refactoring
1 parent 9c1546b commit cef3a93

File tree

4 files changed

+95
-65
lines changed

4 files changed

+95
-65
lines changed

example/index.php

Lines changed: 3 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,46 +1,18 @@
11
<?php
22

3-
/**
4-
* Use this template for index.php to start project.
5-
* Application expects you to register handlers for web path via $app->get or $app->post
6-
* Alternatively you can create controller with action to work with
7-
* For example web path GET /order/create can be defined as (Slim way):
8-
* $app->get('/order/create', function(RequestInterface $request, ResponseInterface $response) {
9-
* $response->setBody("Hello from order create request");
10-
* }
11-
* );
12-
* or as a controller (Yii2 way):
13-
* ./src/controller/OrderController::createAction(RequestInterface $request, ResponseInterface $response)
14-
*/
15-
163
use FF\Application;
17-
use FF\container\PHPDIContainer;
184
use FF\http\Request;
195
use FF\http\Response;
20-
use FF\logger\MonologLogger;
21-
use FF\view\TemplateEngine;
22-
use FF\view\View;
23-
use Monolog\Logger;
246

257
include_once '../../vendor/autoload.php';
268

27-
$definitions = [
28-
MonologLogger::class => function () {
29-
return new MonologLogger(new Logger('app_name_index'));
30-
},
31-
View::class => function () {
32-
return new View(new TemplateEngine(__DIR__ . '/../view'));
33-
}
34-
];
35-
36-
$container = new PHPDIContainer($definitions);
9+
$app = Application::construct(['appName' => 'ff-demo-app']);
3710

38-
$app = (new Application($container, ['controllerNamespace' => 'app\controller\\']));
3911
$app->get('/', function (Request $request, Response $response) {
4012
$response->setBody("Hello from main route");
4113
});
42-
$app->get('/order', function($request, Response $response) {
43-
$response->setBody("Hello from order request");
14+
$app->post('/order', function(Request $request, Response $response) {
15+
$response->setBody("Hello from order post request");
4416
});
4517

4618
$app->run();

src/FF/Application.php

Lines changed: 79 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -4,13 +4,17 @@
44

55
use Closure;
66
use Exception;
7+
use FF\container\PHPDIContainer;
78
use FF\exceptions\MethodAlreadyRegistered;
89
use FF\exceptions\UnavailableRequestException;
910
use FF\http\Request;
1011
use FF\http\Response;
1112
use FF\logger\MonologLogger;
1213
use FF\router\Router;
1314
use FF\router\RouterInterface;
15+
use FF\view\TemplateEngine;
16+
use FF\view\View;
17+
use Monolog\Logger;
1418
use Psr\Container\ContainerExceptionInterface;
1519
use Psr\Container\ContainerInterface;
1620
use Psr\Container\NotFoundExceptionInterface;
@@ -22,23 +26,65 @@ class Application extends BaseApplication
2226
public RouterInterface $router;
2327
public LoggerInterface $logger;
2428

25-
private Request $request;
29+
/** @var bool is application running correctly */
2630
private bool $status = true;
2731

2832
/**
2933
* @param ContainerInterface $container
34+
* @param RouterInterface $router
35+
* @param LoggerInterface $logger
3036
* @param array $config
31-
* @throws ContainerExceptionInterface
32-
* @throws NotFoundExceptionInterface
3337
*/
34-
public function __construct(ContainerInterface $container, array $config = [])
38+
public function __construct(
39+
ContainerInterface $container,
40+
RouterInterface $router,
41+
LoggerInterface $logger,
42+
array $config = []
43+
)
3544
{
3645
parent::__construct($container, $config);
3746

38-
$this->router = $this->container->get(Router::class);
47+
$this->logger = $logger;
48+
49+
$this->router = $router;
3950
$this->router->setConfig($config);
40-
$this->request = $this->container->get(Request::class);
41-
$this->logger = $this->container->get(MonologLogger::class);
51+
}
52+
53+
/**
54+
* Hide construction from client code
55+
*
56+
* @param array $config
57+
* @return static
58+
* @throws Exception
59+
*/
60+
public static function construct(array $config): static
61+
{
62+
$definitions = [
63+
LoggerInterface::class => function () use ($config) {
64+
return new MonologLogger(new Logger($config['appName'] ?? 'ff-core-app'));
65+
},
66+
RouterInterface::class => function () {
67+
return new Router();
68+
},
69+
];
70+
71+
if (isset($config['viewPath'])) {
72+
$definitions[View::class] = function () use ($config) {
73+
return new View(new TemplateEngine($config['viewPath']));
74+
};
75+
}
76+
77+
if (isset($config['definitions']) && is_array($config['definitions'])) {
78+
$definitions = array_merge($definitions, $config['definitions']);
79+
}
80+
81+
$container = new PHPDIContainer($definitions);
82+
return new static(
83+
$container,
84+
$container->get(RouterInterface::class),
85+
$container->get(LoggerInterface::class),
86+
$config
87+
);
4288
}
4389

4490
/**
@@ -48,55 +94,43 @@ public function __construct(ContainerInterface $container, array $config = [])
4894
*/
4995
public function run(): int
5096
{
51-
try {
52-
$response = new Response();
97+
$request = $this->createRequest();
98+
$response = $this->createResponse();
5399

54-
[$controllerName, $action, $handler] = $this->router->parseRequest($this->request);
100+
try {
101+
[$controllerName, $action, $handler] = $this->router->parseRequest($request);
55102

56103
try {
57104
if ($handler !== null) {
58-
$handler($this->request, $response);
105+
$handler($request, $response);
59106
} elseif ($controllerName !== null && $action !== null) {
60107
$controller = $this->container->get($controllerName);
61108
$controller->setRouter($this->router);
62109

63-
$controller->$action($this->request, $response);
110+
$controller->$action($request, $response);
64111
} else {
65112
throw new Exception("No handlers for request found");
66113
}
67114
} catch (Throwable $e) {
68-
$this->logger->error($e->getMessage(), $this->getContext());
115+
$this->logger->error($e->getMessage(), $request->context());
69116
$response->setBody($e->getMessage());
70117
$this->status = false;
71118
}
72119

73-
try {
74-
// TODO: add response headers and code
75-
echo $response;
76-
} catch (\Throwable $e) {
77-
$this->status = false;
78-
$this->logger->error($e->getMessage(), $this->getContext());
79-
}
120+
$response->send();
80121

81122
return $this->status ? ExitCode::SUCCESS : ExitCode::ERROR;
82123
} catch (UnavailableRequestException $e) {
83-
$this->logger->error('Not available request', $this->getContext());
124+
$this->logger->error('Not available request', $request->context());
84125
$this->showErrorPage($e, '404 Page not found');
85126
} catch (Exception $e) {
86-
$this->logger->error($e->getMessage(), $this->getContext());
127+
$this->logger->error($e->getMessage(), $request->context());
87128
$this->showErrorPage($e);
88129
}
89130

90131
return ExitCode::ERROR;
91132
}
92133

93-
private function getContext(): array
94-
{
95-
return [
96-
'request' => $this->request->server('REQUEST_URI'),
97-
'ip' => $this->request->server('REMOTE_ADDR')
98-
];
99-
}
100134

101135
/**
102136
* @param Exception $e
@@ -130,4 +164,20 @@ public function post(string $path, Closure $handler): void
130164
{
131165
$this->router->post($path, $handler);
132166
}
167+
168+
/**
169+
* @return Request
170+
*/
171+
private function createRequest(): Request
172+
{
173+
return new Request();
174+
}
175+
176+
/**
177+
* @return Response
178+
*/
179+
private function createResponse(): Response
180+
{
181+
return new Response;
182+
}
133183
}

src/FF/http/Request.php

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,4 +45,12 @@ public function server(string $param = null): array|string
4545

4646
return $this->server;
4747
}
48+
49+
public function context(): array
50+
{
51+
return [
52+
'request' => $this->server('REQUEST_URI'),
53+
'ip' => $this->server('REMOTE_ADDR')
54+
];
55+
}
4856
}

src/FF/http/Response.php

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,16 +5,16 @@ class Response
55
{
66
private string $body;
77

8-
public function __toString(): string
9-
{
10-
return $this->body;
11-
}
12-
138
/**
149
* @param string $body
1510
*/
1611
public function setBody(string $body): void
1712
{
1813
$this->body = $body;
1914
}
15+
16+
public function send(): void
17+
{
18+
echo $this->body;
19+
}
2020
}

0 commit comments

Comments
 (0)