Reputation: 1206
To organize my controllers, I would like to sort them in folders. For example, I have an admin panel that utilizes many controllers that I don't want mixed up with the other controllers. I moved those controllers in a folder in my /controllers directory.
So my structure looks like this:
controllers /
BaseController.php
HomeController.php
admin /
AdminController.php
Now my admin controller looks like this:
namespace Admin;
class AdminController extends \BaseController {
public function getHome() {
return \View::make('admin.home');
}
}
Then I can do a grouped route for my admin panel:
Route::group(['namespace' => 'Admin'], function() {
Route::get('admin', ['as' => 'admin', 'uses' => 'AdminController@getHome']);
});
There's absolutely nothing wrong with this however, I find it a nuisance having to namespace every class in these controllers using \
. Is there I way I can eliminate the use of having to namespace every class in these controllers under admin? For example, I don't want to type \View::make()
, I want to have View::make()
.
Upvotes: 1
Views: 3069
Reputation: 7578
Looks like you want your controller classes to still be in the global namespace but want the ability to organize them into folders.
If you look in your composer.json
, you'll see that the default controllers folder is autoloaded by "classmap" to the folder directly. So you may add additional folders to the list. Like this:
"autoload": {
"classmap": [
"app/commands",
"app/controllers",
"app/controllers/admin", <-- additional folders
"app/models",
"app/database/migrations",
"app/database/seeds",
]
},
Notice that I added "app/controllers/admin"
into the classmap
array. You can add as many as you want. Then do a composer dump-autoload
.
Another way of doing the same approach is to modify your app/start/global.php
:
ClassLoader::addDirectories(array(
app_path().'/commands',
app_path().'/controllers',
app_path().'/controllers/admin', // additional folders
app_path().'/models',
app_path().'/helpers',
app_path().'/database/seeds',
));
AFAIK, this gives the same effect as modifying composer.json
file, with exception that you do not need to do any composer
commands after adding a new path.
Note that the whole answer above will work well if you do not expect your code to grow considerably larger. Imagine having to maintain tens of controller folders this way, also the risk of class names clashing.
Upvotes: 3