PHP code example of tobento / service-repository-storage
1. Go to this page and download the library: Download tobento/service-repository-storage library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
tobento / service-repository-storage example snippets
use Tobento\Service\Repository\RepositoryInterface;
use Tobento\Service\Repository\ReadRepositoryInterface;
use Tobento\Service\Repository\WriteRepositoryInterface;
use Tobento\Service\Repository\Storage\StorageRepository;
use Tobento\Service\Repository\Storage\StorageEntityFactoryInterface;
use Tobento\Service\Storage\InMemoryStorage;
use Tobento\Service\Storage\Tables\Tables;
class ProductRepository extends StorageRepository
{
//
}
$repository = new ProductRepository(
storage: new InMemoryStorage(
items: [],
tables: (new Tables())->add('products', ['id', 'sku', 'price'], 'id')
),
table: 'products', // specify which storage table should be used.
entityFactory: null, // null|StorageEntityFactoryInterface
);
var_dump($repository instanceof RepositoryInterface);
// bool(true)
var_dump($repository instanceof ReadRepositoryInterface);
// bool(true)
var_dump($repository instanceof WriteRepositoryInterface);
// bool(true)
use Tobento\Service\Repository\ReadRepositoryInterface;
use Tobento\Service\Repository\Storage\StorageReadRepository;
use Tobento\Service\Repository\Storage\StorageEntityFactoryInterface;
use Tobento\Service\Storage\InMemoryStorage;
use Tobento\Service\Storage\Tables\Tables;
class ProductReadRepository extends StorageReadRepository
{
// adding custom find methods
}
$repository = new ProductReadRepository(
storage: new InMemoryStorage(
items: [
'products' => [
1 => ['id' => 1, 'sku' => 'paper', 'price' => 1.2],
2 => ['id' => 2, 'sku' => 'pen', 'price' => 1.8],
3 => ['id' => 3, 'sku' => 'pencil', 'price' => 1.5],
],
],
tables: (new Tables())->add('products', ['id', 'sku', 'price'], 'id')
),
table: 'products',
entityFactory: null, // null|StorageEntityFactoryInterface
);
var_dump($repository instanceof ReadRepositoryInterface);
// bool(true)
use Tobento\Service\Repository\Storage\EntityFactory;
use Tobento\Service\Repository\Storage\StorageEntityFactoryInterface;
use Tobento\Service\Repository\EntityFactoryInterface;
use Tobento\Service\Storage\ItemInterface;
class ProductFactory extends EntityFactory
{
public function createEntityFromArray(array $attributes): Product
{
// Process the columns reading:
$attributes = $this->columns->processReading($attributes);
// Create entity:
return new Product(
id: $attributes['id'] ?? 0,
sku: $attributes['sku'] ?? '',
);
}
}
class Product
{
public function __construct(
public readonly int $id,
public readonly string $sku,
) {}
}
$productFactory = new ProductFactory();
$productFactory->setColumns([]); // will be set by the storage
var_dump($productFactory instanceof StorageEntityFactoryInterface);
// bool(true)
var_dump($productFactory instanceof EntityFactoryInterface);
// bool(true)
$product = $productFactory->createEntityFromArray([
'id' => 1,
'sku' => 'pen',
]);
var_dump($product);
// object(Product)#4 (2) { ["id"]=> int(1) ["sku"]=> string(3) "pen" }
use Tobento\Service\Repository\Storage\StorageRepository;
use Tobento\Service\Repository\Storage\Column;
use Tobento\Service\Storage\InMemoryStorage;
class ProductRepository extends StorageRepository
{
//
}
$repository = new ProductRepository(
storage: new InMemoryStorage(items: []),
table: 'products',
// specify the columns:
columns: [
Column\Id::new(),
Column\Text::new('sku'),
Column\Text::new('title')
->read(fn (string $value, array $attributes): string => ucfirst($value))
->write(fn (string $value, array $attributes, string $action): string => ucfirst($value)),
Column\Boolean::new('active'),
],
);
use Tobento\Service\Repository\Storage\StorageRepository;
use Tobento\Service\Repository\Storage\Column\ColumnsInterface;
use Tobento\Service\Repository\Storage\Column\ColumnInterface;
use Tobento\Service\Repository\Storage\Column;
use Tobento\Service\Storage\InMemoryStorage;
class ProductRepository extends StorageRepository
{
/**
* Returns the configured columns.
*
* @return iterable<ColumnInterface>|ColumnsInterface
*/
protected function configureColumns(): iterable|ColumnsInterface
{
return [
Column\Id::new(),
Column\Text::new('sku'),
Column\Text::new('title')
->read(fn (string $value, array $attributes): string => ucfirst($value))
->write(fn (string $value, array $attributes, string $action): string => ucfirst($value)),
Column\Boolean::new('active'),
];
}
}
$repository = new ProductRepository(
storage: new InMemoryStorage(items: []),
table: 'products',
);
use Tobento\Service\Repository\Storage\Column\Text;
$column = Text::new(name: 'name')
->write(fn (string $value, array $attributes, string $action): string => ucfirst($value));
// $action = the action name processed such as 'create' or 'update'
use Tobento\Service\Repository\Storage\Attribute\StringTranslations;
$repository->locale('en');
$repository->locales('en', 'de', 'fr');
$repository->localeFallbacks(['de' => 'en']);
$entity = $repository->findById(id: 2);
var_dump($entity->get('title') instanceof StringTranslations);
// bool(true)
// The title on the current locale set on the repository:
$title = (string)$entity->get('title');
// or:
$title = $entity->get('title')->get();
// specific locale:
$title = $entity->get('title')->get(locale: 'de');
// specific locale with default value
// if fallback locale value does not exist:
$title = $entity->get('title')->get(locale: 'fr', default: 'title');
// check if translation exists:
var_dump($entity->get('title')->has(locale: 'de'));
// bool(true)
// returns all translations:
var_dump($entity->get('title')->all();
// array(2) {["en"]=> string(5) "Title" ["de"]=> string(5) "Titel"}
use Tobento\Service\Repository\Storage\Attribute\ArrayTranslations;
$repository->locale('en');
$repository->locales('en', 'de', 'fr');
$repository->localeFallbacks(['de' => 'en']);
$entity = $repository->findById(id: 2);
var_dump($entity->get('meta') instanceof ArrayTranslations);
// bool(true)
// The meta on the current locale set on the repository:
$meta = $entity->get('meta')->get();
// array(1) {["color"]=> string(3) "red"}
// specific locale:
$meta = $entity->get('meta')->get(locale: 'de');
// array(1) {["color"]=> string(3) "rot"}
// specific locale with default value
// if fallback locale value does not exist:
$meta = $entity->get('meta')->get(locale: 'fr', default: ['color' => 'rot']);
// array(1) {["color"]=> string(3) "red"}
// check if translation exists:
var_dump($entity->get('title')->has(locale: 'de'));
// bool(true)
// returns all translations:
var_dump($entity->get('meta')->all();
// array(2) {["en"]=> array(1) {["color"]=> string(3) "red"} ["de"]=> array(1) {["color"]=> string(3) "rot"}}
// The meta color on the current locale set on the repository:
$color = $entity->get('meta')->get(key: 'color');
// string(3) "red"
// specific locale:
$color = $entity->get('meta')->get(locale: 'de', key: 'color');
// string(3) "rot"
// specific locale with default value
// if fallback locale value does not exist:
$color = $entity->get('meta')->get(locale: 'fr', key: 'color', default: ['color' => 'rot']);
// string(3) "red"
// check if translation exists:
var_dump($entity->get('title')->has(locale: 'de', key: 'color'));
// bool(true)
// current locale:
$repository->locale('en');
// only the defined locales are used:
$repository->locales('en', 'de', 'fr');
// fallbacks:
$repository->localeFallbacks(['de' => 'en']);
$entities = $repository->findAll(where: [
// query current locale set on the repository:
'title' => ['like' => 'pe%'],
// query specific locale using json syntax:
'title->de' => ['like' => 'pe%'],
// Array translations:
// query current locale set on the repository:
'options->color' => 'red', // same as: options->en->color
// query specific locale using json syntax:
'options->de->color' => 'red',
]);
use Tobento\Service\Repository\Storage\Migration\RepositoryAction;
use Tobento\Service\Repository\Storage\Migration\RepositoryDeleteAction;
use Tobento\Service\Migration\MigrationInterface;
use Tobento\Service\Migration\ActionsInterface;
use Tobento\Service\Migration\Action;
use Tobento\Service\Migration\Actions;
class UserMigration implements MigrationInterface
{
public function __construct(
protected UserRepository $userRepository,
) {}
/**
* Return a description of the migration.
*
* @return string
*/
public function description(): string
{
return 'Users migration';
}
/**
* Return the actions to be processed on install.
*
* @return ActionsInterface
*/
public function install(): ActionsInterface
{
// you might check if repository is supported for the action:
if (RepositoryAction::isSupportedRepository($this->userRepository)) {
// create action
}
return new Actions(
new RepositoryAction(
repository: $this->userRepository,
description: 'User migration',
// you might set items to be migrated
items: [
['email' => '[email protected]'],
],
// you may set if items should be created using a boolean:
createItems: true, // default
// or using a closure:
createItems: fn ($repo): bool => is_null($repo->findOne()),
),
// you might use the newOrNull method
// if the defined repository is of any type.
// If it is an unsupported repository
// a Action\NullAction::class is created.
RepositoryAction::newOrNull(
repository: $this->userRepository,
description: 'User migration',
// you might set items to be migrated
items: [
['email' => '[email protected]'],
],
createItems: true, // default
),
// you might use the newOrFail method
// if the defined repository is of any type.
// If it is an unsupported repository
// a Action\Fail::class is created.
RepositoryAction::newOrFail(
repository: $this->userRepository,
description: 'User migration',
// you might set items to be migrated
items: [
['email' => '[email protected]'],
],
createItems: true, // default
),
);
}
/**
* Return the actions to be processed on uninstall.
*
* @return ActionsInterface
*/
public function uninstall(): ActionsInterface
{
// you might check if repository is supported for the action:
if (RepositoryDeleteAction::isSupportedRepository($this->userRepository)) {
// create action
}
return new Actions(
new RepositoryDeleteAction(
repository: $this->userRepository,
description: 'User migration',
),
// you might use the newOrNull method
// if the defined repository is of any type.
// If it is an unsupported repository
// a Action\NullAction::class is created.
RepositoryDeleteAction::newOrNull(
repository: $this->userRepository,
description: 'User migration',
),
// you might use the newOrFail method
// if the defined repository is of any type.
// If it is an unsupported repository
// a Action\Fail::class is created.
RepositoryDeleteAction::newOrFail(
repository: $this->userRepository,
description: 'User migration',
),
);
}
}
array
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.