Php data storage system

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Простое хранилище данных в виде ключ-значение в JSON-файлах с разделяемой блокировкой на чтение и эксклюзивной блокировкой на запись.

License

andrey-tech/data-storage-php

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Читайте также:  Java enum and hibernate

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Простое хранилище данных в виде ключ-значение в JSON-файлах с разделяемой блокировкой на чтение и эксклюзивной блокировкой на запись.

  • PHP >= 7.0.
  • Трейт \App\Utils\JsonUtils , содержащий методы для работы c данными в формате JSON.
  • Произвольный автозагрузчик классов, реализующий стандарт PSR-4.
$ composer require andrey-tech/data-storage-php 

в секцию require файла composer.json.

Работа с хранилищами производится с помощью класса \App\DataStorage\FileStorage .
При возникновении ошибок выбрасывается исключение с объектом класса \App\DataStorage\FileStorageException .

Класс \App\DataStorage\FileStorage имеет следующие публичные методы:

  • __construct(string $storageName = ‘storage’, string $storageDir = ‘storage/’) Конструктор класса-хранилища.
    • $storageName — имя хранилища. Должно удовлетворять регулярному выражению ‘/^[\w\.-]+$/i ;
    • $storageDir — каталог, в котором будут располагаться JSON-файлы хранилища.
    • $set — ассоциативный массив ключей и значений: [ ‘key1’ => ‘value1’, ‘key2’ => ‘value2’. ] .
    • $keys — ключ или массив ключей.
    • $keys — ключ или массив ключей.
    • $set — ассоциативный массив ключей и значений: [ ‘key1’ => ‘value1’, ‘key2’ => ‘value2’. ] ;
    • $delete — массив удаляемых ключей.
    • $key — имя ключа.
    use \App\DataStorage\FileStorage; use \App\DataStorage\FileStorageException; use \App\AppException; try < $storage = new FileStorage('storage-1'); $storage->set([ 'manager_id' => 2369305, 'numbers' => [ 4, 8, 15, 16, 23, 42 ], 'error_time' => null, 'user_ids' => [ 'alex' => 23, 'bob' => 2 ], 'months' => [ '0' => [ 1, 4 ], '1' => [ 1, 2, 5 ] ] ]); $storage->set([ 'group_id' => 94824 ]); var_dump($storage->hasKey('numbers')); print_r($storage->get('numbers')); print_r($storage->get([ 'manager_id', 'user_ids' ])); $storage->delete('group_id'); $storage->update( $set = [ 'error_time' => 1596124230 ], $delete = [ 'manager_id' ] ); print_r($storage->load()); > catch (FileStorageException $e) < printf('Ошибка (%d): %s' . PHP_EOL, $e->getCode(), $e->getMessage()); > catch (AppException $e) < printf('Ошибка (%d): %s' . PHP_EOL, $e->getCode(), $e->getMessage()); >

    Источник

    Data storage in PHP

    Data storage in PHP | Learn PHP & MySQL | Temporary and permanent containers with few and many data. According to each one of our specific needs, we will have different alternatives to store data in places that we will access from the server, where the PHP interpreter will be able to read them by himself and he will use them for his task of manufacturing an HTML page

    Temporary and permanent containers with few and many data. According to each one of our specific needs, we will have different alternatives to store data in places that we will access from the server, where the PHP interpreter will be able to read them by himself and he will use them for his task of manufacturing an HTML page.

    Temporary and permanent containers with few and many data

    Previously, we told the PHP interpreter what contents to write within each print () or echo order. We also provide each of the data with which he worked and we dictate everything he wrote.

    But paradoxically, the utility of PHP lies in delivering different content to a Web browser, depending on how certain events are triggered by the programmer of the page (according to the password entered, the link clicked, a data that is validated, etc.)

    This behavior is called dynamic Web pages; that is to say: the browser, after requesting a URL, will receive as a response a Web page that was not written in its entirety by the designer or programmer with its editor program, but its code -all, or at least a part- will write it the PHP interpreter every time a user asks to see that page with their browser; therefore, the page will be built «live» on the server, a few moments before it is sent to the browser.

    This leads us to an obvious question: if it is not us (designers, programmers) who will dictate letter by letter to the PHP interpreter, where will you get these data? The answer is «from several possible places».

    According to each one of our specific needs, we will have different alternatives to store data in places that we will access from the server, where the PHP interpreter will be able to read them by himself and he will use them for his task of manufacturing an HTML page. Next we will mention some of those possible places -the main ones-, so that we can imagine the resources with which we will work:

    The data can be stored in a variable — or in a matrix (created by us, or one of the many matrices in which the PHP interpreter automatically stores information)-

    The user will be able to enter the data and, consciously or unconsciously, he will use his browser to send the variables to the server, either through a form or through the variables attached to a URL, with a special type of link. A sending of «signals» to the server that our PHP page will be waiting to decide what information to show.

    The data can also be obtained as a result of executing a function (of those that are included in the PHP language, or of the functions that we will create ourselves).

    A data can be stored in a cookie that the user’s browser will silently save.

    You can read a data in a session variable, which will allow us to identify a particular user at a given time.

    You can read the data written within a text file (txt, XML, etc.) existing on the server.

    You can read the data stored in a database (without doubt, the most powerful option to handle large amounts of data, such as product catalogs, forum messages, etc.).

    Variables (local, Text files, cookies, sessions forms, URLs), constants, functions.

    Источник

    Saved searches

    Use saved searches to filter your results more quickly

    You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

    A simple in-memory data storage for PHP

    License

    scheb/in-memory-data-storage

    This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

    Name already in use

    A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

    Sign In Required

    Please sign in to use Codespaces.

    Launching GitHub Desktop

    If nothing happens, download GitHub Desktop and try again.

    Launching GitHub Desktop

    If nothing happens, download GitHub Desktop and try again.

    Launching Xcode

    If nothing happens, download Xcode and try again.

    Launching Visual Studio Code

    Your codespace will open once ready.

    There was a problem preparing your codespace, please try again.

    Latest commit

    Git stats

    Files

    Failed to load latest commit information.

    README.md

    Scrutinizer Code Quality Code Coverage

    A fast in-memory data storage in plain PHP. It can be used as a test double for a database, in order to to decouple the test cases from the database and speeding them up.

    • CRUD operations
    • Convenience methods for data selection and manipulation
    • Named items
    composer require scheb/in-memory-data-storage

    You can find an executable example in the doc folder.

     use Scheb\InMemoryDataStorage\DataRepositoryBuilder; use Scheb\InMemoryDataStorage\DataStorage\ArrayDataStorage; use function \Scheb\InMemoryDataStorage\Repository\compare; $foo = 'I am foo'; $bar = 'I am bar'; $repositoryBuilder = new DataRepositoryBuilder(); $repository = $repositoryBuilder // ->setDataStorage(new ArrayDataStorage()) ->build(); // Simple CRUD $repository->addItem($foo); $repository->containsItem($foo); // returns true $repository->getAllItems(); // returns [$foo] $repository->removeItem($foo); // Named items $repository->setNamedItem('foo', $foo); $repository->namedItemExists('foo'); // returns true $repository->getNamedItem('foo'); // returns $foo $repository->replaceNamedItem('foo', $bar); $repository->getNamedItem('foo'); // returns $bar $repository->removeNamedItem('foo'); // Advanced get $repository->getAllItemsByCriteria(['property' => 'value']); // $repository->getOneItemByCriteria(. ); // The same, but only one item is retrieved // Advanced update $repository->updateAllItemsByCriteria( ['property' => 'value'], // Match criteria ['property' => 'newValue', 'otherProperty' => 42] // Property updates ); // $repository->updateOneByCriteria(. ); // The same, but only one item is updated // Advanced remove $repository->removeAllItemsByCriteria(['property' => 'value']); // $repository->removeOneItemByCriteria(. ); // The same, but only one item is removed // Comparision functions in matching criteria $repository->getAllItemsByCriteria(['property' => compare()->notNull()]); $repository->getAllItemsByCriteria(['property' => compare()->lessThan(3)]); $repository->getAllItemsByCriteria(['property' => compare()->between(1, 3)]); $repository->getAllItemsByCriteria(['property' => compare()->isInArray([1, 2, 3])]); $repository->getAllItemsByCriteria(['property' => compare()->arrayContains('arrayElement')]); $repository->getAllItemsByCriteria(['property' => compare()->dateGreaterThan(new \DateTime('2018-01-01'))]); // . and many more, see Scheb\InMemoryDataStorage\Comparison

    Single-item (read, update, remove) operations will handle gracefully, when there is no matching item in the data store. Reads will return null , update/remove won’t change anything. If you want such cases to raise an exception instead, you can configure that behavior with the builder for each type of operation.

    $repository = $repositoryBuilder ->strictGet() ->strictUpdate() ->strictRemove() ->build();

    The library comes with a simple array-based storage, but you exchange the data storage engine with whatever you like, by implementing Scheb\InMemoryDataStorage\DataStorage\DataStorageInterface . Then, pass an instance to the builder:

    $repository = $repositoryBuilder ->setDataStorage(new MyCustomDataStorage()) ->build();

    Values are checked for equality with PHP’s === operation. If you want it to use the less-strict == operator, you can change the behavior with the builder.

    $repository = $repositoryBuilder ->useStrictTypeComparison(false) ->build();

    The library integrates scheb/comparator to check values for equality. If you need custom comparison rules, implement Scheb\Comparator\ValueComparisonStrategyInterface and pass your comparision strategy to the builder.

    $repository = $repositoryBuilder ->addComparisonStrategy(new MyCustomValueComparisonStrategy()) ->build();

    You can add as many comparision strategies as you need. They’ll be checked in the order they’re added and will take preference over the default comparision strategy.

    If you want to implement the comparision logic completely on your own, implement Scheb\InMemoryDataStorage\Matching\ValueMatcherInterface and pass an instance to the builder:

    $repository = $repositoryBuilder ->setValueMatcher(new MyCustomValueMatcher()) ->build();

    Properties are read and written with the following access strategies:

    If none of these works on a value object, it’s either using null (in case of read) or fails with an exception (in case of write).

    If you want to implement the property access logic completely on your own, implement Scheb\PropertyAccess\PropertyAccessInterface and pass an instance to the builder:

    $repository = $repositoryBuilder ->setPropertyAccess(new MyCustomPropertyAccess()) ->build();

    You’re welcome to contribute to this library by creating a pull requests or feature request in the issues section. For pull requests, please follow these guidelines:

    • Symfony code style
    • PHP7.1 type hints for everything (including: return types, void , nullable types)
    • Please add/update test cases
    • Test methods should be named [method]_[scenario]_[expected result]

    To run the test suite install the dependencies with composer install and then execute bin/phpunit .

    This bundle is available under the MIT license.

    Источник

Оцените статью