Tag: view helper

  • Laminas View Helper

    Laminas View Helper

    No need to say, just follow these steps below:

    Code

    namespace MyApp;
    
    class MyHelper extends \Laminas\View\Helper\AbstractHelper {
        public function __invoke() {
            return $this;
        }
    
        public function say() {
            return 'Bonjour!';
        }
    }

    Configuration

    'view_helpers' => [
        'aliases' => [
            'myhelper' => \MyApp\MyHelper::class
        ],
        'factories' => [
            \MyApp\MyHelper::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 AbcFactory implements \Laminas\ServiceManager\FactoryInterface {
        public function __invoke(\Interop\Container\ContainerInterface ContainerInterface $container, $requestedName, array $options = null) {
            ///$container is the service manager
            
            return new MyHelper();
        }
    }

    Usage

    In view scripts:

    $this->myhelper();//return MyHelper object
    $this->myhelper()->say();//quick access to member function

    In other view helpers:

    $this->view->myhelper();//return MyHelper object
    $this->view->myhelper()->say();//quick access to member function

    Happy coding!