mnemesong/orm-core

This package is abandoned and no longer maintained. No replacement package was suggested.

Orm core. Contains storages, commands and queries base logic and interfaces.

0.9 2022-09-10 13:52 UTC

This package is not auto-updated.

Last update: 2023-03-29 06:37:41 UTC


README

Latest Stable Version PHPUnit PHPStan-lvl9 PHP Version Require License

  • The documentation is written in two languages: Russian and English.
  • Документация написана на двух языках: русском и английском.

General description / Общее описание

ENG:

The package provides an implementation of the basic object model for working with storages of various types:

  • Class for creating and loading files: RecordsQueue and ScalarsQueue.
  • Class for creating and configuring commands: DeleteCommand, SaveCommand, UpdateCommand.
  • Interfaces and traits: AbleToRecording, LimitExecutable, AbleToSort have special logic for classes and commands, as well as helper methods for testing their receivers.
  • Highly specialized interfaces for storage activities: RecordsDeleteModelInterface, RecordsSaveModelInterface, RecordsSearchModelInterface, RecordsUpdateModelInterface, ScalarsSearchModelInterface.
  • Interface for storage: StorageInterface is a way to create all types of files and commands.

RUS:

Пакет предоставляет реализации базовую необходимую объектную модель для работы с хранилищами различных типов:

  • Классы для создания и настройки запросов: RecordsQueue и ScalarsQueue.
  • Классы для создания и настройки комманд: DeleteCommand, SaveCommand, UpdateCommand.
  • Интерфейсы и трейты: AbleToRecording, LimitExecutable, AbleToSort содержащие специфичную логику для классов и комманд, а так-же вспомогательные методы для тестирования их приемников.
  • Узко-специализированные интерфейсы для активностей хранилищ: RecordsDeleteModelInterface, RecordsSaveModelInterface, RecordsSearchModelInterface, RecordsUpdateModelInterface, ScalarsSearchModelInterface.
  • Интерфейс для хранилища: StorageInterface - способный порождать все указанные выше типы запросов и команд.

Requirements / Требования

  • PHP >= 7.4
  • Composer >=2.0

Installation / Установка

composer require "mnemesong/orm-core"

Table manager / Менеджер таблицы

ENG

A table manager is an object that allows you to interact with a table from any storage. The Table Manager provides two ways to interact with a table.

  • Queries - Allows you to get records and statistical information in scalar values from a table.
  • Commands - Responsible for actions that change the state of the table: adding, deleting and updating records.

In this package, the TableManager is only an interface. TableManager implementations for each concrete type the storages are in separate packages.

RUS

Менеджер таблицы - это объект, который позволяет взаимодействовать с таблицей из любого хранилища. Менеджер таблицы предоставляет два способа для взаимодействия с таблицей.

  • Запросы (Queries) - Позволяют получать из таблицы записи и статистистическую информацию в скалярных величинах.
  • Комманды (Commands) - Отвечают за действия изменяющие состояние таблицы: добавление, удаление и обновление записей.

В данном пакете TableManager представлен только интерфейсом. Реализации TableManager для каждого конкретного типа хранилища находятся в отдельных пакетах.

Queries / Запросы

ENG

This package provides two types of requests:

1. RecordsQuery

Allows you to retrieve records from a table as objects of the Structure class (See mnemesong/structure package).

Methods
  • sortedBy(string[] $fields): self, withoutSorting(): self - Lets get RecordQuery with specified sort fields and their priority.
  • where(SpecificationInterface $spec): self, andWhere(SpecificationInterface $spec): self, orWhere(SpecificationInterface $spec): self- Allows you to get a RecordQuery with a specification search.
  • withOnlyFields(string[] $fields): self, withAllFields(): self - Allows you to get RecordQuery indicating which fields to look for when searching.
  • withLimit(int $limit): self, withoutLimit(int $limit): self - Allows you to get RecordQuery specifying the record search limit. Useful when you need to get only the first, or several first entries. Use sorting to operate the criteria for selecting the first records.
  • find(): StructureCollection - Performs a search and returns the found results as an object StructureCollection.
Example
$checkAuthRecord = $someTable->selectRecordsQuery()
->andWhere(Sp::ex('s=', 'login', $inputLogin))
->andWhere(Sp::ex('s=', 'passwordHash', HashTool::hash($inputPass)))
->withLimit(1)
->find()
->getFirstAsserted()

2. ScalarsQuery

Allows you to get scalar data sets for records that meet the specified specification as a Structure object (See package mnemesong/structure).

Methods
  • where(SpecificationInterface $spec): self, andWhere(SpecificationInterface $spec): self, orWhere(SpecificationInterface $spec): self- Allows you to get a ScalarQuery with a specification search.
  • withAddScalar(ScalarSpecification $spec): self - Allows you to get a ScalarQuery with a query another scalar lookup value.
  • withScalarsFilteredBy(callable $filterFunc): self - Allows you to get a ScalarQuery with a new a list of requests for rock values obtained using the filtering function.
  • find(): Structure - Performs a search and aggregation and returns the found results as an object structure. To configure the keys under which the results will be stored, use the method ScalarSpecification->withName(string $name). Then in from the resulting Structure object the specified scalar value can be obtained using the Structure->get(string $name): scalar method
Example
$numOfPotentialCustomers = $someTable
->getScalarsQuery()
->withAddScalar(Scalar::count()->as('customersCount'))
->andWhere(Sp::ex('n>', 'clicksOnBuyButton', 0))
->find()
->get('customersCount')

RUS

Данный пакет предоставляет два типа запросов:

1. RecordsQuery

Позволяет получать из таблицы записи в виде объектов класса Structure (См. пакет mnemesong/structure).

Методы
  • sortedBy(string[] $fields): self, withoutSorting(): self - Позволяют получить RecordQuery с указанными полями для сортировки и их приоритетом.
  • where(SpecificationInterface $spec): self, andWhere(SpecificationInterface $spec): self, orWhere(SpecificationInterface $spec): self- Позволяет получить RecordQuery со спецификацией поиска.
  • withOnlyFields(string[] $fields): self, withAllFields(): self - Позволяет получить RecordQuery с указанием какие поля искать при поиске.
  • withLimit(int $limit): self, withoutLimit(int $limit): self - Позволяет получить RecordQuery с указанием лимита поиска записей. Полезно когда надо получить только первую, или несколько первых записей. Для опертирования признаков отбора первых записей используйте сортировку.
  • find(): StructureCollection - Выполнгяет поиск и выдает найденные результаты в виде объекта StructureCollection.
Пример
$checkAuthRecord = $someTable
->selectRecordsQuery()
->andWhere(Sp::ex('s=', 'login', $inputLogin))
->andWhere(Sp::ex('s=', 'passwordHash', HashTool::hash($inputPass)))
->withLimit(1)
->find()
->getFirstAsserted()

2. ScalarsQuery

Позволяет получать наборы скалярных данных по записям отвечающим указанной спецификации в виде объекта Structure (См. пакет mnemesong/structure).

Методы
  • where(SpecificationInterface $spec): self, andWhere(SpecificationInterface $spec): self, orWhere(SpecificationInterface $spec): self- Позволяет получить ScalarQuery со спецификацией поиска.
  • withAddScalar(ScalarSpecification $spec): self - Позволяет получить ScalarQuery с запросом еще одного скалярного значения поиска.
  • withScalarsFilteredBy(callable $filterFunc): self - Позволяет получить ScalarQuery с новым списком запросо на скаляные значения, полученным с помощью функции фильтрации.
  • find(): Structure - Выполняет поиск и аггрегацию и выдает найденные результаты в виде объекта Structure. Для настройки ключей под которыми будут храниться полученные результаты, используйте метод ScalarSpecification->withName(string $name). Тогда в из полученного Structure объекта указанную скалярную величину можно будет получить методом Structure->get(string $name): scalar
Пример
$numOfPotentialCustomers = $someTable
->getScalarsQuery()
->withAddScalar(Scalar::count()->as('customersCount'))
->andWhere(Sp::ex('n>', 'clicksOnBuyButton', 0))
->find()
->get('customersCount')

Commands / Комманды

RUS

Данный пакет предоставляет три типа комманд:

1. SaveCommand

Позволяет сохранить запись в хранилище.

License / Лицензия

- MIT

Contacts / Контакты

- Anatoly Starodubtsev "Pantagruel74" - tostar74@mail.ru