PHP code example of bylexus / php-injector

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

    

bylexus / php-injector example snippets




// Method invocation:
$injector = new \PhpInjector\Injector('myfunction');

// Class autowiring:
$aw = new \PhpInjector\AutoWire($diContainer);
$serviceA = $aw->createInstance(ServiceA::class);

public function myFunction(Request $request) {
    $param = $request->input('param);
}

$_REQUEST = array('name' => 'Alex','age' => '24', 'active' => 'true');

function storePersonInfo($name, $age, $active = false) {
	// ... do some complex things
}

$res = storePersonInfo($_REQUEST);

$_REQUEST = array('name' => 'Alex','age' => '24','active' => 'true');

/**
 * @param string $name A name
 * @param int[>20] $age The age
 * @param bool $active
 */
function storePersonInfo($name, $age, $active = false) {
    // here, $age ist casted to an int, and must be > 20,
    // while $active is a proper boolean (true) instead of a string.
}

// Invoke the function via injector:
$injectStore = new Injector('storePersonInfo');
$res = $injectStore->invoke($_REQUEST);

$_REQUEST = array('name' => 'Alex','age' => '24','active' => 'true');

class MyController {
    /**
     * @param string $name A name
     * @param int[>20] $age The age
     * @param bool $active
     */
    public function storePersonInfo($name, $age, $active = false) {
        // here, $age ist casted to an int, and must be > 20,
        // while $active is a proper boolean (true) instead of a string.
    }

}

// Invoke the method via injector:
$controller = new Controller();
$injectStore = new Injector(array($controller,'storePersonInfo'));
$res = $injectStore->invoke($_REQUEST);

// Normal function:
function teaser($text, $maxlen = 80, $tail = '...') {
    if (mb_strlen($text) > $maxlen) {
        return mb_substr($text,0,$maxlen-mb_strlen($tail)) . $tail;
    } else {
        return $text;
    }
}

// Class method:
class TextHandler {
    public function teaser($text, $maxlen = 80, $tail = '...') {
        if (mb_strlen($text) > $maxlen) {
            return mb_substr($text,0,$maxlen-mb_strlen($tail)) . $tail;
        } else {
            return $text;
        }
    }
}

// Function injector:
$injector = new \PhpInjector\Injector('teaser');
$ret = $injector->invoke(array(
    'maxlen' => 10,
    'text' => 'My fancy long text that gets cut'
);

// Method injector:
$th = new TextHandler();
$injector = new \PhpInjector\Injector(array($th,'teaser'));
$ret = $injector->invoke(array(
    'maxlen' => 10,
    'text' => 'My fancy long text that gets cut'
);

function doSome(\Psr\Http\Message $message) {
    // do something with the $message object
}

$injector = new \PhpInjector\Injector('doSome');
$ret = $injector->invoke(array(
    'Psr\Http\Message' => new HttpMessage()
);

/**
 * A fancy function with some weird input params
 *
 * @param string $param_a The name of some monster
 * @param int $param_b The age of the monster
 * @param string $param_c The favourite color of the monster
 * @param bool $param_d Is the monster dangerous?
function funcWithSomeParams($param_a, $param_b, $param_c = 'red', $param_d = false) {}

/**
 * A fancy function with some weird input params
 *
 * @param string[<100] $param_a The name of some monster, max. 100 chars
 * @param int[>=0] $param_b The age of the monster
 * @param timestamp[>=01.01.2000] $param_c Date of viewing, min 1.1.2000
 * @param bool $param_d Is the monster dangerous?
function funcWithSomeParams($param_a, $param_b, $param_c = 'red', $param_d = false) {}

// ServiceB is independant
class ServiceB {}

// ServiceA depends on ServiceB:
class ServiceA {
    public ServiceB $b;
    public function __construct(ServiceB $b) {
        $this->b = $b;
    }
}

use PhpInjector\AutoWire;
 
 $aw = new AutoWire();
 // In this case, ServiceB will also be instantiated and injected:
 $instA = $aw->createInstance(ClassNameA::class);

use PhpInjector\AutoWire;

// a PSR-11-compatible service container:
$container = new Container();


// register the container with the AutoWire class:
$aw = new AutoWire($container);

// register ServiceB, which is independant. We could just use `new ServiceB()` here,
// but we can also ask the AutoWire class to create an instance:
// This makes the instantiation of ServiceB future-proof, e.g.
// if ServiceB becomes a dependant of a ServiceC in the future:
$container->set(ServiceB::class, $aw->createInstance(ServiceB::class));

// register ServiceA, while ServiceB is fetched from the containe:
$container->set(ServiceA::class, $aw->createInstance(ServiceA::class));

class ServiceC {
    private $b;
    private $name;
    private $isActive;
    public function __construct(ServiceB $b, string $name, bool $isActive) {
        $this->b = $b;
        $this->name = $name;
        $this->isActive = $isActive;
    }
}

use PhpInjector\AutoWire;

$aw = new AutoWire($container);
$instC = $aw->createInstance(ServiceC::class, [
    'isActive' => true,
    'name' => 'Alex',
]);



// Function to use for injection:
function fact($n) {
    if ($n > 1) {
        return $n*fact($n-1);
    } else return 1;
}

// Injector with no type casting / conditions:
$injector = new \PhpInjector\Injector('fact');
$ret = $injector->invoke(array('n'=>4)); // 24



// Function to use for injection: DocBlock defines the casting type:
/**
 * calculates the factorial of n.
 *
 * @param int $n The value to calculate the factorial from
 */
function fact($n) {
    // here, $n is casted to an int:
    if ($n > 1) {
        return $n*fact($n-1);
    } else return 1;
}

// Injector with type casting to int:
$injector = new \PhpInjector\Injector('fact');
$ret = $injector->invoke(array('n'=>4.5)); // 24



// Function to use for injection: DocBlock defines the casting type and condition:
/**
 * calculates the factorial of n.
 *
 * @param int[>0] $n The value to calculate the factorial from
 */
function fact($n) {
    // here, $n is casted to an int. An exception is thrown when $n is < 1.
    if ($n > 1) {
        return $n*fact($n-1);
    } else return 1;
}

// Injector with type casting to int:
$injector = new \PhpInjector\Injector('fact');
$ret = $injector->invoke(array('n'=>4.5)); // 24

$inj = new \PhpInjector\Injector('strtolower');
echo $inj->invoke(array('str'=>'HEY, WHY AM I SMALL?'));

// Function that receives an object of type 'Psr\Http\Request':
function processRequest(\Psr\Http\Request $req, $param1, $param2) {
    // process Request
}

$inj = new \PhpInjector\Injector('processRequest');
echo $inj->invoke(['Psr\Http\Request' => new Request(), 'param1' => 'foo', 'param2' => 'bar']);

use MyServices\FooService;

// Function that receives an object of type 'Psr\Http\Request':
function processRequest(FooService $myService, $param1) {
    $myService->doSome($param1);
}

// Service container with available service, created / intantiated elswhere:
$container = get_the_PSR_11_Service_container();
$container->registerService(new FooService());

// Now just give the service container in the options array:
$inj = new \PhpInjector\Injector('processRequest', ['service_container' => $container]);
echo $inj->invoke(['param1' => 'foo']);


// Or, optionally, set the service container later:
$inj = new \PhpInjector\Injector('processRequest');
$inj->setServiceContainer($container);
echo $inj->invoke(['param1' => 'foo']);

use PhpInjector\AutoWire;

class ServiceA {}
class ServiceB {
    public function __construct(ServiceA $a) {}
}

$aw = new AutoWire();
// here, ServiceA is just instantiated with "new ServiceA()", along with ServiceB:
$b = $aw->createInstance(ServiceB::class);

use PhpInjector\AutoWire;

class ServiceA {}
class ServiceB {
    public function __construct(ServiceA $a, string $name) {}
}

$aw = new AutoWire();
// here, ServiceA is just instantiated with "new ServiceA()", along with ServiceB:
$b = $aw->createInstance(ServiceB::class, [
    'name' => 'foo',
    new ServiceA(),
]);

use PhpInjector\AutoWire;

// ServiceB is independant
class ServiceB {}

// ServiceA depends on ServiceB:
class ServiceA {
    public ServiceB $b;
    public function __construct(ServiceB $b) {
        $this->b = $b;
    }
}

// a PSR-11-compatible service container:
$container = new Container();

// register the container with the AutoWire class:
$aw = new AutoWire($container);

// ServiceB is indepenadnt
$container->set(ServiceB::class, new ServiceB());

// register ServiceA, while ServiceB is fetched from the containe:
$container->set(ServiceA::class, $aw->createInstance(ServiceA::class));
shell
# With docker:
$ git clone [email protected]:bylexus/php-injector.git
$ cd php-injector
$ docker build -t php-injector docker/
$ docker run --name php-injector -ti -v "$(pwd):/src" php-injector bash
docker> composer install
docker> composer test