In this article, we will create a service provider for all all of the custom hashing implementations that we created in previous articles. The articles about the hashing implementations can be found at these locations:
- Laravel: Implementing a CRYPT_STD_DES Hasher
- Laravel: Implementing a CRYPT_EXT_DES Hasher
- Laravel: Implementing a MD5 Hasher
- Laravel: Implementing a CRYPT_SHA256 Hasher
- Laravel: Implementing a CRYPT_SHA512 Hasher
To register all the Illuminate\Contracts\Hashing\Hasher
implementations with the application service container, we will create a new service provider named HashServiceProvider
in the app/Providers/
directory. The path (relative to the project directory) would then be app/Providers/HashServiceProvider.php
. The service provider itself will be fairly simple, just registering the implementations with a given name as singletons (some lines have been intentionally wrapped to improve readability):
1<?php
2
3namespace App\Providers;
4
5use Illuminate\Support\ServiceProvider;
6use Laravel\Artisan\Hashing\ExtendedDesHasher;
7use Laravel\Artisan\Hashing\StandardDesHasher;
8use Laravel\Artisan\Hashing\Md5Hasher;
9use Laravel\Artisan\Hashing\Sha256Hasher;
10use Laravel\Artisan\Hashing\Sha512Hasher;
11
12class HashServiceProvider extends ServiceProvider
13{
14 /**
15 * Indicates if loading of the provider is deferred.
16 *
17 * @var bool
18 */
19 protected $defer = true;
20 /**
21 * Register the service provider.
22 *
23 * @return void
24 */
25 public function register()
26 {
27 $this->app->singleton('hash.extDes',
28 function () { return new ExtendedDesHasher; });
29
30 $this->app->singleton('hash.des',
31 function () { return new StandardDesHasher; });
32
33 $this->app->singleton('hash.md5',
34 function () { return new Md5Hasher; });
35
36 $this->app->singleton('hash.sha256',
37 function () { return new Sha256Hasher; });
38
39 $this->app->singleton('hash.sha512',
40 function () { return new Sha512Hasher; });
41 }
42 /**
43 * Get the services provided by the provider.
44 *
45 * @return array
46 */
47 public function provides()
48 {
49 return [
50 'hash.extDes', 'hash.des', 'hash.md5'.
51 'hash.sha256', 'hash.sha512'
52 ];
53 }
54}
Each implementation has been bound according to the format hash.<hashName>
. This will be useful for our next step: creating a convenient hashing manager.
∎