Created
July 27, 2020 17:48
-
-
Save nhalstead/db7f75f25fb73b99f501ca3cf2354eb5 to your computer and use it in GitHub Desktop.
Laravel BootingTraits
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Traits; | |
/** | |
* This is a copy of code from Illuminate\Database\Eloquent\Model | |
* that allows traits to be booted and initialized. | |
* | |
* These functions are on the trait its self and allow for an initialization | |
* to take place. | |
* | |
* This allows classes to add traits and inherit trait boots. | |
* On trait boot (static) you can set default values or register global listeners etc. | |
* On trait initialize you can manipulate the current instance. | |
* | |
* Uses a Laravel specific function `class_uses_recursive` | |
* - src/Illuminate/Support/helpers.php | |
* - vendor/laravel/framework/src/Illuminate/Support/helpers.php | |
*/ | |
trait BootingTraits | |
{ | |
/** | |
* The array of booted models. | |
* | |
* @var array | |
*/ | |
protected static $booted = []; | |
/** | |
* The array of trait initializers that will be called on each new instance. | |
* | |
* @var array | |
*/ | |
protected static $traitInitializers = []; | |
/** | |
* Boot Traits if not Booted | |
*/ | |
public function __construct() | |
{ | |
$this->bootIfNotBooted(); | |
$this->initializeTraits(); | |
} | |
/** | |
* Check if the model needs to be booted and if so, do it. | |
* | |
* @return void | |
*/ | |
protected function bootIfNotBooted() | |
{ | |
if (! isset(static::$booted[static::class])) { | |
static::$booted[static::class] = true; | |
static::bootTraits(); | |
} | |
} | |
/** | |
* Boot all of the bootable traits on the model. | |
* | |
* @return void | |
*/ | |
protected static function bootTraits() | |
{ | |
$class = static::class; | |
$booted = []; | |
static::$traitInitializers[$class] = []; | |
foreach (class_uses_recursive($class) as $trait) { | |
$method = 'boot'.class_basename($trait); | |
if (method_exists($class, $method) && ! in_array($method, $booted)) { | |
forward_static_call([$class, $method]); | |
$booted[] = $method; | |
} | |
if (method_exists($class, $method = 'initialize'.class_basename($trait))) { | |
static::$traitInitializers[$class][] = $method; | |
static::$traitInitializers[$class] = array_unique( | |
static::$traitInitializers[$class] | |
); | |
} | |
} | |
} | |
/** | |
* Initialize any initializable traits on the model. | |
* | |
* @return void | |
*/ | |
protected function initializeTraits() | |
{ | |
foreach (static::$traitInitializers[static::class] as $method) { | |
$this->{$method}(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment