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!

#[Log(level: 'info', logArgs: true, channel: 'stack')]

#[Cache(ttl: 3600, store: 'redis', tags: ['users'], prefix: 'u:')]

#[Retry(times: 3, delay: 100, backoff: 2.0, catch: [ServiceException::class])]

#[RateLimit(maxAttempts: 5, decaySeconds: 60, key: 'my-bucket')]

#[Transactional(connection: 'mysql', attempts: 2)]

#[Validate(['id' => '

#[Deprecated('Use newMethod() instead.')]

#[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;
        };
    }
}

// config/decorators.php
return [
    'decorate' => [
        App\Contracts\PaymentProcessor::class,
    ],
];

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;
        };
    }
}
bash
php artisan vendor:publish --tag="decorators-config"