From 3ce5b20aefb6273b02a5391b02a5b6ed1dba1f58 Mon Sep 17 00:00:00 2001 From: Marc Jauvin Date: Fri, 7 Oct 2022 10:48:42 -0400 Subject: [PATCH 1/2] document the $after argument of the extend() method --- database/model.md | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/database/model.md b/database/model.md index 977d3912..fce25088 100644 --- a/database/model.md +++ b/database/model.md @@ -675,7 +675,7 @@ Since models are [equipped to use behaviors](../services/behaviors), they can be Inside the closure you can add relations to the model. Here we extend the `Backend\Models\User` model to include a profile (has one) relationship referencing the `Acme\Demo\Models\Profile` model. ```php -\Backend\Models\User::extend(function($model) { +\Backend\Models\User::extend(function ($model) { $model->hasOne['profile'] = ['Acme\Demo\Models\Profile', 'key' => 'user_id']; }); ``` @@ -683,19 +683,32 @@ Inside the closure you can add relations to the model. Here we extend the `Backe This approach can also be used to bind to [local events](#events), the following code listens for the `model.beforeSave` event. ```php -\Backend\Models\User::extend(function($model) { +\Backend\Models\User::extend(function ($model) { $model->bindEvent('model.beforeSave', function() use ($model) { // ... }); }); ``` +It is also possible to have the provided callback execute after the model Behaviors have been loaded: + +```php +\System\Models\MailSetting::extend(function ($model) { + if ($model->methodExists('getSettingsRecord')) { + // the SettingsModel behavior's getSettingsRecord() method is only available after the behavior has been loaded. + } + if ($model->getTable() === 'system_settings') { + // the model table changes from 'mail_settings' to 'system_settings' after the behavior has loaded + } +}, after: true); +``` + > **NOTE:** Typically the best place to place code is within your plugin registration class `boot` method as this will be run on every request ensuring that the extensions you make to the model are available everywhere. Additionally, a few methods exist to extend protected model properties. ```php -\Backend\Models\User::extend(function($model) { +\Backend\Models\User::extend(function ($model) { // add cast attributes $model->addCasts([ 'some_extended_field' => 'int', From ff5c78c6bdd50cc675474d59c6f0e624326e6d76 Mon Sep 17 00:00:00 2001 From: Marc Jauvin Date: Sat, 8 Oct 2022 09:19:57 -0400 Subject: [PATCH 2/2] add ToC link to this section --- database/model.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/database/model.md b/database/model.md index fce25088..6e2664d7 100644 --- a/database/model.md +++ b/database/model.md @@ -690,6 +690,8 @@ This approach can also be used to bind to [local events](#events), the following }); ``` +### Extend after behaviors are loaded + It is also possible to have the provided callback execute after the model Behaviors have been loaded: ```php