7

我正在关注Symfony 2 网站上的 How to Override any Part of a Bundle页面。这是有趣的:

您可以通过在 app/config/config.yml 中设置来将保存服务的类名的参数设置为您自己的类。当然,这只有在类名被定义为包含服务的捆绑包的服务配置中的参数时才有可能。

所以我看了看,/vendor/symfony/src/Symfony/Bundle/FrameworkBundle/Resources/config发现这session.xml是定义%session.class%参数,所以应该很容易扩展 SymfonySession类,如下所示:

namespace Acme\HelloBundle\Component\HttpFoundation;

use Symfony\Component\HttpFoundation\Session;

class ExtendedSession extends Session
{
    public function setSuccessFlashText($text, array params = array())
    {
       parent::setFlash('success', $this->getTranslator()->trans($text, $params);
    }
}

我还没有测试过这个。但是我怎样才能对request特殊服务做同样的事情呢?我想添加一些方便的快捷方式,以使我的代码更易于阅读。

我在services.xml文件中找到了这个:

    <!--
        If you want to change the Request class, modify the code in
        your front controller (app.php) so that it passes an instance of
        YourRequestClass to the Kernel.
        This service definition only defines the scope of the request.
        It is used to check references scope.
    -->
    <service id="request" scope="request" synthetic="true" />

这是我的app.php。我应该如何传递我的自定义请求类的实例?

require_once __DIR__.'/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppKernel.php';
//require_once __DIR__.'/../app/AppCache.php';

use Symfony\Component\HttpFoundation\Request;

$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
//$kernel = new AppCache($kernel);
$kernel->handle(Request::createFromGlobals())->send();
4

1 回答 1

14

嗯,这很简单。

在您app.php刚刚传递的实例中,YourRequest而不是默认值:

require_once __DIR__.'/../app/bootstrap.php.cache';
require_once __DIR__.'/../app/AppKernel.php';
//require_once __DIR__.'/../app/AppCache.php';

use src\YourCompany\YourBundle\YourRequest;

$kernel = new AppKernel('prod', false);
$kernel->loadClassCache();
//$kernel = new AppCache($kernel);
$kernel->handle(YourRequest::createFromGlobals())->send();

只需确保您从课堂上的默认值Request扩展YourRequest

应该在没有额外服务定义的情况下工作。


根据评论,有人认为这会导致 IDE 自动完成问题。理论上 - 它不应该。

在您的控制器中,您只需添加use语句

use src\YourCompany\YourBundle\YourRequest;

在行动中,你通过的地方$request,只需定义它的类:

public function yourAction(YourRequest $request)

这将为您提供自动完成功能。

如果您想将请求作为服务或从控制器获取,对于 IDE,您还可以在注释文档中定义其类:

    /** @var $request YourRequest */
    $request = $this->getRequest();
于 2012-08-06T06:32:23.457 回答