PHP code example of mykemeynell / laravel-decorators
1. Go to this page and download the library: Download mykemeynell/laravel-decorators library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
mykemeynell / laravel-decorators example snippets
namespace App\Services;
use MykeMeynell\Laravel\Decorators\Decorators\Log;
use MykeMeynell\Laravel\Decorators\Decorators\Cache;
class UserService
{
#[Log]
#[Cache(ttl: 3600)]
public function findUser(int $id): array
{
return User::findOrFail($id)->toArray();
}
}
use MykeMeynell\Laravel\Decorators\Facades\Decorator;
use App\Services\UserService;
$service = Decorator::make(UserService::class);
$user = $service->findUser(1); // Call is logged and cached!
#[DecorateWith(MyCustomWrapper::class)]
#[DecorateWith('App\Decorators\MyDecorator::handle')]
#[DecorateWith('my_global_decorator_function')]
public function myMethod() { ... }
class MyCustomWrapper
{
public function __invoke(callable $next): callable
{
return function (array $args) use ($next) {
// Pre-processing
$result = $next($args);
// Post-processing
return $result;
};
}
}
namespace App\Decorators;
use Attribute;
use MykeMeynell\Laravel\Decorators\Contracts\MethodDecorator;
#[Attribute(Attribute::TARGET_METHOD)]
class MyCustomDecorator implements MethodDecorator
{
public function wrap(callable $next, array $context = []): callable
{
return function (array $args) use ($next) {
// Logic before
$result = $next($args);
// Logic after
return $result;
};
}
}