Lately, I've been creating only models for my L5 packages, but now I'd like to try and introduce a Controller as well. I've been following this but I always get the error "Class StatController does not exist"
.
Folder structure
/src
routes.php
/Controllers
StatController.php
StatController.php
<?php namespace Enchance\Sentrysetup\Controllers;
use App\Http\Controllers\Controller;
class StatController extends Controller {
public function index() {
return 'Moot.';
}
}
Service provider
public function register()
{
// Can't get this to work
include __DIR__.'/routes.php';
$this->app->make('Enchance\Sentrysetup\Controllers\StatController');
$this->app['sentrysetup'] = $this->app->share(function($app) {
return new Sentrysetup;
});
}
routes.php
Route::get('slap', 'StatController@index');
Does anyone have an alternate way of assigning a Controller to a L5 package?
You don't need to call
$this->app->make()
on your controllers. Controllers are resolved by Laravel's IoC automatically (meaning that Laravel creates / instantiates controllers automatically that are tied to routes).Require your routes in the
boot()
method of your packages service provider:And inside your
routes.php
file:Also, just a tip. You should PascalCase your namespaces:
Note the capital S in setup
The
boot()
method should be used to register your routes because when Laravel starts up, it goes through each service provider in yourconfig/app.php
file, creates them, calls theregister()
method (to insert/add any dependencies that the service provider "provides" into Laravel's singleton / IoC container).Think of Laravel's container as simply a big key => value array. Where the "key" is the name of the dependency (such as
config
), and the "value" is a closure (function () {}
) that is called to create the dependency:Once Laravel has registered each provider, it then goes through them again and calls the
boot()
method. This ensures that any dependencies that have been registered (inside of theregister()
method of all of your application service providers) is available in theboot()
method, ready to be used.The Service Provider Boot Method - Laravel Docs