PHPackages                             rikta/callback-switch - 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. rikta/callback-switch

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

rikta/callback-switch
=====================

Switch-statement-like objects based on callbacks for several use-cases

v1.0.0(5y ago)05[1 PRs](https://github.com/MadWillow/CallbackSwitch/pulls)MITPHPPHP &gt;=7.4CI passing

Since Jan 15Pushed 7mo ago1 watchersCompare

[ Source](https://github.com/MadWillow/CallbackSwitch)[ Packagist](https://packagist.org/packages/rikta/callback-switch)[ Docs](https://packagist.org/packages/rikta/callback-switch)[ RSS](/packages/rikta-callback-switch/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (7)Versions (3)Used By (0)

CallbackSwitch
==============

[](#callbackswitch)

[![GitHub issues](https://camo.githubusercontent.com/3d44054cdb2f4510f19c0e3670b7dd2a3cc11df8fe5f05cc7158589ffd9d6aa6/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6973737565732f52696b7461442f43616c6c6261636b537769746368)](https://github.com/RiktaD/CallbackSwitch/issues)[![GitHub license](https://camo.githubusercontent.com/151163d26b07126a90c237ac4d81b4324d3551f6d8d9473b2f57056cbe88e18a/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f52696b7461442f43616c6c6261636b537769746368)](https://github.com/RiktaD/CallbackSwitch/blob/master/LICENSE)[![Packagist PHP Version Support](https://camo.githubusercontent.com/00aa3aacb24782837afd0ed432a3fcbf777fc1541e65488c3dedd9846acbfb10/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f72696b74612f63616c6c6261636b2d737769746368)](https://camo.githubusercontent.com/00aa3aacb24782837afd0ed432a3fcbf777fc1541e65488c3dedd9846acbfb10/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f72696b74612f63616c6c6261636b2d737769746368)[![Packagist Version](https://camo.githubusercontent.com/93dfe22a2cd0ca932f8bee9cb8327f023f5175abf8eba2d5071b7624369146b6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f72696b74612f63616c6c6261636b2d737769746368)](https://camo.githubusercontent.com/93dfe22a2cd0ca932f8bee9cb8327f023f5175abf8eba2d5071b7624369146b6/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f72696b74612f63616c6c6261636b2d737769746368)

Advanced switch statements as classes

Description
-----------

[](#description)

This package provides classes that wrap similar logic to a switch statement into object-instances.

You provide several callbacks together with their key and subsequently call the instance like a method. (there is also a static one-method-call)

This enables you to abstract away commonly used switching-logic, dynamically construct the cases or maybe even inject some conditional as dependency e.g. in DI or Strategy-Patterns

Along the Abstraction this package ships:

- `SwitchByIsA` -&gt; Keys are Interfaces (FQCN), prioritized by order of added callbacks (first wins)
- `SwitchByType` -&gt; Keys are inbuilt types or FQCNs, FQCNs have higher priority
- `SwitchByValue` -&gt; Keys are the values
- `SwitchBySubstring` -&gt; Keys are substrings of the passed value; prioritized by order of added callbacks (first wins)

You can also easily implementing your own CallbackSwitches by extending the `AbstractCallbackSwitch`and implementing the only abstract method to choose which callback to use

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

[](#installation)

Require this package with `composer require rikta/callback-switch`

Usage
-----

[](#usage)

### Cases

[](#cases)

Regardless of your concrete call you provide your cases as `callables` with an associated key.

The `callable` will get the `$value` as first parameter, and `...$extra` for the rest of it.

What you have to choose for the key depends on the type of switch you are using. e.g. if you use `SwitchByValue` it must match the exact `(string)$value`, if you use `SwitchByType` it must match the type or class of `$value`

### with Instance

[](#with-instance)

#### Create

[](#create)

You can create a class implementing `CallbackSwitch` with an optional `['key' => fn($value, ...$extra)]` array.

```
$exampleSwitch = new SwitchByType([
    SwitchByType::string => staticfn($value) => ('Hello ' . $value),
    SwitchByType::int => staticfn($value) => ('Hello Agent '. $value),
])
```

#### Add Cases

[](#add-cases)

You can add cases to a CallbackSwitchInstance with `addCase($key, $callable)`

```
$exampleSwitch->addCase(SwitchByType::array, fn($value) => ('Hello ' . implode(' and ', $value)))
```

#### Make optional

[](#make-optional)

By default, a `CallbackSwitch` shall throw an exception if neither a matching case was found, nor a default was provided.

If you mark the instance as "optional" `null` will be returned instead.

There are two ways to mark an instance as optional:

- You can pass `true` as second argument to the constructor

```
$exampleSwitch = new SwitchByType([...], true)
```

- You can call `setOptional()` on the instance

```
$exampleSwitch->setOptional()
```

#### Invoke

[](#invoke)

Every class implementing `SwitchCallback` is invokable, as if it would be a method.

Pass your `$value` as first parameter, it will be used to determine the case and passed to the callback. Any extraneous parameters you pass here will be passed to the callback as well.

```
echo $exampleSwitch(['Anna', 'Bob']);

```

#### Full example

[](#full-example)

```
$exampleSwitch = new SwitchByType([
    SwitchByType::string => staticfn($value) => ('Hello ' . $value),
    SwitchByType::int => staticfn($value) => ('Hello Agent '. $value),
]);

$exampleSwitch
    ->addCase(SwitchByType::array, fn($value) => ('Hello ' . implode(' and ', $value)))
    ->setOptional();

echo $exampleSwitch('World'); // Hello World
echo $exampleSwitch(['Jay', 'Bob']); // Hello Jay and Bob
echo $exampleSwitch(47); // Hello Agent 47
```

### without Instance

[](#without-instance)

If you need the CallbackSwitch only once, you can call the static version.

```
$value = 'World';
echo SwitchByType::switch($value, [
    SwitchByType::string => staticfn($value) => ('Hello ' . $value),
    SwitchByType::int => staticfn($value) => ('Hello Agent '. $value),
    SwitchByType::array => staticfn($value) => ('Hello ' . implode(' and ', $value)))
]) // Hello World;
```

#### Make optional

[](#make-optional-1)

By default, a `CallbackSwitch` shall throw an exception if neither a matching case was found, nor a default was provided.

If you call `::switchOptional` instead of `::switch`, `null` will be returned instead.

Contributing
------------

[](#contributing)

Contributions are always welcome.

Should you want to contribute I suggest you take a look at [CONTRIBUTING.md](.github/CONTRIBUTING.md) first.

License
-------

[](#license)

[MIT](./LICENSE)

###  Health Score

29

—

LowBetter than 60% of packages

Maintenance44

Moderate activity, may be stable

Popularity4

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity54

Maturing project, gaining track record

 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.

###  Release Activity

Cadence

Unknown

Total

1

Last Release

1940d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/f0ccaa2dd19d65140583addf5e5a4178d77932366733e99eeb78cc0fc53c291f?d=identicon)[kuroishinjitsu](/maintainers/kuroishinjitsu)

---

Top Contributors

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

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Code StylePHP\_CodeSniffer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/rikta-callback-switch/health.svg)

```
[![Health](https://phpackages.com/badges/rikta-callback-switch/health.svg)](https://phpackages.com/packages/rikta-callback-switch)
```

###  Alternatives

[lexxyungcarter/chatmessenger

Simple one-to-one/group chat messaging tool for Laravel 5, 6, 7, 8, 9 &amp; 10 with Pusher Integration

10724.1k](/packages/lexxyungcarter-chatmessenger)[georgeboot/laravel-tiptap

Opinionated integration of Tiptap editor using the TALL stack

346.4k](/packages/georgeboot-laravel-tiptap)[bmichotte/dijkstra

php 7+ implementation of the Dijkstra algorithm

131.5k](/packages/bmichotte-dijkstra)

PHPackages © 2026

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