2014-07-26 26 views
1

我目前正在爲自己開發一個小項目,並且開始使用Symfony 2。現在一切都很順利,但我確實質疑自己在哪裏放置某種「主類」。Symfyon 2何處放置一個被多個控制器功能使用的類

問題是,我要在多個頁面/控制器上使用「相同類型」的數據。例如,我想顯示用戶在頁面X上創建的「帖子」數量,但也會在頁面Y上顯示它。

我實際上想要一個函數,可以說「getUserData($ user)」,即可用於多個控制器。我不想在兩個頁面上使用相同的控制器,因爲除了幾個部分外,它們完全不同。

這是助手,服務還是依賴注入?或者我應該只擴展bundle的默認控制器?

我擁有的功能是這樣的:

public function getPostsByUserTopic($value, $currentTopic) 
{ 
    $em = $this->getDoctrine()->getManager(); 
    $posts = $em->getRepository('DevrantStatBundle:Coffeecorner')->findBy(
     array('user' => $value, 
     'topicid' => $currentTopic), 
     array('time' => 'ASC') 
     ); 

    return $posts; 
} 

public function getPostsByUser($value) 
{ 
    $em = $this->getDoctrine()->getManager(); 
    $posts = $em->getRepository('DevrantStatBundle:Coffeecorner')->findBy(
     array('user' => $value), 
     array('time' => 'ASC') 
     ); 

    return $posts;  
} 

public function countPostsByUserTopic($value, $currentTopic) 
{ 
    $em = $this->getDoctrine()->getManager(); 
    $repository = $this->getDoctrine()->getRepository('DevrantStatBundle:Coffeecorner'); 
    $parameters = array(
     'user' => $value, 
     'topicid' => $currentTopic, 
    ); 
    $query = $em->createQuery(
     'SELECT COUNT(u.user) as aantal, u.user 
     FROM DevrantStatBundle:Coffeecorner u 
     WHERE u.user = :user 
     AND u.topicid = :topicid 
     GROUP BY u.user, u.topicid 
     ORDER BY aantal DESC' 
    )->setParameters($parameters); 

    $count = $query->getResult(); 

    return $count[0]; 
} 

回答

1

絕對是一個服務。服務是專門爲提供需要應用於系統不同部分的某些功能而設計的。只需創建一個具有所需功能的類並將其註冊爲服務。瞧! :)

更多的是: http://symfony.com/doc/current/book/service_container.html

+0

並沒有真正意義上的我。我的函數不會啓動某種被用來做事情的對象。例如,我的控制器傳遞一些信息,如用戶,應收集的數據類型以及函數返回的數據。我不打算使用該對象來實例更新用戶。 –

0

我不認爲有一個像在Symfony2的助手的概念。

用於計數用戶做出你能的方法添加到用戶對象(例如getPostsCount())..在嫩枝模板柱:{{app.user.postsCount}},或可以使用的枝條濾波器length{{app.user.posts|length}}。但我不知道,如何學說如何處理(懶加載?..也許有人可以告訴請嗎?)

你可以寫一個Twig-Extension (a Twig-Function)這實際上是symfony服務,用twig.extension標記。這個服務比通過在services.yml,services.xml或annotations中定義的依賴注入來注入它需要的依賴(例如,doctrine,security_context)。

例如(ACME/FooBundle /資源/配置/ services.yml):

acme_foo_bundle.twig.user_posts_count: 
    class: Acme\FooBundle\Twig\UserPostsCount 
    arguments: [@doctrine, @security_context] 
    tags: 
     - { name: twig.extension } 

然後在模板:

{{ user_posts_count() }}

你可以做到這一點也比較一般不注入@security_context到服務和傳球用戶的功能:

acme_foo_bundle.twig.user_posts_count: 
    class: Acme\FooBundle\Twig\UserPostsCount 
    arguments: [@doctrine] 
    tags: 
     - { name: twig.extension } 

然後在模板:

{{ user_posts_count(app.user) }}

你也可以做到這一點作爲一個枝杈過濾器:

{{ app.user | count_posts }}

+0

感謝您的輸入。我用一些例子編輯了我的第一條消息。無論如何,我想我應該使用enitiry存儲庫,對吧?缺點是,我不明白爲什麼它不生成這個,但這是另一個問題:) –

+0

是的。在查詢數據庫時,您應該在存儲庫類中進行操作。 – qwertz

相關問題