PHPackages                             centamiv/cast - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. centamiv/cast

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

centamiv/cast
=============

A strictly typed, zero-dependency PHP object-to-object mapping library.

10PHPCI passing

Since Dec 22Pushed 4mo ago1 watchersCompare

[ Source](https://github.com/centamiv/cast-php)[ Packagist](https://packagist.org/packages/centamiv/cast)[ RSS](/packages/centamiv-cast/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Cast (PHP Object Mapper)
========================

[](#cast-php-object-mapper)

**Cast** is a lightweight, strictly typed, zero-dependency PHP library for object-to-object mapping. It allows you to transform entities into DTOs (and vice-versa) using a fluent API and a "convention over configuration" approach.

Features
--------

[](#features)

- **Zero Dependencies**: Pure PHP 8.2+ implementation.
- **Strict Types**: Built with `declare(strict_types=1)`.
- **Automapping**: Automatically maps properties with the same name.
- **Fluent Interface**: Clean and readable API (`Cast::from($src)->to(Target::class)`).
- **Inline Mapping**: Define rules directly in the chain (`Cast::from($src)->map([...])->to(...)`).
- **Transformers**: Built-in helpers for common type conversions.
- **Callbacks**: Custom transformation logic via closures.
- **Recursive**: Automatically handles arrays and collections.
- **Private Properties**: Works with private and protected properties via Reflection.

Installation
------------

[](#installation)

```
composer require centamiv/cast
```

Usage
-----

[](#usage)

### 1. Basic Mapping (Automapping)

[](#1-basic-mapping-automapping)

If your source and target classes have properties with the same names, mapping is automatic.

```
use Centamiv\Cast\Cast;

class User {
    public function __construct(
        public int $id,
        public string $name
    ) {}
}

class UserDto {
    public int $id;
    public string $name;
}

$user = new User(1, 'Mario');

// Maps 'id' and 'name' automatically
$dto = Cast::from($user)->to(UserDto::class);
```

### 2. Custom Transformations (Cast::define)

[](#2-custom-transformations-castdefine)

For complex mappings, renaming, or nested objects, you can define rules using `Cast::define()`.

```
use Centamiv\Cast\Cast;

// Configuration (e.g., in a bootstrap file or ServiceProvider)
Cast::define(Order::class, OrderDto::class, [
    // Simple Rename: source property 'customer_name' -> target property 'client'
    'client' => 'customer_name',

    // Custom Callback: formatting value
    'total' => fn(Order $o) => '€ ' . number_format($o->amount, 2),

    // Nested Mapping: transform array of Items to array of ItemDtos
    'items' => fn(Order $o) => Cast::from($o->getItems())->to(ItemDto::class)
]);

// Execution
$order = $repository->find(123);
$dto = Cast::from($order)->to(OrderDto::class);
```

### 3. Inline Mapping

[](#3-inline-mapping)

You can also define mapping rules directly in the fluent chain, without using `Cast::define()`. This is useful for one-off transformations. Inline rules merge with and override global definitions.

```
$dto = Cast::from($user)
    ->map([
        'fullName' => fn($u) => $u->firstName . ' ' . $u->lastName,
        'isActive' => Cast::toBool('status')
    ])
    ->to(UserDto::class);
```

### 4. Transformers

[](#4-transformers)

The library provides built-in transformer methods directly on the `Cast` facade to simplify common type conversions.

```
use Centamiv\Cast\Cast;

Cast::define(Product::class, ProductDto::class, [
    // Cast 'status_int' (0/1) to boolean
    'isActive' => Cast::toBool('status_int'),

    // Cast 'price_string' to float
    'price' => Cast::toFloat('price_string'),

    // Convert string to DateTimeImmutable (default format: Y-m-d H:i:s)
    'createdAt' => Cast::toDateTime('created_at'),

    // Custom format
    'birthDate' => Cast::toDateTime('dob', 'd/m/Y')
]);
```

Available transformers:

- `Cast::toInt(string $property)`
- `Cast::toFloat(string $property)`
- `Cast::toString(string $property)`
- `Cast::toBool(string $property)`
- `Cast::toDateTime(string $property, string $format = 'Y-m-d H:i:s')`

### 5. Collections

[](#5-collections)

`Cast` detects iterables (arrays, collections) automatically. Passing an array of objects to `Cast::from()` returns an array of mapped objects.

```
$orders = $repository->findAll(); // array

// Returns array
$dtos = Cast::from($orders)->to(OrderDto::class);
```

Requirements
------------

[](#requirements)

- PHP 8.2 or higher

License
-------

[](#license)

MIT

###  Health Score

18

—

LowBetter than 8% of packages

Maintenance50

Moderate activity, may be stable

Popularity2

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity12

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/4bb6e94628f1de489fb3f7114991eef0c4d84f8b42d507cadc2bd54fefc75091?d=identicon)[centamiv](/maintainers/centamiv)

---

Top Contributors

[![centamiv](https://avatars.githubusercontent.com/u/4162703?v=4)](https://github.com/centamiv "centamiv (4 commits)")

### Embed Badge

![Health badge](/badges/centamiv-cast/health.svg)

```
[![Health](https://phpackages.com/badges/centamiv-cast/health.svg)](https://phpackages.com/packages/centamiv-cast)
```

###  Alternatives

[mateusjunges/laravel-invite-codes

This package allows you to easily manage invite codes for your Laravel application.

29166.8k](/packages/mateusjunges-laravel-invite-codes)[ilab/namespacer

Tool for re-namespacing composer packages for use in WordPress plugins.

291.1k](/packages/ilab-namespacer)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
