Last active
May 14, 2018 12:05
-
-
Save rogercbe/71718c028eae977f18f71d0b6e70b01c to your computer and use it in GitHub Desktop.
Abstract code generation to a trait
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; | |
| use App\Support\Traits\GenerateUniqueCode; | |
| use App\Support\Contracts\GeneratesCodes; | |
| use Illuminate\Database\Eloquent\Model; | |
| class Lead extends Model implements GeneratesCodes | |
| { | |
| use GenerateUniqueCode; | |
| // Override | |
| protected static function getCodeName() | |
| { | |
| return 'lead_code'; | |
| } | |
| /** | |
| * Logic to generate a new code. | |
| * | |
| * @return string | |
| */ | |
| protected function generateCode() | |
| { | |
| return strtoupper(substr(md5(str_random(16)), 0, 8)); | |
| } | |
| } |
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\Support\Contracts; | |
| interface GeneratesCodes | |
| { | |
| /** | |
| * Logic to generate a code. | |
| * | |
| * @return mixed | |
| */ | |
| function generateCode(); | |
| } |
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 | |
| trait GenerateUniqueCode | |
| { | |
| /** | |
| * Boot the trait. | |
| */ | |
| protected static function bootGenerateUniqueCode() | |
| { | |
| static::creating(function ($model) { | |
| $model->attributes[static::getCodeName()] = $model->generateUniqueCode(); | |
| }); | |
| } | |
| /** | |
| * Determine the name of the code column. | |
| * | |
| * @return string | |
| */ | |
| protected static function getCodeName() | |
| { | |
| return 'code'; | |
| } | |
| /** | |
| * Make sure the code is unique for the model. | |
| * | |
| * @return string | |
| */ | |
| protected function generateUniqueCode() | |
| { | |
| $code = $this->generateCode(); | |
| while (static::where(static::getCodeName(), $code)->exists()) { | |
| $code = $this->generateCode(); | |
| } | |
| return $code; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment