Орла
Области
Компаний
Пользователи
Галерея
Фиксированные новости
Орла
Отзывы о фирмах
Тарифы
Пользователи
Области
Банкоматы
Торговые точки
Доска объявлений
Курсы валют
Скидки
организации Орла
организации области
товары
сайты
сайты Орел
Данные
Разделы
Поиск
Поиск запросы
Статистика
Показы каталога организаций
Статистика клиенты
Пользователи
Сайты
Управление сайтом
Анкета
Аптеки
Афиша
Афиша новая
Баннеры
Бизнес >
Викторина
Голосование
Гость на сайте
Истории
Календарь событий
Каталоги >
Конкурс красоты
Конкурс аудио
Консультации
Меню
Новое на сайте
Новости >
Организации >
Программа ТВ
Публикации
Разделы сайта
Рассылка
Рестораны
Секрет фирмы >
Сервисы >
Ссылки
Тесты
Файловый менеджер
Форум
Фотогалерея
Обратная связь
Недвижимость
Новый год
Тексты
Пользователи
Юридический рейтинг
Отзывы на товары
Бан пользователей
Жалобы
Новые тесты
Коронавирус
Файловый менеджер
Имя файла
ActiveRecord.php
Содержимое
<?php namespace app\core\models; use app\core\Component; /** * Класс для работы с таблицами в базе данных * Class ActiveRecord * @package app\core\models */ abstract class ActiveRecord extends Component { /** * Связь один к однму */ const ATTRIBUTE_HAS_ONE = 0; /** * Связь один ко многим */ const ATTRIBUTE_HAS_MANY = 1; /** * В этой переменной хранятся поля из таблицы static::tableName(), * @var array */ private $_attributes = []; /** * Массив для связей между таблицами, используйте методы * hasOne(), hasMany() * @var array */ private $_relationAttributes = []; /** * Массив измененных аттрибутов, через метод __set() * @var array */ private $_modifiedAttributes = []; /** * SQL запрос * @var */ private $_sql; /** * Данные, которые будут передаваться в execute * при Insert или Update * @var array */ private $_values = []; /** * Функция возвращает возвращает значение из таблицы. * Пример использования: * ```php * $someValue = $model->somefield; * ``` * @param $name * @return mixed|null */ public function &__get($name) { if (array_key_exists($name, $this->_attributes) == false) { $this->_attributes[$name] = null; } if (is_scalar($this->_attributes[$name])) { $property = $this->_attributes[$name]; } else { $property = &$this->_attributes[$name]; } return $property; } /** * Функция устанавливает какое-либо значение, чтобы записать его в таблицу * с помощью $model->save(); * * @param $name * @param $value * @return bool */ public function __set($name, $value) { if (is_callable($value)) { $value = call_user_func($value); } $this->_attributes[$name] = $value; $this->_modifiedAttributes[] = $name; return true; } /** * Вы можете переопределить эту функцию, если хотите, * чтобы модель соеденялась с другой базой данных. * @return \PDO - фунция должна возвращать только \PDO */ public static function getDb() { return \App::$pdo; } /** * Функция выполняет поиск с учетом связей и прочего. * При связке с join у вас не будет работать сохранение. * @return QueryBuilder */ public static function find() { $queryBuilder = new QueryBuilder(static::className()); $queryBuilder->from(static::tableName()); $queryBuilder->setDb(static::getDb()); return $queryBuilder; } public function hasOne($targetClassName, array $condition) { $relation = new RelationAttribute(); $relation->setRelationType(RelationAttribute::RELATION_TYPE_HAS_ONE); $relation->select(['*']); $relation->setCondition($condition); $relation->setTargetClass($targetClassName); $this->_relationAttributes[] = &$relation; return $relation; } public function hasMany($targetClassName, array $condition) { $relation = new RelationAttribute(); $relation->setRelationType(RelationAttribute::RELATION_TYPE_HAS_MANY); $relation->select(['*']); $relation->setCondition($condition); $relation->setTargetClass($targetClassName); $this->_relationAttributes[] = &$relation; return $relation; } public function save() { if (isset($this->_attributes[static::primaryKey()])) { return $this->update(); } else { return $this->insert(); } } /** * Функция обновления данных в модели. Пример использования такой функции: * ```php * $user = User::findOne(1); * $user->name = "foobar"; * $user->work = function() { * return "work_name"; * } * $user->save() // можно вызвать явно $user->update(); * ``` * @return bool */ public function update() { if ($this->{static::primaryKey()} == null) { return false; } if (count($this->_modifiedAttributes) == 0) { return true; } $sqlFragmentArray = []; $keysValuesExecute = []; foreach ($this->_modifiedAttributes as $modifiedAttribute) { // аттрибут является Expression выражением. В этом случае не нужно его плейсхолдить if ($this->{$modifiedAttribute} instanceof Expression) { $sqlFragmentArray[$modifiedAttribute] = $modifiedAttribute .' = ' . $this->{$modifiedAttribute}->getValue(); } else { $sqlFragmentArray[$modifiedAttribute] = $modifiedAttribute .' = :' . $modifiedAttribute; $keysValuesExecute[':' . $modifiedAttribute] = $this->{$modifiedAttribute}; } } $sql = ' UPDATE `'.static::tableName().'` SET '.implode(',', $sqlFragmentArray).' WHERE '.static::primaryKey().' = ' . $this->{static::primaryKey()} . ';'; $this->_sql = $sql; $pdo = static::getDb(); $sth = $pdo->prepare($sql); if ($sth->execute($keysValuesExecute) == true) { $this->resetModifiedAttributes(); return true; } return false; } /** * Функция выполняет вставку новой записи в базу данных. * Пример использования функции: * ```php * $user = new User(); * $user->created_at = new Expression("NOW()"); * $user->name = "foobar"; * $user->save(); * ``` * @return bool */ public function insert() { $sqlPlaceHolder = ' INSERT INTO `{tableName}`({fields}) VALUES({values}); '; $fields = []; $executeParams = []; $values = []; foreach ($this->_attributes as $key => $attribute) { $fields[] = $key; if ($attribute instanceof Expression) { $executeParams[] = $attribute->getValue(); } else { $executeParams[] = ':' . $key; $values[':' . $key] = $attribute; } } $sqlPlaceHolder = str_replace('{tableName}', static::tableName(), $sqlPlaceHolder); $sqlPlaceHolder = str_replace('{fields}', implode(',', $fields), $sqlPlaceHolder); $sqlPlaceHolder = str_replace('{values}', implode(',', $executeParams), $sqlPlaceHolder); $this->_sql = $sqlPlaceHolder; $this->_values = $values; $pdo = static::getDb(); $sth = $pdo->prepare($sqlPlaceHolder); if ($sth->execute($values)) { $this->{static::primaryKey()} = $pdo->lastInsertId(); return true; } return false; } /** * Функция удаляет модель. * @return bool */ public function delete() { if (array_key_exists(static::primaryKey(), $this->_attributes) == false) { return true; } $pdo = static::getDb(); $sth = $pdo->prepare(' DELETE FROM `'.static::tableName().'` WHERE '.static::primaryKey().' = :key '); $result = $sth->execute([ static::primaryKey() => $this->_attributes[static::primaryKey()] ]); if ($result == true) { // очищаем primary key, чтобы нельзя было пересохранять данные unset($this->_attributes[static::primaryKey()]); return true; } return false; } public static function tableName() { return null; } public static function primaryKey() { return null; } /** * Функция убирает модифицированные аттрибуты, * таким образом при update() ничего не произойдет. */ public function resetModifiedAttributes() { $this->_modifiedAttributes = []; } /** * Функция делает выборку одой записи из таблицы * Пример простого запроса: * ```php * $user = User::findOne(1); * ``` * * Также можно делать условия выборки: * ```php * $user = User::findOne([ * 'id' => 100, * 'active' => 1 * ]); * ``` * * @param $condition * @return null|static */ public static function findOne($condition) { if (is_array($condition) == false) { $condition = [ static::primaryKey() => $condition ]; } $queryBuilder = new QueryBuilder(static::className()); $queryBuilder->from(static::tableName()); $queryBuilder->setDb(static::getDb()); $queryBuilder->where($condition); return $queryBuilder->one(); } /** * Функция делает выборку массива записей из таблицы * @param string|array $condition * @return array */ public static function findAll($condition) { if (is_array($condition) == false) { $condition = [ static::primaryKey() => $condition ]; } $queryBuilder = new QueryBuilder(static::className()); $queryBuilder->from(static::tableName()); $queryBuilder->setDb(static::getDb()); $queryBuilder->where($condition); return $queryBuilder->all(); } /** * Функция возвращает SQL запрос. * @return mixed */ public function getSql() { return $this->_sql; } public function getValues() { return $this->_values; } }
/app/core/models/
Имя
Дата
Размер
..
2019-02-12
validators
2026-05-25
ActiveRecord.php
2023-09-07
10 кб.
ActiveRecord.php~
2016-12-23
10 кб.
BaseModel.php
2016-12-22
167 байт
Command.php
2016-12-22
199 байт
Expression.php
2016-12-22
329 байт
Form.php
2016-12-22
6 кб.
Mail.php
2016-12-22
762 байт
MySQLCommand.php
2019-01-31
1 кб.
NoInjection.php
2019-01-30
987 байт
QueryBuilder.php
2020-03-10
20 кб.
RelationAttribute.php
2016-12-22
5 кб.
SqlModel.php
2016-11-24
98 байт
WhereConditionHelper.php
2019-01-30
813 байт
/app/core/models
Загрузить файлы
Файл 1
Файл 2
Файл 3