扩展Symfony 2请求服务?

时间:2012-08-06 06:14:21

标签: symfony

我正在关注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%参数,因此应该很容易扩展Symfony Session类,例如:

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();

1 个答案:

答案 0 :(得分: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();