Primer on the Laravel workflow - using service providers to add your own classes to the Laravel service container so they are easier to use.
- Let's say we created a class called S3 with a public method called listBuckets()
- Natively in PHP, you would access the method like this:
$s3 = new S3;
$s3->listBuckets();
- That is pretty easy, BUT it can get really complicated when you have to start passing in a lot of dependencies to a constructor everytime you want to use a class
- In a nutshell, a service provider is how you show Laravel how to create an object of your class, which dependencies to pass, and then it will do it for you automatically
- To register your class with the Laravel service container (App is the service container that is accessible by all classes), you have to create a service provider
- The service provider has a simple register() method that binds the class
- In config/app.php, there is a provider array and an alias array
- The service provider gets added to the providers array
- The alias gets added to the alias array
- Aliases are optional and just allow you to use classes statically like this:
AwsHelper::listBuckets();
- If you leave out the alias, you would have to use the class like this:
$s3 = App::make('awshelper');
$s3->listBuckets();
- If you choose not to use a service provider, you would have to call the method like this:
$s3 = new S3;
$s3->listBuckets();
When you use the AwsHelper::listBuckets() in your controller, you must have the name specified in two places:
- the namespace at the top of the file: use \AwsHelper;
- the alias array at config/app.php: 'AwsHelper' => App\Library\Aws\AwsHelperFacade::class,
Once you have the pointer to the facade file, you can use the getFacadeAccessor() method to return the name of the binding from the service provider file. You could actually have one service provider file with many different bindings, but you will need a separate facade file for each one of those bindings.
If you make a change to a service provider, the change won't be applied until you run: php artisan clear-compiled. The command essentially deletes bootstrap/cache/services.php. This is a known issue: laravel/framework#2760 (comment)