PHP code example of norvica / invoker

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

    

norvica / invoker example snippets


// using function
$result = \Norvica\Invoker\call('some_function', ['arg1' => 'value1']);

// using class
$result = \Norvica\Invoker\Invoker::call('some_function', ['arg1' => 'value1']);

$result = \Norvica\Invoker\call('some_function', ['arg1' => 'value1']);

$closure = function (string $arg1) {
  // [...]
};
$result = \Norvica\Invoker\call($closure, ['arg1' => 'value1']);

$object = new ClassWithInvokeMethod();
$result = \Norvica\Invoker\call($object, ['arg1' => 'value1']);

// same as
$result = \Norvica\Invoker\call([$object, '__invoke'], ['arg1' => 'value1']);

$object = new ClassWithPublicMethod();
$result = \Norvica\Invoker\call([$object, 'someMethod'], ['arg1' => 'value1']);

$result = \Norvica\Invoker\call([ClassWithStaticMethod::class, 'someMethod'], ['arg1' => 'value1']);

// or
$result = \Norvica\Invoker\call(ClassWithStaticMethod::class . '::foo', ['arg1' => 'value1']);

$closure = function (string $arg1, int ...$number) {
  // [...]
};
$result = \Norvica\Invoker\call($closure, ['arg1' => 'value1', 'number' => [1, 2, 3]]);

use Norvica\Invoker\Resolver;
use ReflectionParameter;
use Psr\Container\ContainerInterface;

final class ServiceResolver implements Resolver
{
    public function __construct(
        private ContainerInterface $container,
    ) {}

    public function resolve(ReflectionParameter $parameter): mixed
    {
        return $this->container->get((string) $parameter->getType());
    }

    public function supports(ReflectionParameter $parameter): bool
    {
        return $this->container->has((string) $parameter->getType());
    }
}

$container = // your PSR-11 container
$resolver = new ServiceResolver($container);
$result = \Norvica\Invoker\call([$someObject, 'someMethod'], ['foo' => 'bar'], $resolver);

use Norvica\Invoker\Resolver;
use ReflectionParameter;
use Psr\Http\Message\ServerRequestInterface;

final class RequestResolver implements Resolver
{
    public function __construct(
        private YourRequestFactory $factory,
    ) {}

    public function resolve(ReflectionParameter $parameter): ServerRequestInterface
    {
        return $this->factory->createFromGlobals();
    }

    public function supports(ReflectionParameter $parameter): bool
    {
        return is_a((string) $parameter->getType(), ServerRequestInterface::class, true);
    }
}

$requestResolver = new RequestResolver($yourRequestFactory);
$result = \Norvica\Invoker\call($someInvokableController, ['id' => '123'], $requestResolver);