derrabus/silex-psr11-provider

提供一个PSR-11兼容的服务容器。

v1.1.2 2020-07-17 10:41 UTC

This package is auto-updated.

Last update: 2024-09-18 21:14:24 UTC


README

此服务提供者在Silex应用程序内部注册一个PSR-11兼容的服务容器。

PSR-11允许开发者编写可以感知服务容器但不与其特定实现耦合的代码,从而更轻松地切换到另一个服务容器。

Build Status

安装

使用Composer安装此包。

composer require derrabus/silex-psr11-provider

用法

注册服务提供者后,您可以访问容器作为服务service_container,或者通过使用Psr\Container\ContainerInterface作为类型提示作为控制器参数。

示例

use Psr\Container\ContainerInterface;
use Rabus\Psr11ServiceProvider\Psr11ServiceProvider;
use Silex\Application;
use Silex\Provider\ServiceControllerServiceProvider;
use Symfony\Component\HttpFoundation\RedirectResponse;

class SomeController
{
    private $container;

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

    public function someAction()
    {
        return new RedirectResponse(
            $this->container->get('url_generator')->generate('home')
        );
    }
}

$app = new Application();
$app->register(new ServiceControllerServiceProvider());
$app->register(new Psr11ServiceProvider());

$app['some_controller'] = function ($app) {
    // Inject a PSR-11 container instead of the $app
    return new SomeController($app['service_container']);
};

$app->get('/', function() {
    return 'Home.';
})->bind('home');

$app->get('/test1', 'some_controller:someAction');

// Type-hint the PSR-11 container instead of the $app
$app->get('/test2', function (ContainerInterface $container) {
    new RedirectResponse($container->get('url_generator')->generate('home'));
});

博客

此服务提供者可以作为从Silex迁移到Symfony的跳板使用。它被创建来展示如何解耦Silex应用程序与服务容器实现