Session Management ¶
The Symfony HttpFoundation component has a very powerful and flexible session subsystem which is designed to provide session management through a clear object-oriented interface using a variety of session storage drivers.
Sessions are used via the Session implementation of SessionInterface interface.
Caution
Make sure your PHP session isn't already started before using the Session class. If you have a legacy session system that starts your session, see Legacy Sessions.
Quick example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
use Symfony\Component\HttpFoundation\Session\Session;
$session = new Session();
$session->start();
// set and get session attributes
$session->set('name', 'Drak');
$session->get('name');
// set flash messages
$session->getFlashBag()->add('notice', 'Profile updated');
// retrieve messages
foreach ($session->getFlashBag()->get('notice', []) as $message) {
echo '<div class="flash-notice">'.$message.'</div>';
}
|
Note
Symfony sessions are designed to replace several native PHP functions.
Applications should avoid using session_start()
, session_regenerate_id()
,
session_id()
, session_name()
, and session_destroy()
and instead
use the APIs in the following section.
Note
While it is recommended to explicitly start a session, a session will actually start on demand, that is, if any session request is made to read/write session data.
Caution
Symfony sessions are incompatible with php.ini
directive session.auto_start = 1
This directive should be turned off in php.ini
, in the web server directives or
in .htaccess
.
Session API ¶
The Session class implements SessionInterface.
The Session has the following API, divided into a couple of groups.
Session Workflow ¶
- start()
-
Starts the session - do not use
session_start()
.セッションを開始します - session_start() は使用しないでください。 - migrate()
-
Regenerates the session ID - do not use
session_regenerate_id()
. This method can optionally change the lifetime of the new cookie that will be emitted by calling this method.セッション ID を再生成します。session_regenerate_id() は使用しないでください。このメソッドは、このメソッドを呼び出すことによって発行される新しい Cookie の有効期間をオプションで変更できます。 - invalidate()
-
Clears all session data and regenerates session ID. Do not use
session_destroy()
.すべてのセッション データを消去し、セッション ID を再生成します。 session_destroy() を使用しないでください。 - getId()
-
Gets the session ID. Do not use
session_id()
.セッション ID を取得します。 session_id() を使用しないでください。 - setId()
-
Sets the session ID. Do not use
session_id()
.セッション ID を設定します。 session_id() を使用しないでください。 - getName()
-
Gets the session name. Do not use
session_name()
.セッション名を取得します。 session_name() を使用しないでください。 - setName()
-
Sets the session name. Do not use
session_name()
.セッション名を設定します。 session_name() を使用しないでください。
Session Attributes ¶
The session attributes are stored internally in a "Bag", a PHP object that acts
like an array. They can be set, removed, checked, etc. using the methods
explained later in this article for the AttributeBagInterface
class. See
Session Management.
In addition, a few methods exist for "Bag" management:
- registerBag()
-
Registers a SessionBagInterface.
SessionBagInterface を登録します。
- getBag()
-
Gets a SessionBagInterface by
bag name.
バッグ名で SessionBagInterface を取得します。
- getFlashBag()
-
Gets the FlashBagInterface.
This is just a shortcut for convenience.
FlashBagInterface を取得します。これは便宜上のショートカットです。
Session Metadata ¶
- getMetadataBag()
-
Gets the MetadataBag
which contains information about the session.
セッションに関する情報を含む MetadataBag を取得します。
Session Data Management ¶
PHP's session management requires the use of the $_SESSION
super-global,
however, this interferes somewhat with code testability and encapsulation in an
OOP paradigm. To help overcome this, Symfony uses session bags linked to the
session to encapsulate a specific dataset of attributes or flash messages.
This approach also mitigates namespace pollution within the $_SESSION
super-global because each bag stores all its data under a unique namespace.
This allows Symfony to peacefully co-exist with other applications or libraries
that might use the $_SESSION
super-global and all data remains completely
compatible with Symfony's session management.
Symfony provides two kinds of storage bags, with two separate implementations. Everything is written against interfaces so you may extend or create your own bag types if necessary.
SessionBagInterface has the following API which is intended mainly for internal purposes:
- getStorageKey()
-
Returns the key which the bag will ultimately store its array under in
$_SESSION
. Generally this value can be left at its default and is for internal use.バッグが最終的にその配列を $_SESSION に格納するキーを返します。通常、この値はデフォルトのままにすることができ、内部で使用されます。 - initialize()
-
This is called internally by Symfony session storage classes to link bag data
to the session.
これは Symfony セッション ストレージ クラスによって内部的に呼び出され、バッグ データをセッションにリンクします。
- getName()
-
Returns the name of the session bag.
セッション バッグの名前を返します。
- clear()
-
Clears out data from the bag.
バッグからデータを消去します。
Attributes ¶
The purpose of the bags implementing the AttributeBagInterface is to handle session attribute storage. This might include things like user ID, and "Remember Me" login settings or other user based state information.
- AttributeBag
-
This is the standard default implementation.
これは、標準のデフォルトの実装です。
AttributeBagInterface has the API
- set()
-
Sets an attribute by name (
set('name', 'value')
).名前で属性を設定します (set('name', 'value'))。 - get()
-
Gets an attribute by name (
get('name')
) and can define a default value when the attribute doesn't exist (get('name', 'default_value')
).名前で属性を取得し (get('name'))、属性が存在しない場合にデフォルト値を定義できます (get('name', 'default_value'))。 - all()
-
Gets all attributes as an associative array of
name => value
.名前 => 値の連想配列としてすべての属性を取得します。 - has()
-
Returns
true
if the attribute exists.属性が存在する場合は true を返します。 - replace()
-
Sets multiple attributes at once using an associative array (
name => value
). If the attributes existed, they are replaced; if not, they are created.連想配列 (名前 => 値) を使用して一度に複数の属性を設定します。属性が存在する場合は、それらが置き換えられます。そうでない場合は作成されます。 - remove()
-
Deletes an attribute by name and returns its value.
名前で属性を削除し、その値を返します。
- clear()
-
Deletes all attributes.
すべての属性を削除します。
Example:
1 2 3 4 5 6 7 8 9 10 11 12 |
use Symfony\Component\HttpFoundation\Session\Attribute\AttributeBag;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\NativeSessionStorage;
$session = new Session(new NativeSessionStorage(), new AttributeBag());
$session->set('token', 'a6c1e0b6');
// ...
$token = $session->get('token');
// if the attribute may or may not exist, you can define a default value for it
$token = $session->get('attribute-name', 'default-attribute-value');
// ...
$session->clear();
|
Namespaced Attributes ¶
Any plain key-value storage system is limited in the extent to which
complex data can be stored since each key must be unique. You can achieve
namespacing by introducing a naming convention to the keys so different parts of
your application could operate without clashing. For example, module1.foo
and
module2.foo
. However, sometimes this is not very practical when the attributes
data is an array, for example a set of tokens. In this case, managing the array
becomes a burden because you have to retrieve the array then process it and
store it again:
1 2 3 4 5 6 |
$tokens = [
'tokens' => [
'a' => 'a6c1e0b6',
'b' => 'f4a7b1f3',
],
];
|
So any processing of this might quickly get ugly, even adding a token to the array:
1 2 3 |
$tokens = $session->get('tokens');
$tokens['c'] = $value;
$session->set('tokens', $tokens);
|
Flash Messages ¶
The purpose of the FlashBagInterface is to provide a way of setting and retrieving messages on a per session basis. The usual workflow would be to set flash messages in a request and to display them after a page redirect. For example, a user submits a form which hits an update controller, and after processing the controller redirects the page to either the updated page or an error page. Flash messages set in the previous page request would be displayed immediately on the subsequent page load for that session. This is however just one application for flash messages.
- AutoExpireFlashBag
-
In this implementation, messages set in one page-load will
be available for display only on the next page load. These messages will auto
expire regardless of if they are retrieved or not.
この実装では、1 つのページ読み込みで設定されたメッセージは、次のページ読み込みでのみ表示できます。これらのメッセージは、取得されるかどうかに関係なく、自動期限切れになります。
- FlashBag
-
In this implementation, messages will remain in the session until
they are explicitly retrieved or cleared. This makes it possible to use ESI
caching.
この実装では、メッセージは明示的に取得または消去されるまでセッションに残ります。これにより、ESIcaching を使用できるようになります。
FlashBagInterface has the API
- add()
-
Adds a flash message to the stack of specified type.
指定されたタイプのスタックにフラッシュ メッセージを追加します。
- set()
-
Sets flashes by type; This method conveniently takes both single messages as
a
string
or multiple messages in anarray
.タイプごとにフラッシュを設定します。このメソッドは、単一のメッセージを文字列として、または配列内の複数のメッセージを簡単に取得できます。 - get()
-
Gets flashes by type and clears those flashes from the bag.
タイプごとにフラッシュを取得し、それらのフラッシュをバッグからクリアします。
- setAll()
-
Sets all flashes, accepts a keyed array of arrays
type => [messages]
.すべてのフラッシュを設定し、配列 type => [messages] のキー付き配列を受け入れます。 - all()
-
Gets all flashes (as a keyed array of arrays) and clears the flashes from the bag.
すべてのフラッシュを (配列のキー付き配列として) 取得し、バッグからフラッシュをクリアします。
- peek()
-
Gets flashes by type (read only).
タイプ別にフラッシュを取得します (読み取り専用)。
- peekAll()
-
Gets all flashes (read only) as a keyed array of arrays.
すべてのフラッシュ (読み取り専用) を配列のキー付き配列として取得します。
- has()
-
Returns true if the type exists, false if not.
型が存在する場合は true、存在しない場合は false を返します。
- keys()
-
Returns an array of the stored flash types.
保存されているフラッシュ タイプの配列を返します。
- clear()
-
Clears the bag.
バッグをクリアします。
For simple applications it is usually sufficient to have one flash message per
type, for example a confirmation notice after a form is submitted. However,
flash messages are stored in a keyed array by flash $type
which means your
application can issue multiple messages for a given type. This allows the API
to be used for more complex messaging in your application.
Examples of setting multiple flashes:
1 2 3 4 5 6 7 8 9 10 11 12 |
use Symfony\Component\HttpFoundation\Session\Session;
$session = new Session();
$session->start();
// add flash messages
$session->getFlashBag()->add(
'warning',
'Your config file is writable, it should be set read-only'
);
$session->getFlashBag()->add('error', 'Failed to update name');
$session->getFlashBag()->add('error', 'Another error');
|
Displaying the flash messages might look as follows.
Display one type of message:
1 2 3 4 5 6 7 8 9 |
// display warnings
foreach ($session->getFlashBag()->get('warning', []) as $message) {
echo '<div class="flash-warning">'.$message.'</div>';
}
// display errors
foreach ($session->getFlashBag()->get('error', []) as $message) {
echo '<div class="flash-error">'.$message.'</div>';
}
|
Compact method to process display all flashes at once:
1 2 3 4 5 |
foreach ($session->getFlashBag()->all() as $type => $messages) {
foreach ($messages as $message) {
echo '<div class="flash-'.$type.'">'.$message.'</div>';
}
}
|