91 lines
1.6 KiB
Markdown
91 lines
1.6 KiB
Markdown
|
# Observers
|
||
|
|
||
|
Observers maybe used for creating and clearing cache purposes
|
||
|
|
||
|
## Example observe use
|
||
|
|
||
|
Create you own class with observer:
|
||
|
|
||
|
```php
|
||
|
<?php namespace Dimti\Mirsporta\Classes\Observers;
|
||
|
|
||
|
use Dimti\Mirsporta\Models;
|
||
|
use Wpstudio\Helpers\Classes\Observer\BaseObserver;
|
||
|
|
||
|
class TagObserver extends BaseObserver
|
||
|
{
|
||
|
public static function getClass(): string
|
||
|
{
|
||
|
return Models\Tag::class;
|
||
|
}
|
||
|
}
|
||
|
```
|
||
|
|
||
|
Use in models:
|
||
|
|
||
|
```php
|
||
|
<?php namespace Dimti\Mirsporta\Models;
|
||
|
|
||
|
use Dimti\Mirsporta\Classes\Observers;
|
||
|
|
||
|
class Tag extends Model
|
||
|
{
|
||
|
//...
|
||
|
|
||
|
public function afterSave()
|
||
|
{
|
||
|
Observers\TagObserver::clearCache();
|
||
|
}
|
||
|
|
||
|
//...
|
||
|
}
|
||
|
```
|
||
|
|
||
|
And in your code for caching data based on this model/observer:
|
||
|
|
||
|
```php
|
||
|
use Dimti\Mirsporta\Classes\Observers;
|
||
|
//...
|
||
|
|
||
|
$cacheTags = Observers\TagObserver::getCacheTag();
|
||
|
|
||
|
$cacheKey = CacheManager::formatCacheKey([__CLASS__, __METHOD__, $siteId]);
|
||
|
|
||
|
\Cache::tags($cacheTags)->rememberForever($cacheKey, fn() =>
|
||
|
Models\Tag::all()
|
||
|
));
|
||
|
```
|
||
|
|
||
|
* CacheManager::formatCacheKey - that is simple helper for concatenate array elements to string
|
||
|
|
||
|
## Clearing cache from admin dashboard widget
|
||
|
|
||
|
### Template
|
||
|
|
||
|
```html
|
||
|
<input
|
||
|
type="button"
|
||
|
class='btn btn-primary'
|
||
|
value="Clear tag model cache"
|
||
|
data-request="<?= $this->getEventHandler('onClearTagCache') ?>"
|
||
|
data-request-success="$.oc.flashMsg({text: 'Cache of tag model is clearing', 'class': 'success', 'interval': 5}); return false;"
|
||
|
/>
|
||
|
```
|
||
|
|
||
|
### Controller widget action
|
||
|
|
||
|
```php
|
||
|
use Dimti\Mirsporta\Classes\Observers;
|
||
|
|
||
|
//...
|
||
|
|
||
|
public function onClearTagCache()
|
||
|
{
|
||
|
Observers\TagObserver::clearCache();
|
||
|
|
||
|
return ['status' => 1];
|
||
|
}
|
||
|
|
||
|
//...
|
||
|
```
|