PHP code example of xou816 / silex-autowiring

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

    

xou816 / silex-autowiring example snippets


use SilexAutowiring\AutowiringServiceProvider;

// ...

$app->register(new AutowiringServiceProvider());

class Foo {}
class Bar {
    public function __construct(Foo $foo) {
        $this->foo = $foo;
    }
    public function greet() {
        return 'Hello!';
    }
}
$app['autowiring']->wire(Foo::class);
$app['autowiring']->wire(Bar::class);

$app->get('/', function (Bar $bar) {
    return $bar->greet();
});

$fun = function(Foo $foo, $arg) {
    $foo->bar($arg);
};
$app['autowiring']->invoke($fun, ['bar']); // Calls $foo->bar('bar'), where $foo has class Foo

$fun = function(Foo $foo, $arg) {
    $foo->bar($arg);
};
$newfun = $app['autowiring']->partial($fun);
$newfun('bar'); // Calls $foo->bar('bar'), where $foo has class Foo

interface GreeterInterface {
    public function greet();
}

class PoliteGreeter implements GreeterInterface {
    public function greet() {
        return 'Hello!';
    }
}
$app['autowiring']->wire(PoliteGreeter::class);

class RudeGreeter implements GreeterInterface {
    public function greet() {
        return '...';
    }
}
$app['autowiring']->wire(RudeGreeter::class);

$app->get('/', function(GreeterInterface $greeter) {
    return $greeter->greet(); // '...'
});

$app->register(new DoctrineServiceProvider()); // registers a 'db' service
$app['autowiring']->expose('db');

// ...

class DAO {
    public function __construct(\Doctrine\DBAL\Connection $db) { /**/ }
}
$app['autowiring']->wire(DAO::class); // will work just fine!

$app['autowiring']->provide(Foo::class, function($app, Bar $bar) {
    return new Foo($bar);
});

$app['foo_options'] = array('bar' => true);
$app['foo_options.baz'] = false;

class Foo {
    public __construct(Injectable $fooOptions) {
        $this->bar = $fooOptions->get()['bar']; // true
        $this->baz = $fooOptions->get()['baz']; // false
    }
}
$app['autowiring']->wire(Foo::class);

// ...
class Foo {
    public __construct(Configuration $fooOptions) {
        $this->bar = $fooOptions['bar']; // true
        $this->baz = $fooOptions['baz']; // false
    }
}

$app['fooconfig'] = array('bar' => true);
$app['fooconfig.baz'] = false;

class Foo {
    private $bar;
    private $baz;
}
$app['autowiring']->wire(Foo::class);
$app['autowiring']->configure(Foo::class, 'fooconfig');

class Foo {
    use Autowire;
}
class Bar {
    use Autowire;
    public function __construct(Foo $foo) {
        $this->foo = $foo;
    }
    public function greet() {
        return 'Hello!';
    }
}