1

I'm transitioning a Kohana application to Symfony2. In Kohana I had to register a custom autoloader to make the framework see my controllers given my preferred directory structure. Is there an elegant way in Symfony2 to achieve routing to controllers where the "Controller" directory is a level lower. For example. Src/Somename/aBundle/Theme/Frontend/Controller/defaultController.php

2 Answers 2

2

You can place your controllers wherever you want, just import them in your routing.yml:

controller:
    resource: @MyBundle/Theme/Frontend/Controller/
    type: annotation

Of course, this is only an example. You can find more information and plenty of examples on routing here: http://symfony.com/doc/current/book/routing.html

Sign up to request clarification or add additional context in comments.

5 Comments

Ok, I added the proper resource string and now it finds my controllers namespace. But I still do not understand how to create the route so that it connects to the controller.
For your example what would the _controller parameter of the route look like in routing.yml ?
Edit, ok I got it. Thank you !! Stupid me I didn't add the annotation to the controller :) eg. /** * @Route("/test") */ But is there a way to do custom routing like this using yaml instead of annotations?
It depends on the type in the routing.yml definition. You can use the _controller if you want, but I suggest using annotations as it's more clear and easy to maintain. Also, you can avoid putting the @Route annotation in the controller itself by using the prefix in the routing.yml.
Well maybe I'm wrong but it seems like (based on error messages) when I use the _controller param controllers are searched for immediately under the bundle directory. But I will experiment more with the type attribute. Thank you for your help, annotations seem to be a better system anyway.
0

Its not possible using the _controller key of a YAML resource file. This is the Symfony2 code that is executed:

//classes.php, parse method

 $try = $b->getNamespace() . '\\Controller\\' . $controller . 'Controller'; 
 if (class_exists($try)) {
      return $try . '::' . $action . 'Action';
 }

As you can see "Controller" is concatenated after the Bundle namespace. Autoloading will use the namespace as a file path and the controller will never be found.

If your using _Controller your controllers must be under the "Controller" folder that is immediately inside your Bundle directory.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.