0

I am making a controller for each type of request post/put/get.

So my question now is, what is the best way to put controllers in subfolders when using L 4.2 ?

/controllers/subfolders..

I've seen some people using namespacing and some people simply makes a subfolder and put their controllers in it then run composer dump autoload-

But is there any "best practice" way to do it in L 4.2?

user2722667
  • 8,195
  • 14
  • 52
  • 100

1 Answers1

2

I do it the namespace way. One advantage this gives is that we can have same named classes inside the folders. Currently in a Laravel 4.2 app that I'm building, I am using controllers/api subfolder, with the namespace of Api for all the classes in it. And one of the classes is UsersController. Which might also be used for the frontend website, so now you will have to say FrontendUsersController, or something weird and long. So to avoid this, better get in shape with namespaced controllers.

Also, Laravel 5 advocates namespacing for your project, so does PSR standard. So this is probably much better way in the long run.

Sameer Nyaupane
  • 782
  • 8
  • 9
  • Thanks for you response @Sameer Nyaupane But how do I use namespaces in controllers? Do I have to write use "the folder" and call the controller by the whole path? Sry never used it so I am new to this – user2722667 Mar 27 '15 at 10:55
  • Is it like this: In /controllers/Subfolder I make my controller: – user2722667 Mar 27 '15 at 10:58
  • You're welcome. Yes I was writing a response but then you already replied yourself :D, and yes that is exactly how you do it. And when you use it form a route you should call it like `Route::get('myroute-path', 'Subfolder\MainController@mymethod');` Yes, once you make any changes to your directory structure, you need to do a `composer dumpautoload` inside your laravel project path. – Sameer Nyaupane Mar 27 '15 at 11:00
  • sorry for asking again @Sameer Nyaupane , but I seen some diffrent ways to write the controller. Should i write use BaseController; somecontroller extends BaseController {} or can I simply write: somecontroller extends \BaseController {} Without the "use BaseController;" part – user2722667 Mar 27 '15 at 15:22
  • I would suggest you to make a new base controller for each namespace. What I mean is, if you are using `controllers/subfolder` , then you can have a `SubfolderController` which extends Controller. And inside `SubfolderController` , use the Subfolder namespace. This way, all other classes that use this namespace, will automatically have access to `SubfolderController`, without using \ or use. So bascially our `BaseController` is `SubfolderController`. :) – Sameer Nyaupane Mar 28 '15 at 04:27