petekaner
petekaner

Reputation: 8901

How to use controllers as services configuring the routing in yaml without annotations

So far I've been using annotations for my routes but for a new project I'd to start using yaml routes instead.

The problem is I don't know how to use controllers as services by doing that. I have my controller:

final class SuspendController extends Controller
{

    /** @var UserManagerInterface */
    private $userManager;

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

    /**
     * @return Response
     */
    public function suspendAction() : Response
    {
        /** @var User $user */
        $user = $this->getUser();

        $user->setStatus(User::STATUS_SUSPENDED);

        $this->get('fos_user.user_manager')->updateUser($user);

        return $this->redirectToRoute('fos_user_security_logout');
    }
}

My routing.yml:

suspend_session:
    path:      /suspend
    defaults:  { _controller: UserBundle:Suspend:suspend }

And I include the following services definition:

services:

  controller.suspend_account:
      class: UserBundle\Controller\SuspendController
      arguments:
          - '@fos_user.user_manager'

The problem is that the fos_user_manager never gets injected in the controller. Is there any annotation that I should include in the routing to specify that that controller is a service (something equivalent to the @Route service annotation)?

Upvotes: 1

Views: 177

Answers (2)

Matteo
Matteo

Reputation: 39380

if you user the Controller as a Service, you can't use the helper method getUser of the base class because you haven't yet the container injected. For redirect Route you need the router dependencies also.

So you should inject all the necessary dependency (also the token manager) and dial with them.

  controller.suspend_account:
      class: UserBundle\Controller\SuspendController
      arguments:
          - '@fos_user.user_manager'
          - '@router'
          - '@security.token_storage'

Then your implementation looks like this:

/**
 * @return Response
 */
public function suspendAction() : Response
{
    /** @var User $user */
    $user = $this->securityTokenStorage->getToken()->getUser();

    $user->setStatus(User::STATUS_SUSPENDED);

    $this->userManager->updateUser($user);

    return $this->redirect($this->router->generate('fos_user_security_logout'), 200);
}

EDIT:

Then define the route as follow:

suspend_session:
    path:      /suspend
    defaults:  { _controller: controller.suspend_account:suspendAction  }

As described in the doc.

Hope this help

Upvotes: 2

Rooneyl
Rooneyl

Reputation: 7902

You need to change your routing to include the full controller function.
E.g.

suspend_session:
    path:      /suspend
    defaults:  { _controller: UserBundle:Suspend:suspendAction }

Upvotes: 0

Related Questions