markdown Zend Framework 3:用于身份验证服务的CurrentUser Filter和CurrentUser View Helper

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown Zend Framework 3:用于身份验证服务的CurrentUser Filter和CurrentUser View Helper相关的知识,希望对你有一定的参考价值。

# CurrentUser Plugin and CurrentUser View Helper
## CurrentUserPlugin
`User\Controller\Plugin\CurrentUserPlugin.php`
```php
namespace User\View\Helper;

use Doctrine\ORM\EntityManager;
use User\Entity\User;
use Zend\Authentication\AuthenticationService;
use Zend\View\Helper\AbstractHelper;

/**
 * This view helper is used for retrieving the User entity of currently logged in user.
 * @package User\View\Helper
 */
class CurrentUser extends AbstractHelper {

    /**
     * Entity Manager.
     * @var EntityManager
     */
    private $entityManager;

    /**
     * Authentication service.
     * @var AuthenticationService
     */
    private $authService;

    /**
     * Previously fetched User entity.
     * @var null
     */
    private $user = null;

    /**
     * CurrentUser constructor.
     * @param $entityManager
     * @param $authService
     */
    public function __construct($entityManager, $authService) {
        $this->entityManager = $entityManager;
        $this->authService = $authService;
    }

    /**
     * Return the current user or null if not logged in.
     * @param bool $userCachedUser
     * @return null
     * @throws \Exception
     */
    public function __invoke($userCachedUser = true)
    {
        // CHeck if User is already fetched previously.
        if ($userCachedUser && $this->user!==null)
            return $this->user;

        // Check if user is logged in.
        if ($this->authService->hasIdentity()) {

            // Fetch user entity from database.
            $this->user = $this->entityManager->getRepository(User::class)->findOneBy([
                'user' => $this->authService->getIdentity()
            ]);

            // Oops.. the identity presents in session, but there is no such user in database.
            // We throw an exception, because this is a possible security problem.
            if ($this->user == null)
                throw new \Exception('Not found user with such ID');

            // Return the User entity we found.
            return $this->user;
        }

        return null;
    }
}
```
## CurrentUserPluginFactory
```php
namespace User\Controller\Plugin\Factory;

use Interop\Container\ContainerInterface;
use User\Controller\Plugin\CurrentUserPlugin;
use Zend\Authentication\AuthenticationService;
use Zend\ServiceManager\Factory\FactoryInterface;

class CurrentUserPluginFactory implements FactoryInterface {

    public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
    {
        $entityManager = $container->get('doctrine.entitymanager.orm_default');
        $authService = $container->get(AuthenticationService::class);

        return new CurrentUserPlugin($entityManager, $authService);
    }
}
```
## Register CurrentUserPlugin
```php
use User\Controller\Plugin\CurrentUserPlugin;
use User\Controller\Plugin\Factory\CurrentUserPluginFactory;

return [
    'controller_plugins' => [
        'factories' => [
            CurrentUserPlugin::class => CurrentUserPluginFactory::class,
        ],
        'aliases' => [
            'currentUser' => CurrentUserPlugin::class,
        ]
    ],
]
```
## CurrentUser ViewHelper
```php
namespace User\View\Helper;

use Zend\View\Helper\AbstractHelper;
use User\Entity\User;

/**
 * This view helper is used for retrieving the User entity of currently logged in user.
 */
class CurrentUser extends AbstractHelper 
{
    /**
     * Entity manager.
     * @var Doctrine\ORM\EntityManager
     */
    private $entityManager;
    
    /**
     * Authentication service.
     * @var Zend\Authentication\AuthenticationService
     */
    private $authService;
    
    /**
     * Previously fetched User entity.
     * @var User\Entity\User
     */
    private $user = null;
    
    /**
     * Constructor. 
     */
    public function __construct($entityManager, $authService) 
    {
        $this->entityManager = $entityManager;
        $this->authService = $authService;
    }
    
    /**
     * Returns the current User or null if not logged in.
     * @param bool $useCachedUser If true, the User entity is fetched only on the first call (and cached on subsequent calls).
     * @return User|null
     */
    public function __invoke($useCachedUser = true)
    {
        // Check if User is already fetched previously.
        if ($useCachedUser && $this->user!==null)
            return $this->user;
        
        // Check if user is logged in.
        if ($this->authService->hasIdentity()) {
            
            // Fetch User entity from database.
            $this->user = $this->entityManager->getRepository(User::class)->findOneBy(array(
                'email' => $this->authService->getIdentity()
            ));
            if ($this->user==null) {
                // Oops.. the identity presents in session, but there is no such user in database.
                // We throw an exception, because this is a possible security problem. 
                throw new \Exception('Not found user with such ID');
            }
            
            // Return the User entity we found.
            return $this->user;
        }
        
        return null;
    }
}
```
## CurrentUserFactory
```php
namespace User\View\Helper\Factory;

use Interop\Container\ContainerInterface;
use User\View\Helper\CurrentUser;

class CurrentUserFactory
{
    public function __invoke(ContainerInterface $container)
    {        
        $entityManager = $container->get('doctrine.entitymanager.orm_default');
        $authService = $container->get(\Zend\Authentication\AuthenticationService::class);
                        
        return new CurrentUser($entityManager, $authService);
    }
}
```
## Register CurrentUser ViewHelper
```php
use User\View\Helper\CurrentUser;
use User\View\Helper\Factory\CurrentUserFactory;

return [
    'view_helpers' => [
        'factories' => [
            CurrentUser::class => CurrentUserFactory::class
        ],
        'aliases' => [
            'currentUser' => CurrentUser::class
        ]
    ]
];
```

以上是关于markdown Zend Framework 3:用于身份验证服务的CurrentUser Filter和CurrentUser View Helper的主要内容,如果未能解决你的问题,请参考以下文章

markdown Zend Framework 3:授权和RBAC

markdown Zend Framework 3:Controller插件管理器

markdown Zend Framework 3:RBAC的访问过滤器和访问视图助手

markdown Zend Framework 3:用于身份验证服务的CurrentUser Filter和CurrentUser View Helper

如何模拟 Zend\Form 提交而不在 Zend Framework 2/3 中显示表单?

如何模拟Zend Form提交而不在Zend Framework 2/3中显示表单?