pioniro/wrapper-bundle

Wraps your symfony services

Installs: 0

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 1

Forks: 0

Open Issues: 0

Type:symfony-bundle

1.0.1 2024-11-16 07:14 UTC

This package is auto-updated.

Last update: 2025-02-16 07:49:30 UTC


README

This is a wrapper bundle for the Symfony framework.

Main goal of this bundle is to provide a simple way to create a wrappers for the services.

Under the hood, this bundle performs code generation similar to how Doctrine does for entity proxying.

Installation

composer require pioniro/wrapper-bundle

Usage

You can see the example of usage in the example directory.

Create an annotation

<?php

/**
* @Annotation
 */
class LogException implements \Pioniro\WrapperBundle\AnnotationInterface
{
}

Create a handler

<?php
class LogExceptionHandler implements \Pioniro\WrapperBundle\HandlerInterface
{
    public function __construct(private \Psr\Log\LoggerInterface $logger) {}

    public function handle(callable $next, array $args, AnnotationInterface $annotation): callable
    {
        return function ($input) use ($next) {
            try{
                return $next($input);
            } catch (\Throwable $exception) {
                $this->logger->error($exception->getMessage(), compact('exception'));
                throw $exception;
        }
    }

    public static function handledClass(): string
    {
        return LogException::class;
    }
}

Annotate a service

<?php

class MyService
{
    #[LogException]
    public function doSomethingWithPHP8(): void
    {
        throw new \Exception('Something went wrong');
    }

    /**
    * @LogException
    */
    protected function doSomethingWithPHP7(): void
    {
        throw new \Exception('Something went wrong');
    }
}

Register the handler

services:
    App\Handler\LogException:
        tags:
            - { name: wrapper.handler }

OR

services:
    _instanceof:
        Pioniro\WrapperBundle\HandlerInterface:
            tags: ['wrapper.handler']

Enjoy

And now, when you call doSomethingWithPHP8 or doSomethingWithPHP7 method, the exception will be logged.

You can create as many handlers as you want and use them in your services.

Limitations

  • Handlers are not called for private, static or final methods.
  • Handlers are not called for methods of the final classes.
  • Handlers are not called for methods of the classes that are not in the container.
  • May occur strange errors if you use static keyword (for example in the Command) in the annotated hierarchy.
  • Using other annotations in the same class may lead to unexpected behavior (e.g. if you use @Route or @Template annotations in the same class, these annotation may not work as expected)