Hello everyone!

We have been investing plenty of personal time and energy for many years to share our knowledge with you all. However, we now need your help to keep this blog running. All you have to do is just click one of the adverts on the site, otherwise it will sadly be taken down due to hosting etc. costs. Thank you.

This is an another example where we define routes for controllers in different folders. Don't forget to install sensio/framework-extra-bundle with composer.


Controller Structure


Assume that we are designing an API and have different route structure per version.


src/
├── Controller
│   └── DefaultController.php
├── v1
│   └── Controller
│   └── DefaultController.php
└── v2
└── Controller
└── DefaultController.php

config/services.yaml


services:
_defaults:
autowire: true
autoconfigure: true
public: false

App\:
resource: '../src/*'
exclude: '../src/{Kernel.php}'

App\Controller\:
resource: '../src/Controller'
tags: ['controller.service_arguments']

config/routes.yaml


home:
resource: ../src/Controller/
type: annotation
prefix: /

api_v1:
resource: ../src/v1/Controller/
type: annotation
prefix: /api/v1/

api_v2:
resource: ../src/v2/Controller/
type: annotation
prefix: /api/v2/

Routes


 ---------------------- -------- -------- ------ ---------- 
Name Method Scheme Host Path
---------------------- -------- -------- ------ ----------
app_default_index GET ANY ANY /
app_v1_default_index GET ANY ANY /api/v1/
app_v2_default_index GET ANY ANY /api/v2/
---------------------- -------- -------- ------ ----------

Controllers


Controller/DefaultController.php


declare(strict_types=1);

namespace App\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;

/**
* @Route("")
*/
class DefaultController
{
/**
* @Route("")
* @Method("GET")
*/
public function index()
{
return new Response('Home');
}
}

v1/Controller/DefaultController.php


declare(strict_types=1);

namespace App\v1\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;

/**
* @Route("")
*/
class DefaultController
{
/**
* @Route("")
* @Method("GET")
*/
public function index()
{
return new Response('Home v1');
}
}

v2/Controller/DefaultController.php


declare(strict_types=1);

namespace App\v2\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\HttpFoundation\Response;

/**
* @Route("")
*/
class DefaultController
{
/**
* @Route("")
* @Method("GET")
*/
public function index()
{
return new Response('Home v2');
}
}