PHP code example of code-distortion / di-caller

1. Go to this page and download the library: Download code-distortion/di-caller 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/ */

    

code-distortion / di-caller example snippets


use CodeDistortion\DICaller\DICaller;

$callable = fn(Request $request, User $user) => "hello $user->name ({$request->getIp()})";

$user = new User();
$request = new Request();
$shoppingCart = new ShoppingCart();

$result = DICaller::new($callable)
    ->registerByType($user)         // <<<
    ->registerByType($request)      // <<<
    ->registerByType($shoppingCart) // <<<
    ->call(); // 'hello Bob (192.168.1.1)'

use CodeDistortion\DICaller\DICaller;

$callable = fn($param1, $param2) => "$param1 $param2";

$result = DICaller::new($callable)
    ->registerByName('param1', 'hello') // <<<
    ->registerByName('param2', 'world') // <<<
    ->call(); // 'hello world'

use CodeDistortion\DICaller\DICaller;

$callable = fn($param1, $param2) => "$param1 $param2";

$result = DICaller::new($callable)
    ->registerByPosition(0, 'hello') // <<<
    ->registerByPosition(1, 'world') // <<<
    ->call(); // 'hello world'

use CodeDistortion\DICaller\DICaller;

$callable = fn(int|float $param1) => $param1; // <<<

$result = DICaller::new($callable)
    ->registerByType(1.1) // <<<
    ->call(); // 1.1

use CodeDistortion\DICaller\DICaller;

$callable = fn(ParentClass&ChildClass $param1) => $param1; // <<<

$result = DICaller::new($callable)
    ->registerByType(new ChildClass()) // <<<
    ->call(); // ChildClass

use CodeDistortion\DICaller\DICaller;

$callable = fn(int $param1, int ...$param2) => func_get_args(); // <<<

$result = DICaller::new($callable)
    ->registerByName('param1', 1)
    ->registerByName('param2', 2)
    ->call(); // [1, 2]

use CodeDistortion\DICaller\DICaller;

$callable = fn($param1, $param2) => "$param1 $param2";

$caller = DICaller::new($callable);
if ($caller->isCallable()) { // false
    $result = $caller->call();
}

use CodeDistortion\DICaller\DICaller;

$callable = fn($param1, $param2) => "$param1 $param2";

$result = DICaller::new($callable)->callIfPossible(); // null

use CodeDistortion\DICaller\DICaller;

$callable = 'not a callable';

$result = DICaller::new($callable)->call(); // throws DICallerInvalidCallableException

use CodeDistortion\DICaller\DICaller;

$callable = fn($param1, $param2) => "$param1 $param2";

$result = DICaller::new($callable)->call(); // throws DICallerUnresolvableParametersException