将应用程序注入控制器


Inject Application into Controller

我有以下DemoController

class DemoController {
    public function test() {
        return new Response('This is a test!');
    }
}

我想将此控制器绑定到$app ['demo.controller']

$app ['demo.controller'] = $app->share ( function () use($app) {
    return new DemoController ();
} );

在DemoController中,我想让Application $app对象与注册的服务一起工作。什么是正确的方法?目前,我使用__construct($app)作为DemoController,并通过$app。这看起来像

$app ['demo.controller'] = $app->share ( function () use($app) {
    return new DemoController ($app);
} );

最好的做法是什么?

这当然是一种方法。我想展示两种选择。

一种是使用类型提示将应用程序直接注入到操作方法中:

use Silex'Application;
use Symfony'Component'HttpFoundation'Request;
class DemoController
{
    public function test(Request $request, Application $app)
    {
        $body = 'This is a test!';
        $body .= ':'.$request->getRequestUri();
        $body .= ':'.$app['foo']->bar();
        return new Response($body);
    }
}

此选项的优点是,您实际上不需要将控制器注册为服务。

另一种可能性是注入特定的服务,而不是注入整个容器:

use Silex'Application;
use Symfony'Component'HttpFoundation'Request;
class DemoController
{
    private $foo;
    public function __construct(Foo $foo)
    {
        $this->foo = $foo;
    }
    public function test()
    {
        return new Response($this->foo->bar());
    }
}

服务定义:

$app['demo.controller'] = $app->share(function ($app) {
    return new DemoController($app['foo']);
});

此选项的优点是,您的控制器不再依赖于silex、容器或任何特定的服务名称。这使得它更加孤立、可重复使用,并且更容易在隔离中进行测试。