2012-08-06 77 views
6

我在關注Symfony 2網站上的How to Override any Part of a Bundle頁面。這很有趣:擴展Symfony 2請求服務?

您可以通過在應用程序/配置/ 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); 
    } 
} 

我din't測試這個呢。但是我怎樣才能做到與request特殊服務一樣呢?我想添加一些便捷的快捷方式以使我的代碼更易於閱讀。

<!-- 
     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

services.xml文件中發現這一點。我應該如何傳遞我的自定義請求類的實例?

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

'網/ app.php' - 你不有這樣的? O_o – 2012-08-06 06:18:51

+0

@thecatontheflat lol:D我正在看'/ app'文件夾...然後我要更新這個問題。 – gremo 2012-08-06 06:23:11

回答

13

好吧,很簡單。

在你app.php剛剛通過的實例,而不是默認的:

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在類擴展。

應該沒有額外的服務定義。


根據評論,有人認爲這會導致IDE自動完成問題。理論上 - 不應該。

在你的控制器,你只需要添加use聲明

use src\YourCompany\YourBundle\YourRequest; 

而且在行動上,在那裏你通過$request,只是定義它的類:

public function yourAction(YourRequest $request) 

這會給你自動完成。

在情況下,如果你想獲得請求的服務或從控制器,用於IDE還可以在註釋文檔定義了同級車:

/** @var $request YourRequest */ 
    $request = $this->getRequest(); 
+0

姆姆......看起來好容易,我會試試!那麼只有這件壞事,我想,是你無法獲得IDE自動完成功能...... – gremo 2012-08-06 06:48:01

+0

你總是可以。更新我的回答 – 2012-08-06 06:48:36

+0

我的意思是用'$ this-> getRequest()'... – gremo 2012-08-06 08:56:18