Skip to content

Instantly share code, notes, and snippets.

@JordanDalton
Last active August 27, 2019 19:00
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JordanDalton/113315afb2c35a6ca5bf to your computer and use it in GitHub Desktop.
Save JordanDalton/113315afb2c35a6ca5bf to your computer and use it in GitHub Desktop.
Here's a nice, common App Service Provider I created and use in 100% of my applications. It provides a simple way to define and bind contracts, define model observers as well as extend form validation extension.
<?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Validator;
class AppServiceProvider extends ServiceProvider
{
/**
* List of contracts that will need to be bound to their implementation.
*
* @var array
*/
protected $contracts_to_bind = [
// Repositories
// 'Repositories\\UserRepository',
];
/**
* List of models that will need to be observed.
*
* @var array
*/
protected $models_to_observe = [
// 'User'
];
/**
* List if custom validator extensions to register.
*
* @var array
*/
protected $custom_validator_extensions_to_register = [
// 'validation_name' => 'SomeClass@method'
];
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
$this->bindContractsToImplementations();
$this->observeModels();
$this->registerCustomValidatorExtensions();
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
/**
* Bind contracts to their implementation.
*
* @return void
*/
public function bindContractsToImplementations()
{
foreach( $this->contracts_to_bind as $bindable )
{
$contract = "\\App\\Contracts\\{$bindable}";
$implementation = "\\App\\{$bindable}";
app()->bind( $contract , $implementation );
}
}
/**
* Assign observer to model.
*
* @return void
*/
public function observeModels()
{
foreach( $this->models_to_observe as $model )
{
$eloquentModel = "\\App\\{$model}";
$oberverClass = "\\App\\Observers\\{$model}Observer";
$eloquentModel::observe( $oberverClass );
}
}
/**
* Register a custom validator extensions.
*
* @return void
*/
public function registerCustomValidatorExtensions()
{
foreach( $this->custom_validator_extensions_to_register as $name => $action )
{
Validator::extend( $name , $action );
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment