Literally me

Custom service for Laminas web app

Follow these simple steps to create a custom service for Laminas:

Code

namespace MyApp;

class MyService {
    public function hello($name) {
        return 'Hola ' . $name;
    }
}

Configuration

'service_manager' => [
    'factories' => [
        \MyApp\MyService::class => \Laminas\ServiceManager\Factory\InvokableFactory::class
    ]
]

Note

You can create your own factory class so as your object can access the service manager or do some special prepare for thereof. To make a factory class, just create a class with postfix Factory and implements from interface FactoryInterface.

namespace MyApp;

class MyServiceFactory implements \Laminas\ServiceManager\FactoryInterface {
    public function __invoke(\Interop\Container\ContainerInterface ContainerInterface $container, $requestedName, array $options = null) {
        ///$container is the service manager
        
        return new MyService();
    }
}

Usage

Now, you can access it via service manager.

$application->getServiceManager()->get(\MyApp\MyService::class);

Happy coding!