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

hw12 #1128

Open
wants to merge 1 commit into
base: ASyrovatkin/main
Choose a base branch
from
Open

hw12 #1128

Show file tree
Hide file tree
Changes from all 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
29 changes: 29 additions & 0 deletions builds/fpm/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
FROM php:8.2-fpm

RUN apt-get update && apt-get install -y \
libfreetype6-dev \
libjpeg62-turbo-dev \
libpng-dev \
libonig-dev \
libzip-dev \
libmemcached-dev \
libmcrypt-dev \
libssl-dev pkg-config unzip git \
&& docker-php-ext-install -j$(nproc) iconv mbstring

RUN pecl install redis \
&& rm -rf /tmp/pear \
&& docker-php-ext-enable redis\
&& pecl install zlib zip mongodb \
&& docker-php-ext-enable mongodb

RUN curl -sS https://getcomposer.org/installer | php -- --install-dir=/usr/local/bin --filename=composer


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

WORKDIR /data

VOLUME /data

CMD ["php-fpm"]
3 changes: 3 additions & 0 deletions builds/fpm/php.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
session.save_handler = memcache
session.save_path = "tcp://memcache:11211"
extension = mongodb.so;
10 changes: 10 additions & 0 deletions builds/nginx/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
FROM nginx:latest

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

WORKDIR /data

EXPOSE 80

CMD ["nginx", "-g", "daemon off;"]

34 changes: 34 additions & 0 deletions builds/nginx/mysite.local.conf
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
server {
listen 80;

server_name mysite.local;

root /data;

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

# при обращении к статическим файлам логи не нужны, равно как и обращение к fpm
# http://mysite.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 app:9000;
#fastcgi_pass unix:/var/run/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
1 change: 1 addition & 0 deletions code/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/vendor/
12 changes: 12 additions & 0 deletions code/composer.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"name": "asyrovatkin/hw12",
"type": "project",
"autoload": {
"psr-4": {
"Asyrovatkin\\Hw12\\": "src/"
}
},
"require": {
"ext-pdo": "*"
}
}
20 changes: 20 additions & 0 deletions code/composer.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

17 changes: 17 additions & 0 deletions code/src/App.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<?php

declare(strict_types=1);

namespace Asyrovatkin\Hw11;

use PDO;

class App
{
public function run()
{
$pdo = new PDO('mysql:host=localhost;dbname=hw11', 'root', '');
$productMapper = new ProductMapper($pdo);
$result = $productMapper->findAll();
}
}

Check failure on line 17 in code/src/App.php

View workflow job for this annotation

GitHub Actions / phpcs

Expected 1 newline at end of file; 0 found
33 changes: 33 additions & 0 deletions code/src/Product.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
<?php

declare(strict_types=1);

namespace Asyrovatkin\Hw11;

class Product
{
private int $id;
private string $name;
private int $price;
public function __construct(int $id, string $name, int $price)
{
$this->id = $id;
$this->name = $name;
$this->price = $price;
}

public function getId(): int
{
return $this->id;
}

public function getName(): string
{
return $this->name;
}

public function getPrice(): int
{
return $this->price;
}
}

Check failure on line 33 in code/src/Product.php

View workflow job for this annotation

GitHub Actions / phpcs

Expected 1 newline at end of file; 0 found
72 changes: 72 additions & 0 deletions code/src/ProductMapper.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?php

declare(strict_types=1);

namespace Asyrovatkin\Hw11;

use PDO;
use PDOStatement;

class ProductMapper
{
private PDO $pdo;
private PDOStatement $insertStatement;
private PDOStatement $updateStatement;
private PDOStatement $deleteStatement;
private PDOStatement $findByIdStatement;
private PDOStatement $findAllStatement;

public function __construct(PDO $pdo)
{
$this->pdo = $pdo;
$this->insertStatement = $pdo
->prepare('INSERT INTO products (name, price) VALUES (?, ?)');
$this->updateStatement = $pdo
->prepare('UPDATE products SET name = ?, price = ? WHERE id = ?');
$this->deleteStatement = $pdo->prepare('DELETE FROM products WHERE id = ?');
$this->findByIdStatement = $pdo->prepare('SELECT * FROM products WHERE id = ?');
$this->findAllStatement = $pdo->prepare('SELECT * FROM products');
}

public function insert(array $productArr): Product
Copy link

Choose a reason for hiding this comment

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

Сюда передается сущность, а не массив, мэппер не фабрика.

{
$this->insertStatement->execute([
$productArr['name'],
$productArr['price'],
]);

return new Product(
intval($this->pdo->lastInsertId()),
$productArr['name'],
$productArr['price'],
);
}

public function update(Product $product): void
{
$this->updateStatement->execute([
$product->getName(),
$product->getPrice(),
$product->getId(),
]);
}

public function delete(int $productId): void
{
$this->deleteStatement->execute([$productId]);
}

public function findById(int $productId): Product
{
$this->findByIdStatement->setFetchMode(PDO::FETCH_CLASS, Product::class);
$this->findByIdStatement->execute([$productId]);
return $this->findByIdStatement->fetch();
}

public function findAll(): array
{
$this->findAllStatement->setFetchMode(PDO::FETCH_CLASS, Product::class);
Copy link

Choose a reason for hiding this comment

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

Такая реализация ставит нейминг аттрибутов сущности в прямое соотвевтствие с полями таблицы. Хрупко. Теряется смысл дата мэппера. Необходимо вытаскивать сырые данные и через конструктор или рефлексию (в случае приватных полей) явно создавать сущности.

return $this->findAllStatement->fetchAll();
}

}

Check failure on line 72 in code/src/ProductMapper.php

View workflow job for this annotation

GitHub Actions / phpcs

Expected 1 newline at end of file; 0 found

Check failure on line 72 in code/src/ProductMapper.php

View workflow job for this annotation

GitHub Actions / phpcs

The closing brace for the class must go on the next line after the body
91 changes: 91 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
services:
nginx:
build:
context: ./builds/nginx
dockerfile: Dockerfile
image: myapp/nginx
container_name: nginx
ports:
- "80:80"
volumes:
- ./code:/data
networks:
- app-network

app:
build:
context: ./builds/fpm
dockerfile: Dockerfile
image: myapp/php
container_name: app
volumes:
- ./code:/data
networks:
- app-network

# elastic:
# image: elasticsearch:8.17.0
# container_name: elastic
# environment:
# ES_JAVA_OPTS: "-Xmx512m -Xms512m"
# ELASTIC_USERNAME: "elastic"
# ELASTIC_PASSWORD: "MyPw123"
# discovery.type: single-node
# xpack.security.http.ssl.enabled: false
#
# ports:
# - "9200:9200"
# - "9300:9300"
# networks:
# - app-network


# redis:
# image: redis:latest
# container_name: redis
# command: ["redis-server", "--appendonly", "yes"]
# ports:
# - "6379:6379"
# networks:
# - app-network
#
#
# mongo:
# image: mongo:latest
# container_name: mongodb_container
# environment:
# MONGO_INITDB_ROOT_USERNAME: root
# MONGO_INITDB_ROOT_PASSWORD: mypass1
# ports:
# - "27017:27017"
# volumes:
# - mongo_data:/data/db
# networks:
# - app-network

# memcached:
# image: memcached:latest
# container_name: memcached
# ports:
# - "11311:11211"
# networks:
# - app-network

# db:
# image: postgres
# container_name: db
# environment:
# - POSTGRES_USER=${DB_USER}
# - POSTGRES_PASSWORD=${DB_PASS}
# ports:
# - "5432:5432"
# volumes:
# - ./db:/var/lib/postgresql/data
# networks:
# - app-network
#volumes:
# mongo_data:

networks:
app-network:
driver: bridge
Loading