Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Alex dolgov/hw5 #576

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .env.dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
COMPOSE_FILE=docker/docker-compose.yaml:docker/docker-compose.yaml
MYSQL_ROOT_PASSWORD=
MYSQL_DATABASE=
MYSQL_USER=
MYSQL_PASSWORD=
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
.env
vendor
mysql-data
.idea
composer.lock
10 changes: 10 additions & 0 deletions composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"name": "aleksandrdolgov/otus_php_2023",
"type": "project",
"autoload": {
"psr-4": {
"Aleksandrdolgov\\OtusPhp2023\\": "src/"
}
},
"require": {}
}
64 changes: 64 additions & 0 deletions docker/docker-compose.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
version: '3'

services:
nginx:
build:
context: ./nginx
dockerfile: Dockerfile
image: myapp/nginx
container_name: webserver
ports:
- "80:80"
volumes:
- ../src:/app
networks:
- app-network

memcached:
build:
context: ./memcached
dockerfile: Dockerfile
ports:
- "11211:11211"
container_name: app-memcached
networks:
- app-network

app1:
build:
context: ./..
dockerfile: docker/fpm/Dockerfile
image: myapp/php
container_name: app1
volumes:
- ../src:/app
networks:
- app-network

# second php-fpm
app2:
build:
context: ./..
dockerfile: docker/fpm/Dockerfile
image: myapp/php
container_name: app2
volumes:
- ../src:/app
networks:
- app-network

# second php-fpm
app3:
build:
context: ./..
dockerfile: docker/fpm/Dockerfile
image: myapp/php
container_name: app3
volumes:
- ../src:/app
networks:
- app-network

networks:
app-network:
driver: bridge
40 changes: 40 additions & 0 deletions docker/fpm/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
FROM php:8.2-fpm

# ставим необходимые для нормальной работы модули
ADD https://github.com/mlocati/docker-php-extension-installer/releases/latest/download/install-php-extensions /usr/local/bin/

RUN apt-get update && apt-get install -y \
libfreetype6-dev \
libjpeg62-turbo-dev \
libpng-dev \
libonig-dev \
libzip-dev \
libmemcached11 \
zlib1g-dev libssl-dev \
libmemcached-dev \
libmcrypt-dev \
&& pecl install mcrypt \
&& docker-php-ext-enable mcrypt \
&& docker-php-ext-install -j$(nproc) iconv mbstring mysqli pdo_mysql zip \
&& docker-php-ext-configure gd --with-freetype --with-jpeg \
&& docker-php-ext-install -j$(nproc) gd \
&& chmod +x /usr/local/bin/install-php-extensions \
&& install-php-extensions redis \
&& install-php-extensions @composer-2.2.0 \
&& install-php-extensions memcached

COPY docker/fpm/php.ini /usr/local/etc/php/conf.d/php-custom.ini

COPY --from=composer:latest /usr/bin/composer /usr/local/bin/composer

USER www-data:www-data

COPY ../../../composer.json composer.json

RUN composer install

WORKDIR /app

VOLUME /app

CMD ["php-fpm"]
2 changes: 2 additions & 0 deletions docker/fpm/php.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
session.save_handler = memcache
session.save_path = "tcp://memcache:11211"
1 change: 1 addition & 0 deletions docker/memcached/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
FROM memcached:latest
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Если мы не собираемся как-то менять базовый образ, то нам нет нужды описывать dockerfile, можем просто использовать базовый образ.

1 change: 1 addition & 0 deletions docker/mysql/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
FROM mysql:latest
11 changes: 11 additions & 0 deletions docker/nginx/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
FROM nginx

COPY ./application.local.conf /etc/nginx/conf.d/application.local.conf

WORKDIR /app

VOLUME /app

EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]
42 changes: 42 additions & 0 deletions docker/nginx/application.local.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
upstream php-fpm-backend {
least_conn;
server app1:9000;
server app2:9000;
server app3:9000;
}

server {
# указываем 80 порт для соединения
listen 80;
# нужно указать, какому доменному имени принадлежит наш конфиг
server_name application.local;

# задаём корневую директорию
root /app;

# стартовый файл
index index.php index.html;

# при обращении к статическим файлам логи не нужны, равно как и обращение к fpm
# http://application.local/static/some.png
location ~* .(jpg|jpeg|gif|css|png|js|ico|html)$ {
access_log off;
expires max;
}

# помним про единую точку доступа
# все запросы заворачиваются в корневую директорию root на index.php
location / {
try_files $uri $uri/ /index.php?$query_string;
}

# и наконец правило обращения к php-fpm
location ~* .php$ {
try_files $uri = 404;
fastcgi_split_path_info ^(.+.php)(/.+)$;
fastcgi_pass php-fpm-backend;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
25 changes: 25 additions & 0 deletions src/index.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
<?php
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Пожалуйста, используйте паттерн фронт-контроллер. Пусть в index.php будет только инициализация приложения и его запуск:

$app = new App();
echo $app->run();


echo "<h1>This is " . $_SERVER['HOSTNAME'] . "</h1>";
// Создание объекта Memcached
$memcached = new Memcached();

// Добавление серверов Memcached (адрес и порт)
$memcached->addServer("memcached", 11211);

$key = 'test_key';
$value = 'Hello, Memcached!';

// Запись данных
$memcached->set($key, $value, 3600);

// Чтение данных
$result = $memcached->get($key);

if ($result === $value) {
echo sprintf('Memcached is working! Your value: %s<br>', $result);
} else {
echo "Memcached is not working!";
}

phpinfo();
35 changes: 35 additions & 0 deletions src/validator.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
<?php
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Данный файл лежит в папке, которую обслуживает nginx. Как итог, пользователь может запросить её напрямую - это плохо. Нужно создать отдельную папку public, где будет только index.php.


declare(strict_types=1);

namespace Aleksandrdolgov\OtusPhp2023;

use Exception;

function validateString(string $string): bool {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Обратите внимание на предупреждение линтера и исправьте пожалуйста форматирование.

if (preg_match('/^(\((?1)*\))*$/', $string)) {
return true;
} else {
return false;
}
}

try {
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
throw new Exception('Use POST method', 400);
}

$string = $_POST['string'] ?? '';

if (empty($string)) {
throw new Exception('Send me not empty "string" param', 400);
}

if (validateString($string)) {
echo sprintf('Скобки в строке "<b>%s</b>" прошли валидацию', $string);
} else {
echo sprintf('Строка "<b>%s</b>" не прошла валидацию на скобки', $string);
}
} catch (Exception $exception) {
header("HTTP/1.1 {$exception->getCode()} {$exception->getMessage()}");
}