Download the PHP package tobento/service-read-write without Composer

On this page you can find all versions of the php package tobento/service-read-write. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package service-read-write

Read and Write Service

The Read and Write Service provides a unified way to consume and produce structured data across different formats and sources.
It abstracts common operations such as reading rows from streams or iterables, inspecting column metadata, and writing data back to files or streams in formats like CSV, JSON, or NDJSON.

Key Capabilities

Why Use It?

Table of Contents

Getting started

Add the latest version of the read/write project running this command.

Requirements

Documentation

Workflow

Readers Comparison

Reader Streaming Supports Preview Detects Columns Nested Structures Skips Invalid Rows Typical Use Case
CSV Stream Reader Yes Yes Yes No Yes Importing tabular CSV files of any size
Iterable Reader Yes Yes Yes (from first row) Yes (if iterable contains arrays) Yes Reading from arrays, generators, API responses
JSON Stream Reader Yes Yes Yes Yes Yes (SkipRow) Large JSON arrays, API exports, structured data
NDJSON Stream Reader Yes Yes Yes Yes (per line) Yes (SkipRow) Log streams, event streams, line-based JSON
Repository Reader No Yes Yes (from first entity) Yes (entity to array) Yes (SkipRow) Domain repositories, entity-based data sources
Storage Reader No Yes Yes Yes (item to array) Yes (SkipRow) Storage backends (in-memory, database, abstracted storage)

Notes

Readers

CSV Stream Reader

The CsvStream reader allows you to consume CSV data from any source that implements the PSR-7 . It supports reading rows sequentially, applying offsets and limits.

Features

Example

Notes

Iterable Reader

The IterableReader wraps any PHP iterable (array, generator, Traversable) into a ReaderInterface.
It is useful for testing, working with in-memory datasets, or adapting existing collections to the reader API.

Features

Example

Notes

JSON Stream Reader

The JsonStream reader consumes JSON arrays from any source that implements the PSR-7 StreamInterface.
Each element in the array is parsed into a RowInterface, allowing sequential access with offset and limit support.

Requirements

To use the JsonStream reader you must install the JsonMachine library, which provides efficient streaming of large JSON arrays:

Features

Example

Notes

NDJSON Stream Reader

The NdJsonStream reader consumes NDJSON (newline-delimited JSON) from any source that implements the PSR-7 StreamInterface.
Each line is parsed into a RowInterface, allowing sequential access with offset and limit support.

Features

Example

Notes

Repository Reader

The RepositoryReader reads entities from any repository that implements the ReadRepositoryInterface.
It applies optional where and orderBy constraints, converts each entity into a RowInterface, and supports sequential reading with offset and limit.

Requirements

Install the tobento/service-repository package, which provides the ReadRepositoryInterface used by this reader:

Features

Example

Storage Reader

The StorageReader reads rows from any storage backend that implements the StorageInterface.
It applies an optional query callable, converts each storage item into a RowInterface, and supports sequential reading with offset and limit.

Requirements

Install the tobento/service-storage package, which provides the StorageInterface used by this reader:

Features

Example

Writers Comparison

Writer Streaming Supports Headers Supports Attributes Nested Structures Append Mode Typical Use Case
CSV Resource Writer Yes Yes No No Yes Exporting tabular data, spreadsheets, reports
HTML Resource Writer No Template-based Yes (via template) Yes No (Finalize only) HTML reports, tables, invoices, formatted exports
JSON Resource Writer Yes N/A N/A Yes Yes APIs, structured exports, debugging
NDJSON Resource Writer Yes N/A N/A Yes (per line) Yes Log streams, large datasets, incremental processing
XML Resource Writer Yes N/A Yes (@attr) Yes No (Finalize only) Feeds (RSS, Atom), Google Shopping, catalogs, sitemaps
PDF Resource Writer No Template-based Yes (via template) Yes No (Finalize only) PDF reports, tables, invoices, formatted exports
Null Writer Yes No No No N/A Discarding output, testing pipelines
Repository Writer No No No No N/A Writing rows into repositories or collections
Storage Writer No No No No N/A Writing rows into storage services (e.g., key-value stores)

Notes

Writers

CSV Resource Writer

The CsvResource writer exports rows into a CSV file or stream using a ResourceInterface.
It supports writing headers, handling BOM, and controlling write modes (overwrite or append).

Features

Example

Notes

HTML Resource Writer

The HtmlResource writer exports rows into an HTML document using a template-based rendering system powered by tobento/service-view. It collects all written rows, merges them with optional template data, and renders an HTML view using any supported template engine (PHP, Twig, Plates, etc.).

Requirements

Install the tobento/service-view package, which provides the view rendering interfaces and utilities used by this writer:

Features

Example

Template Example

A HTML template is a regular view file that receives the merged $templateData and the collected $rows.
You may include CSS assets, partials, and any layout structure you need.

JSON Resource Writer

The JsonResource writer exports rows into a JSON file or stream using a ResourceInterface.
It writes rows as objects inside a top-level JSON array, supporting overwrite, append, and finalize modes.

Features

Example

Notes

NDJSON Resource Writer

The NdJsonResource writer exports rows into an NDJSON file or stream using a ResourceInterface.
It writes each row as a standalone JSON object on its own line, making it ideal for log‑style or streaming data.

Features

Example

Notes

Null Writer

The NullWriter is a writer implementation that accepts rows but does nothing with them. It is useful for:

The writer fully participates in the processing lifecycle (start, write, finish) but performs no side effects.

Example Use Cases

Example

PDF Resource Writer

The PdfResource writer exports rows into a PDF document using a template-based rendering system.
It collects all written rows, merges them with optional template data, and generates a PDF using a PdfGeneratorInterface.

Requirements

Install the tobento/service-pdf package, which provides the PDF generation interfaces and utilities used by this writer:

Features

Example

Template Example

A PDF template is a regular view file that receives the merged $templateData and the collected $rows.
You may include CSS assets, partials, and any layout structure you need.

Repository Writer

The RepositoryWriter writes rows into a WriteRepositoryInterface.
It supports automatic create/update operations or custom writer callbacks for flexible handling.

Requirements

Install the tobento/service-repository package, which provides the WriteRepositoryInterface used by this writer:

Features

Example

Custom Writer Example

Notes

Storage Writer

The StorageWriter writes rows into a StorageInterface.
It supports automatic create/update operations or custom writer callbacks for flexible handling.

Requirements

Install the tobento/service-storage package, which provides the StorageInterface used by this writer:

Features

Example

Custom Writer Example

XML Resource Writer

The XmlResource writer streams rows into an XML document using a ResourceInterface.
It supports configurable root elements, row elements, optional wrapper elements, attributes, nested structures, and safe XML escaping.

Features

Example

Atom Feed Example

Google Shopping Product Feed Example

Notes

Writer Resources

Writer Resources define where and how data is physically written when using a writer (CSV, JSON, NDJSON, etc.).
They act as the destination layer, abstracting away the details of file handling, memory buffering, or storage backends.

Why They Are Used

Examples of Resources

By combining a writer (format) with a resource (destination), you can easily control both how data is structured and where it is stored.

File Storage Resource

The FileStorage resource provides a bridge between writers and a storage backend implementing StorageInterface.
It buffers written data into a temporary stream and commits the contents to the configured storage when closed.

Requirements

Install the tobento/service-file-storage package, which provides the StorageInterface used by the FileStorage resource:

Features

Example

Notes

In Memory Resource

The InMemory resource provides a simple, non-persistent buffer for writers.
It stores all written data in memory, making it useful for testing, debugging, or scenarios where you don't want to write to disk or external storage.

Features

Example

Notes

Local File Resource

The LocalFile resource provides direct file access for writers.
It opens a file on the local filesystem, writes data to it, and manages the file handle lifecycle.

Features

Example

Notes

Modifiers

Modifiers allow you to transform, filter, or reshape rows as they move through the processing pipeline.
They operate between the reader and writer, giving you full control over how data is normalized, renamed, enriched, or reduced before it is written.

Modifiers are applied by processors, not by writers directly.
This keeps the system flexible and composable: you can chain multiple modifiers, reorder them, or reuse them across different read/write workflows.

Why Modifiers Are Useful

Use modifiers whenever you need to adapt data between reading and writing without changing your reader or writer implementations.

Apply Modifiers If Modifier

The ApplyModifiersIf modifier applies one or more modifiers only when a condition is met.
If the condition does not match, the wrapped modifiers are skipped and the row continues unchanged.

Features

Supported Conditions

1. Boolean Condition

2. String Condition

Apply only if the field exists and is not empty:

3. Array Condition

4. Callable Condition

Apply only for Swiss addresses:

Callable Modifier

The CallableModifier allows you to apply custom transformation logic to a row using any user-defined callable.
It provides maximum flexibility when built-in modifiers are not sufficient or when you want to encapsulate small, one-off transformations.

Features

Example

Column Map Modifier

The ColumnMap modifier transforms a row's attributes by remapping column names according to a user-defined mapping.
It is useful when the input and output schemas differ, or when you need to rename columns during read/write operations.

Features

Example

Notes

Combine Fields Modifier

The CombineFields modifier merges multiple attributes into a single target attribute.
It is useful for creating derived fields such as full_name from first_name and last_name.

Features

Example

Compute Modifier

The Compute modifier computes a field value using a user-defined callback. It is useful for creating derived fields, performing custom calculations, or generating values based on the entire row.

Features

Example

Default Value Modifier

The DefaultValue modifier ensures that missing or empty attributes are populated with predefined default values.
It is useful for filling in required fields during imports or normalizing incomplete input data.

Features

Example

Encrypt Modifier

The Encrypt modifier encrypts one or more fields using an application-defined encryption service based on
tobento/service-encryption.
It is useful for protecting sensitive data such as API keys, tokens, personal information, or any value that must be stored securely but still be decryptable later.

Requirements

To use the Encrypt modifier, you must install the
tobento/service-encryption package:

Features

Example

Notes

Filter Fields Modifier

The FilterFields modifier keeps only the specified fields and removes all others.
It is useful for privacy filtering, export shaping, or limiting output to a defined subset of fields.

Features

Example

Format Modifier

The Format modifier applies a user-defined formatting callback to a specific field. It is useful for normalizing values, converting types, trimming, cleaning, or applying any custom transformation to a single attribute.

Features

Example

Hash Modifier

The Hash modifier hashes one or more fields using a user-defined hashing callable.
It is useful for securely transforming sensitive values such as passwords, tokens,
API keys, or other secrets before they are stored or processed further.

Features

Example

Notes

Lookup Modifier

The LookupModifier maps a source field's value to another value using either a lookup array or a callable resolver.
It is useful for normalizing human-readable labels into IDs or codes (e.g. category name to category ID).

Features

Example (array lookup)

Example (callable lookup)

Mask Modifier

The Mask modifier masks one or more fields to hide sensitive information while preserving enough structure for display or logging.
It is useful for partially hiding emails, phone numbers, tokens, names, or any other sensitive value that should not appear in plain text.

Features

Example

Example: Custom masking

Notes

Redact Modifier

The Redact modifier removes sensitive information by replacing one or more fields with a fixed value.
It is useful for eliminating confidential data such as passwords, tokens, personal identifiers, or any value that must not appear in logs, exports, or downstream systems.

Features

Example

Example: Custom replacement

Notes

Remove Fields Modifier

The RemoveFields modifier removes the specified fields from a row.
It is useful for stripping sensitive data, removing debug or internal fields, or cleaning up unwanted input before further processing.

Features

Example

Replace Modifier

The Replace modifier replaces values or substrings in one or more fields.
It is useful for cleaning up imported data, normalizing inconsistent values, or converting placeholder values such as "N/A" or "none" into meaningful representations.

Features

Example

Example: Substring replacement

Example: Replace null values

Notes

Sanitize Modifier

The Sanitize modifier cleans row attributes using the tobento/service-sanitizer package.
It is useful for removing unwanted HTML, normalizing input, and ensuring safe, consistent values before validation or storage.

Requirements

To use the Sanitize modifier, you must install the tobento/service-sanitizer package:

Features

Example

Skip If Modifier

The SkipIf modifier skips a row when a condition is met and returns a SkipRow
implementing SkippableInterface.
It is useful for filtering out invalid, incomplete, or unwanted rows before they
reach later modifiers or writers.

Features

Supported Conditions

1. Boolean Condition

2. String Condition

Skip if the field is missing or empty:

3. Array Condition

4. Callable Condition

Skip if age is under 18:

Split Modifier

The Split modifier splits a single string field into multiple fields using a separator.
It is useful for breaking composite values into structured parts
(e.g. "John Doe" into first_name, last_name).

Features

Example

Notes

Trim Modifier

The Trim modifier cleans a row's attributes by removing leading and trailing whitespace (or other specified characters) from defined fields.
It is useful for normalizing text input, ensuring consistent values before validation, transformation, or storage.

Features

Example

Unique Modifier

The Unique modifier ensures that one or more fields contain unique values across the import.
It is useful for preventing duplicate emails, SKUs, usernames, or other identifiers that must not repeat.

Features

Example

Example: Database lookup

Notes

Validation Modifier

The Validation modifier validates row attributes using the
tobento/service-validation package.
It is useful for enforcing required fields, checking formats, and ensuring data integrity before further processing or storage.

Requirements

To use the Validation modifier, you must install the
tobento/service-validation package:

Features

Example

Processors

Processors form the transformation layer between reading and writing.
They take each row produced by a reader and pass it through a configurable pipeline of modifiers, filters, and other processing steps before the row reaches the writer.

A processor does not change how data is read or written - instead, it controls how data flows and is transformed between the two. This makes processors the central place for applying business logic, normalization, validation, or schema adjustments.

Why Processors Are Useful

Use processors whenever you need to apply transformations, filtering, or mapping logic to rows before they are written.

Default Processor

The default Processor coordinates the full read → modify → write workflow using a reader, writer, and a set of modifiers.
It handles row iteration, modifier execution, writer mode selection, error tracking, and optional result handling.

Key Responsibilities

Example

Processing Flow

  1. Determine writer mode
    If the writer implements ModeAwareInterface, the processor sets the mode based on the current offset and reader state:

    • Overwrite when starting at offset 0
    • Append when continuing and the reader is not finished
    • Finalize when processing the last chunk
  2. Start the writer
    The processor calls writer->start() before any rows are processed.

  3. Iterate through rows
    For each row returned by reader->read(offset, limit):

    • Skip immediately if the row implements SkippableInterface
    • Apply all modifiers via ModifiersInterface
    • Skip again if modifiers mark the row as skippable
    • Write the row using writer->write()
  4. Error handling

    • ModifyException and WriteException increment the failed row count
    • Any other exception is wrapped in a ProcessException
  5. Finish the writer
    After all rows are processed, the processor calls writer->finish().

  6. Build the result
    A Result object is created containing:

    • Number of successful, failed, and skipped rows
    • The reader, writer, and modifiers used
    • Start and finish timestamps
  7. Notify result handler
    If a ResultHandlerInterface is provided, it receives:
    • Row success events
    • Row skip events
    • Row failure events
    • The final result event

Time Budget Processor

The TimeBudgetProcessor works like the default processor but adds a strict execution time limit.
It processes rows only as long as the predicted time for the next row stays within the configured time budget.
This makes it ideal for cron jobs, queue workers, or long-running tasks where execution time must be controlled.

The processor estimates future row duration using a moving average of the last N processed rows.

Key Responsibilities

Example

Processing Flow

  1. Determine writer mode
    If the writer implements ModeAwareInterface, the processor sets the mode based on the current offset and reader state:

    • Overwrite when starting at offset 0
    • Append when continuing and the reader is not finished
    • Finalize when processing the last chunk
  2. Start the writer
    The processor calls writer->start() before any rows are processed.

  3. Initialize time-budget tracking

    • Convert the configured time budget from seconds to nanoseconds
    • Record the start time using hrtime(true)
    • Prepare a moving window of recent row durations (default: last 50 rows)
  4. Predict next row cost
    Before processing each row:

    • Compute the moving average of recent row processing times
    • Calculate elapsed time and remaining budget
    • Stop early if the predicted next row would exceed the remaining time budget
  5. Iterate through rows
    For each row returned by reader->read(offset, limit):

    • Skip immediately if the row implements SkippableInterface
    • Apply all modifiers via ModifiersInterface
    • Skip again if modifiers mark the row as skippable
    • Write the row using writer->write()
    • Measure the row's processing time and update the moving average window
  6. Error handling

    • ModifyException and WriteException increment the failed row count
    • Any other exception is wrapped in a ProcessException
  7. Finish the writer
    After processing stops (either naturally or due to time budget), the processor calls writer->finish().

  8. Build the result
    A Result object is created containing:

    • Number of successful, failed, and skipped rows
    • The reader, writer, and modifiers used
    • Start and finish timestamps
  9. Notify result handler
    If a ResultHandlerInterface is provided, it receives:
    • Row success events
    • Row skip events
    • Row failure events
    • The final result event

Results

The Results system provides structured feedback about what happened during processing.
Every processor returns a ResultInterface describing how many rows were processed successfully, how many failed, and how many were skipped. This makes it easy to track progress, display summaries, log outcomes, or resume processing later.

Results are split into two parts:

Together, these components give you full visibility into the processing workflow and allow you to integrate reporting, logging, or UI updates in a clean and consistent way.

Result Handler

A ResultHandlerInterface allows you to react to processing events as they occur.
While the Result object provides a final summary after processing finishes, a result handler gives you real-time hooks for row-level and batch-level events.

Result handlers are especially useful in queue-driven or event-driven architectures, where you may want to:

Processors call the handler methods synchronously and only if a handler is provided.
Handlers never modify rows or influence the processing flow - they are purely observational.

Event Methods

Example: PSR‑3 Logging Result Handler

Result Object

The default Result implementation provides a complete summary of a processing run.
It is returned by every processor and contains counters, timestamps, references to the components involved, and optional metadata.
This makes it easy to display summaries, log outcomes, or resume processing based on the final state.

The Result object is immutable: all values are set at construction time and exposed through read-only accessors.

Features

Example

Available Data

Row Counters

Components

These references allow you to inspect configuration, offsets, or writer state after processing.

Metadata

Timing Information

Timeline Summary

Events

The Import/Export workflow provides simple event value objects that describe different stages of processing:

These events are not dispatched automatically.
Your application is responsible for dispatching them, which gives you full control over how and when they are used (e.g., for logging, queueing, or UI updates).

Each event contains a ResultInterface so listeners can inspect progress or statistics.

Example: Dispatching Events While Running a Processor

Just make sure you pass an event dispatcher to your runner!

Learn More

Using Processors with Registries and Queues

This package focuses on reading, writing, modifying, and processing data.
It does not define how readers, writers, or modifiers are registered or configured.
Different applications solve this differently (CRUD fields, JSON config, DI factories, etc.).

Because of this, applications are expected to provide their own registry layer that knows how to create readers, writers, and modifiers from stored job definitions.

Below is a simplified example showing how an application might integrate a processor with a registry and a queue worker.
The example demonstrates a possible job handler for the queue service.

Full Example

A complete implementation, including registries, CRUD configuration, and job entities, is available in the Import/Export App.

Credits


All versions of service-read-write with dependencies

PHP Build Version
Package Version
Requires php Version >=8.4
psr/http-message Version ^2.0
tobento/service-collection Version ^2.0
tobento/service-iterable Version ^2.0
tobento/service-message Version ^2.0
tobento/service-support Version ^2.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package tobento/service-read-write contains the following files

Loading the files please wait ...