Орла
Области
Компаний
Пользователи
Галерея
Фиксированные новости
Орла
Отзывы о фирмах
Тарифы
Пользователи
Области
Банкоматы
Торговые точки
Доска объявлений
Курсы валют
Скидки
организации Орла
организации области
товары
сайты
сайты Орел
Данные
Разделы
Поиск
Поиск запросы
Статистика
Показы каталога организаций
Статистика клиенты
Пользователи
Сайты
Управление сайтом
Анкета
Аптеки
Афиша
Афиша новая
Баннеры
Бизнес >
Викторина
Голосование
Гость на сайте
Истории
Календарь событий
Каталоги >
Конкурс красоты
Конкурс аудио
Консультации
Меню
Новое на сайте
Новости >
Организации >
Программа ТВ
Публикации
Разделы сайта
Рассылка
Рестораны
Секрет фирмы >
Сервисы >
Ссылки
Тесты
Файловый менеджер
Форум
Фотогалерея
Обратная связь
Недвижимость
Новый год
Тексты
Пользователи
Юридический рейтинг
Отзывы на товары
Бан пользователей
Жалобы
Новые тесты
Коронавирус
Файловый менеджер
Имя файла
NotificationRepository.php
Содержимое
<?php namespace app\users\notifications; use App; use app\users\entity\User; /** * Ртот класс отвечает Р·Р° управление уведомлениями пользователей. * Class NotificationRepository * @package app\users\notifications */ class NotificationRepository { private $_pdo; public function __construct() { $this->_pdo = App::$pdo; } /** * Функция добавляет уведомление РІ репозиторий. * * @param Notification $notification * @return bool */ public function add(Notification $notification) { $sth = $this->_pdo->prepare(' INSERT INTO `user_notification` (created_at, user_from_id, user_to_id, message, url, url_text, viewed) VALUES(NOW(), :user_from_id, :user_to_id, :message, :url, :url_text, :viewed) '); $result = $sth->execute([ ':user_from_id' => $notification->getUserFrom()->getId(), ':user_to_id' => $notification->getUserTo()->getId(), ':message' => $notification->getMessage(), ':url' => $notification->getUrl(), ':url_text' => $notification->getUrlText(), ':viewed' => 0 ]); if ($result === true) { $notification->setId($this->_pdo->lastInsertId()); return true; } return false; } /** * Функция помечает уведомление как прочитанное. * @param Notification $notification * @return bool */ public function markAsViewed(Notification $notification) { $sth = $this->_pdo->prepare(' UPDATE `user_notification` SET viewed = 1 WHERE id = :id '); return $sth->execute([ ':id' => $notification->getId() ]); } /** * Помечает РІСЃРµ непрочитанные уведомления как прочитанные, для пользователя $userId * @param $userId * @return bool */ public function markAllAsViewed($userId) { if ($this->getTotalNotViewedItems($userId) > 0) { $sth = $this->_pdo->prepare(' UPDATE user_notification SET viewed = 1 WHERE viewed = 0 AND user_to_id = :user_to '); return $sth->execute([ ':user_to' => $userId ]); } return true; } /** * Функция находит РІСЃРµ уведомления (прочитанные Рё непрочитанные) для пользователя $userId * @param $userId * @param int $limit - количество последних уведомлений, которые РЅСѓР¶РЅРѕ вернуть * @return Notification[] */ public function findAll($userId, $limit = 9) { $sth = $this->_pdo->prepare(' SELECT user_notification.*, user_from.name as user_from_name, user_from.name_full as user_from_name_full, user_from.avatar as user_from_avatar, user_from.sex as user_from_sex, user_to.name as user_to_name, user_to.name_full as user_to_name_full, user_to.avatar user_to_avatar, user_to.sex as user_to_sex FROM user_notification INNER JOIN user user_from ON user_from.id = user_notification.user_from_id INNER JOIN user user_to ON user_to.id = user_notification.user_to_id WHERE user_notification.user_to_id = :user_to ORDER BY user_notification.id DESC LIMIT ' . (int) $limit . '; '); $sth->execute([ ':user_to' => $userId ]); $items = $sth->fetchAll(); $instances = []; foreach ($items as $item) { // РѕС‚ РєРѕРіРѕ пришло уведомление $userFrom = User::instance([ 'id' => $item['user_from_id'], 'name' => $item['user_from_name'], 'avatar' => $item['user_from_avatar'], 'name_full' => $item['user_from_name_full'], 'sex' => $item['user_from_sex'] ]); // РєРѕРјСѓ пришло уведомление $userTo = User::instance([ 'id' => $item['user_to_id'], 'name' => $item['user_to_name'], 'avatar' => $item['user_to_avatar'], 'name_full' => $item['user_to_name_full'], 'sex' => $item['user_to_sex'] ]); $notification = new Notification($userFrom, $userTo, $item['message'], $item['url'], $item['url_text']); $notification->setId((int) $item['id']); $notification->setCreatedAt($item['created_at']); $notification->setViewed($item['viewed']); $instances[] = $notification; } return $instances; } /** * Функция возвращает количество непрочитанных уведомлений. * * @param int $userId идентификатор пользователя, для которого возвращаем данные. * @return int */ public function getTotalNotViewedItems($userId) { $sth = $this->_pdo->prepare(' SELECT COUNT(*) as total FROM `user_notification` WHERE user_to_id = :user_to AND viewed = 0 '); $sth->execute([ ':user_to' => $userId ]); return (int) $sth->fetch()['total']; } }
/app/users/notifications/
Имя
Дата
Размер
..
2019-02-25
Notification.php
2019-01-24
4 кб.
NotificationRepository.php
2019-01-24
6 кб.
/app/users/notifications
Загрузить файлы
Файл 1
Файл 2
Файл 3