User ID in all ViewModels

I am using Zend\Authentication\AuthenticationService

to control the current user. Now I want the object object to be available in all ViewModels by default without having to assign a user object in every controller action.

Is there a good way to do this? Or do I need to create a Factory for the ViewModels and enter a user id there? In this case, I would have to use the ServiceManager every time I wanted to create a ViewModel, which is not exactly sexy.

Is there a more elegant way? Can I somehow access the AuthenticationService directly from the ViewModel (i.e. the Template)?

+3


source to share


3 answers


Inspired by the answers of Okramius and Bram, I dive deeper into helping the ZF View helpers. And tadaa: As it turns out, the ZF2 already comes with a helper for accessing the user ID in any view model. The view assistant is simply called identity

.

For it to work, you need to add Zend\Authentication\AuthenticationService

to the list of classes to be called (there is no hint why this is not the default) eg. in config / autoload / global.php file:

return array(
    'service_manager' => array(
        'invokables' => array(
            'Zend\Authentication\AuthenticationService' => 'Zend\Authentication\AuthenticationService',
        ),
    ),
);

      



After that, you can easily access the id of the current user from any template:

<p>Hello <?php echo $this->identity()->getName() ?></p>

      

Thanks again to Okramus for getting me on the right track! If you don't use Zend \ Authentication \ AuthenticationService, his answer still applies.

+4


source


See how it works ZfcUser

. Instead of entering an identity variable in all views, it allows you to see a helper for accessing the authentication service.

For this, the authentication service is injected into the view helper through the factory service .



This basically allows you to use something like the following in any of your browsing scripts:

echo $user = $this->zfcUserIdentity();

echo $user ? $user->getUsername() : 'Not logged in!';

      

+2


source


You should create a view helper that retrieves the user model from the authentication service. See the ZfcUser example for an example. Perhaps you can use the ZfcUser module for your use.

0


source







All Articles