PHP code example of lingualeo / php-servaxle

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

    

lingualeo / php-servaxle example snippets


namespace Tutorial;

class Foo
{
}

class Bar
{
    public function __construct(Foo $foo)
    {
    }
}

$scope = new \LinguaLeo\DI\Scope([
    'bar' => Bar::class
]);

$scope->bar; // instance of Tutorial\Bar class

namespace Tutorial;

interface AnimalInterface {}

class Dog implements AnimalInterface {}

class Cat implements AnimalInterface {}

class Home
{
    public function __construct(AnimalInterface $animal)
    {
    }
}

$scope = new \LinguaLeo\DI\Scope([
    'home' => Home::class,
    AnimalInterface::class => Dog::class
]);

$scope->home; // instanse of Tutorial\Home class with Tutorial\Dog object injection

$scope = new LinguaLeo\DI\Scope([
    'user' => 'root'
]);

$scope->getValue('user'); // "root"

$scope = new LinguaLeo\DI\Scope([
    'max' => 'PHP_INT_MAX'
]);

$scope->max; // 9223372036854775807 (in 64 bit OS)

$scope = new LinguaLeo\DI\Scope([
    'super' => 'admin',
    '@user' => 'super',
    'member' => '@user'
]);

$scope->getValue('member'); // "admin" as @user -> super -> admin

$scope = new LinguaLeo\DI\Scope([
    'super' => 'admin',
    'member' => '$super'
]);

$scope->getValue('member'); // "admin"

$scope = new LinguaLeo\DI\Scope([
    'now' => function () {
        return uniqid();
    }
]);

$scope->getValue('now') === $scope->getValue('now'); // false
$scope->now === $scope->now; // true

namespace Tutorial;

class RedisFactory
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function __invoke()
    {
        $redis = new \Redis();
        $redis->connect($this->host);
        return $redis;
    }
}

$scope = new \LinguaLeo\DI\Scope([
    'redis' => RedisFactory::class,
    'redis.host' => '192.168.1.1'
]);

$scope->redis; // instance of \Redis class

namespace Tutorial;

// define classes
class Foo {}

class Bar
{
    public function __construct(Foo $foo) {}
}

class Baz
{
    public function __construct(Bar $bar) {}
}

// compiles a tree
$script = \LinguaLeo\DI\Scope::compile([
    'baz' => Baz::class
]);

// put into PHP file
file_put_contents('cache.php', ' return '.$script.';');

// init a scope from file
$scope = new \LinguaLeo\DI\Scope(

$scope = new LinguaLeo\DI\ImmutableScope(