Literally me

Laminas delegator service

Delegator service is a wrapper service which houses the “real” service. This is useful when you want to “decorate” your service, do some extra stuff without changing the working one. Laminas supports multi delegator services for each service, and it follows the nested object structure.

This sample is base from this.

Code

The delegator service class, this will handle the stuff you want.

namespace MyApp;

class MyServiceDelegator extends \MyApp\MyService {
    protect $myservice;

    public function __construct(MyService $service) {
        $this->myservice = $service;
    }

    public function hello($name, $title = null) {
         if ($title == null) {
             $title = 'Ms. ';
         }
         
         $result = $this->myservice->hello($title . $name);

         return $result;
    }
}

The delegator factory class

namespace MyApp;

class MyServiceDelegatorFactory implements Laminas\ServiceManager\Factory\DelegatorFactoryInterface\DelegatorFactoryInterface  {
     public function __invoke(\Interop\Container\ContainerInterface $container, $name, callable $callback, array $options = null) {
         return new \MyApp\MyServiceDelegator($callback());
     }
 }

Configuration

'service_manager' => [
    ///Other service configuration
    ///...
    'delegators' => [
        \MyApp\MyService::class => [
            \MyApp\MyServiceDelegator::class
        ]
    ]
]

Usage

$application->getServiceManager()->get(\MyApp\MyService::class);///this returns \MyApp\MyServiceDelegator instead of \MyApp\MyService

Happy coding!