markdown Zend框架3:会话

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown Zend框架3:会话相关的知识,希望对你有一定的参考价值。

# Why use Zend Session over `$_SESSION`?
Zend provided a wrapper around PHP Session, it takes some pros:
- OOP, so you can use it consistently in your MVC application.
- Namespace, different models can store data without naming conflicts.
- Zend provided session validators, so it is more difficult for a mailicious user to hack.
- $_SESSION superglobal array makes testing your website more difficult.
- It is possible to implement custom data storages like Database, Redis, Memcached.

# Install
```bash
php composer.phar require zendframework/zend-session
```
# Config
```php
<?php
use Zend\Session\Storage\SessionArrayStorage;
use Zend\Session\Validator\RemoteAddr;
use Zend\Session\Validator\HttpUserAgent;

return [
    // Session Configuration
    'session_config' => [
        // Session cookie will expried in 1 hour.
        'cookie_lifetime' => 60*60*1,
        // Session data will be stored on server maximum for 30 days.
        'gc_maxlifetime' => 60*60*24*30,
    ].
    // Session manager configuration.
    'session_manager' => [
        'validators' => [
            // Session validators (use for security) 
            RemoteAddr::class,
            HttpUserAgent::class
        ],
    ],
    // Session storage configurations
    'session_storage' => [
        'type' => SessionArrayStorage::class
    ]
];
```
# Session Container
There are 2 methods for instanting Session Manager.
## Manual
```php
<?php
use Zend\SessionContainer;
use Zend\Session\SessionManager;
$sessionManager = $container->get(SessionManager::class);
$sessionContainer = new Container('ContainerNamspace', $sessionManager);
```
## Using Factory
```php
<?php
return [
    'session_containers' => [
        'ContainerNamespace',
        'Container\Namespace',
        'container_namespace'
    ]
];
```
# Some methods on `Container`
```php
$containerNamespace->offsetGet('userId'); // return '1'
$containerNamespace->offsetSet('userId', 1); // set userId as 1
$containerNamespace->offsetExists('userId'); // return truel of false
$containerNamespace->offsetUnset('userId'); // unset the key 'userId'
```
# Some methods on `SessionManager`
```php
$sessionManager->getId(); // return the id of session.
$sessionManager->setId('517ac3'); // set id for session.
$sessionManager->regenerateId(true); // re-generate session id.
$sessionManager->rememberMe(60*60*30); // cookie store 30 days.
$sessionManager->forgetMe(); // delete the cookie.
```

以上是关于markdown Zend框架3:会话的主要内容,如果未能解决你的问题,请参考以下文章

markdown Zend框架3:学说迁移

Zend 框架、会话和 HttpOnly

markdown Zend Framework 3:概述

markdown Zend Framework 3:身份验证

markdown Zend Framework 3:授权和RBAC

markdown Zend Framework 3:Controller插件管理器