PHP code example of baraja-core / service-method-invoker

1. Go to this page and download the library: Download baraja-core/service-method-invoker 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/ */

    

baraja-core / service-method-invoker example snippets


$invoker = new \Baraja\ServiceMethodInvoker;
$apiEndpoint = new \Baraja\MyApiEndpoint;

$data = $invoker->invoke($apiEndpoint, 'actionDetail', ['id' => 42]);

var_dump($data); // return "My id is: 42"

class MyApiEndpoint
{
    public function actionDetail(int $id): string
    {
        return 'My id is: ' . $id;
    }
}

$invoker = new \Baraja\ServiceMethodInvoker;
$args = $invoker->getInvokeArgs($service, 'methodName', $params);

// $args is now a validated and hydrated array ready for method invocation

class MyService
{
    public function process(
        int $count,      // "42" -> 42, "null" -> null (if nullable)
        float $price,    // "19.99" -> 19.99
        bool $active,    // "true", "1", "yes" -> true; others -> false
        string $name,    // kept as-is
        array $items,    // kept as-is
    ): void {
        // ...
    }
}

$invoker->invoke($service, 'process', [
    'count' => '42',
    'price' => '19.99',
    'active' => 'yes',
    'name' => 'Test',
    'items' => ['a', 'b'],
]);

public function find(?int $id): void
{
    // '' or '0' with nullable type -> null
    // '0' with non-nullable int -> 0
}

class CreateUserRequest
{
    public function __construct(
        public string $email,
        public string $name,
        public ?int $age = null,
    ) {}
}

class UserController
{
    public function create(CreateUserRequest $request): User
    {
        // $request is automatically hydrated from the params array
        return new User($request->email, $request->name);
    }
}

$invoker->invoke($controller, 'create', [
    'email' => '[email protected]',
    'name' => 'John Doe',
    'age' => 25,
]);

class Address
{
    public function __construct(
        public string $street,
        public string $city,
    ) {}
}

class Order
{
    public function __construct(
        public string $product,
        public Address $shippingAddress,
    ) {}
}

$invoker->invoke($service, 'createOrder', [
    'product' => 'Widget',
    'shippingAddress' => [
        'street' => '123 Main St',
        'city' => 'Prague',
    ],
]);

class UserEntity
{
    private string $email;

    public function setEmail(string $email): void
    {
        $this->email = strtolower($email);
    }
}

class NodeA
{
    public NodeB $child;
}

class NodeB
{
    public NodeA $parent; // This would cause a circular reference
}

// RuntimeInvokeException: Circular reference detected...

enum Status: string
{
    case Active = 'active';
    case Inactive = 'inactive';
    case Pending = 'pending';
}

class OrderService
{
    public function updateStatus(int $orderId, Status $status): void
    {
        // ...
    }
}

// All of these work:
$invoker->invoke($service, 'updateStatus', ['orderId' => 1, 'status' => 'active']);
$invoker->invoke($service, 'updateStatus', ['orderId' => 1, 'status' => 'ACTIVE']);
$invoker->invoke($service, 'updateStatus', ['orderId' => 1, 'status' => 'Active']);

use Baraja\ServiceMethodInvoker\ProjectEntityRepository;

class DoctrineEntityRepository implements ProjectEntityRepository
{
    public function __construct(
        private EntityManagerInterface $em,
    ) {}

    public function find(string $className, int|string $id): ?object
    {
        return $this->em->find($className, $id);
    }
}

$invoker = new ServiceMethodInvoker(
    projectEntityRepository: new DoctrineEntityRepository($entityManager),
);

class ArticleController
{
    public function show(Article $article): Response
    {
        // $article is automatically loaded from the database using the ID
    }
}

$invoker->invoke($controller, 'show', ['article' => 42]);
// Article with ID 42 is automatically loaded via the repository

class BatchProcessor
{
    public function process(array $data): void
    {
        // $data contains all the input parameters
    }
}

$invoker->invoke($processor, 'process', [
    'item1' => 'value1',
    'item2' => 'value2',
], dataMustBeArray: true);

// $data = ['item1' => 'value1', 'item2' => 'value2']

try {
    $invoker->invoke($service, 'method', $params);
} catch (RuntimeInvokeException $e) {
    $e->getService();  // The service object that failed
    $e->getMethod();   // The method name that was being called
    $e->getParams();   // The parameters that were passed
    $e->getMessage();  // Detailed error message
}

use Baraja\Service;

class UserApiEndpoint implements Service
{
    public function __toString(): string
    {
        return 'User API Endpoint';
    }

    public function getUser(int $id): array
    {
        // ...
    }
}

// Error messages will now show "User API Endpoint" instead of the class name

class EventService
{
    public function schedule(
        string $name,
        \DateTimeImmutable $startDate,
    ): void {
        // $startDate is automatically created from the string value
    }
}

$invoker->invoke($service, 'schedule', [
    'name' => 'Conference',
    'startDate' => '2024-06-15 10:00:00',
]);