How to pass session variable into layout for all controllers?

I wanted to render the user session information on the header of every page. At the moment the header is written as a layout and I unable to create a function in which every controller can call automatically so that the header can retrieve the session and display the user name.

My current method is to call a function in every action to render the name and it seems this is a dirty solution to me. Any help or approach on this will be greatly appreciated. Thanks.

Hello and welcome to the forums! :smiley:

You can use the Identity view helper from laminas-view. You only need to have a registered authentication service, then the view helper will use it.

Thanks for you comment. But I am not quite sure on how to use the Identity View Helper. Does the config have to be implemented into every module in order for it to work in layout? Thanks.

No, the configuration of all modules are merged when your application is started.
This means if you register the authentication service for example in your User module then you can fetch the service from the service-manager in all your modules and you can use the Identity view helper in any view or layout script.

I see. But for the layout, can we define a separate controller or a common controller which every actions in every modules will call upon the function automatically so that the code for the logic of displaying the login name is written only once? Thanks.

Exactly that can you solve with the Identity view helper.

A separate controller or common controller is the wrong direction. If some separate code or logic must be called in multiple or all actions then there are other ways to do this but never use a base or separate controller. In your case the view helper solves your problem. In many other case a listener is the best way.