0

I'm new to symfony2 and I've been trying to find the best way to call a controller from within another.

I have a list of events and I need an action to get all events and another action to get an event by ID but I don't want to keep repeating the doctrine calls each time I need to do this.

I thought about making a controller with all event actions and then calling the needed action from within other controllers each time I need it, if there is a better way to do it, I'm open for any suggestions.

thanks in advance.

Beirdo Studio
  • 43
  • 2
  • 2
  • 7

1 Answers1

4

If you have a piece of logic that should be reused, it probably doesn't belong in the controllers. You should try moving it to a service, which is easy to do.

In src/BundleName/Resources/config/services.yml:

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

Then, create BundleName\Service\ServiceName class (as shown in the docs) with the logic to be reused. An example below:

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;

    }

}

Then, in your actions, just call $this->get('service_name')->addProduct($array), or something like that.

Of course, if you want a controller action to be reused, you can use your controller as a service. I'd advice you to add a service layer, though.

Pedro Cordeiro
  • 2,085
  • 1
  • 20
  • 41
  • thanks for the quick answer, I think I'll do with services as you said. I'm not really bound to the controller embedding method, it was just the way I thought it should be done but yours sounds more convenient. – Beirdo Studio Feb 10 '14 at 13:52