2014-02-10 130 views
0

我是symfony2的新手,我一直在试图找到从另一个控制器中调用控制器的最佳方法。来自另一个控制器的Symfony2呼叫控制器

我有一个事件列表,我需要一个动作来获取所有事件和另一个动作来通过ID获取一个事件,但是我不想每次都需要重复这个教条调用。

我想过如何使用所有事件动作制作一个控制器,然后在每次需要时从其他控制器中调用所需的动作,如果有更好的方法可以做到这一点,我愿意接受任何建议。

在此先感谢。

+3

http://stackoverflow.com/questions/15827384/how-to-access-a-different-controller-from-inside-a-controller-symfony2 –

回答

4

如果你有一块应该重用的逻辑,它可能不属于控制器。您应该尝试将其移动到服务上,这很容易实现。

在SRC/BUNDLENAME /资源/配置/ services.yml:

services: 
    service_name: 
     class:  BundleName\Service\ServiceName 
     arguments: [@doctrine.orm.default_entity_manager] 

然后,创建BUNDLENAME \服务\服务名称类(as shown in the docs)与待重新使用的逻辑。下面的例子:

class ServiceName { 

    protected $entityManager; 

    public function __construct($entityManager) { 
     $this->entityManager = $entityManager; 
    } 

    public function addProduct($product) { 
     //Get the array, hydrate the entity and save it, at last. 
     //... 
     $entity = new Product(); 
     //... 
     $this->entityManager->persist($entity); 
     $this->entityManager->flush($entity); 
     return $entity; 

    } 

} 

然后,在你的行动,只需拨打$this->get('service_name')->addProduct($array),或类似的东西。

当然,如果你想要一个控制器动作被重用,you can use your controller as a service。不过,我建议你添加一个服务层。

+0

感谢您的快速回答,我想我会做如你所说的服务。我并不是真的被控制器嵌入方法所束缚,它只是我认为应该完成的方式,但是你的听起来更加方便。 –