diff --git a/developer_manual/basics/controllers.rst b/developer_manual/basics/controllers.rst index a0c5b975f6c..9865341825d 100644 --- a/developer_manual/basics/controllers.rst +++ b/developer_manual/basics/controllers.rst @@ -212,87 +212,130 @@ Headers, files, cookies and environment variables can be accessed directly from } -Why should those values be accessed from the request object and not from the global array like $_FILES? Simple: `because it's bad practice `_ and will make testing harder. +Why should those values be accessed from the request object and not from the global array like $_FILES? Simple: +`because it's bad practice `_ and will make testing harder. .. _controller-use-session: -Reading and writing session variables -^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +Sessions and session variables +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +Introduction +~~~~~~~~~~~~ + +Sessions allow your application to store data specific to a particular user across multiple HTTP +requests. Variables are saved server-side and tied to a unique session identifier managed via a +browser cookie. + +Nextcloud uses PHP’s native session handling but adds several performance optimizations and a +transparent encryption layer via the ``CryptoSessionData`` class. Data written through the +``OCP\ISession`` API benefits from these optimizations and is automatically encrypted at rest. + +.. danger:: + Never use PHP superglobals like ``$_SESSION``. This bypasses Nextcloud's encryption and + lifecycle management. leading to race conditions or lost data. -To set, get or modify session variables, the ISession object has to be injected into the controller. +Basic usage +~~~~~~~~~~~ -Nextcloud will read existing session data at the beginning of the request lifecycle and close the session afterwards. This means that in order to write to the session, the session has to be opened first. This is done implicitly when calling the set method, but would close immediately afterwards. To prevent this, the session has to be explicitly opened by calling the reopen method. +Inject the :class:`OCP\\ISession` object via your controller's constructor. -Alternatively, you can use the ``#[UseSession]`` attribute to automatically open and close the session for you. +A more complete example: .. code-block:: php - :emphasize-lines: 2,7 + + session->get('last_visit'); + return new Response(); + } - .. code-block:: php - :emphasize-lines: 2 + // Default: Implicit locking per write. Good for single operations. + public function simpleWrite(): Response { + $this->session->set('last_visit', time()); + return new Response(); + } - /** - * @UseSession - */ - public function writeASessionVariable(): Response { - // .... + // Optimization: Keeps session open for the entire method. + #[UseSession] + public function batchUpdate(): Response { + $this->session->set('theme', 'dark'); + $this->session->set('font_size', '14px'); + $this->session->remove('fallback_theme'); + return new Response(); } + } +When to use ``#[UseSession]`` +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -In case the session may be read and written by concurrent requests of your application, keeping the session open during your controller method execution may be required to ensure that the session is locked and no other request can write to the session at the same time. When reopening the session, the session data will also get updated with the latest changes from other requests. Using the annotation will keep the session lock for the whole duration of the controller method execution. +By default, Nextcloud uses an **on-demand locking strategy**: it closes the session immediately after the +request starts to allow high concurrency, then briefly re-opens and closes it only during a ``set()`` or +``remove()`` call. This default "close-early" behavior works for infrequent and standalone writing events +and prevents one request from blocking another. Developers do not need to do anything special to enable +this behavior. -For additional information on how session locking works in PHP see the article about `PHP Session Locking: How To Prevent Sessions Blocking in PHP requests `_. +However, in more advanced scenarios (e.g., calling ``set()`` five times in immediate succession) Nextcloud's +default behavior means the session will open and close five times. This introduces significant I/O +overhead (even if it does minimize locking). For these cases, Nextcloud supports an optional method-level +attribute: ``#[UseSession]``. This attribute ensures the session is opened once at the start of your method and +closed at the end, providing efficiency and correct locking in complex workflows. -Then session variables can be accessed like this: +Use the ``#[UseSession]`` attribute when: -.. note:: The session is closed automatically for writing, unless you add the ``#[UseSession]`` attribute! +* **Multiple Writes**: You are calling ``set()`` or ``remove()`` multiple times in one method (prevents + I/O overhead from repeated open/close cycles). +* **Reference Manipulation**: You need the session to remain open for complex logic or to ensure data + consistency throughout the method. -.. code-block:: php +.. note:: + The ``#[UseSession]`` attribute was introduced in Nextcloud 26. Previously, this feature used the + ``@UseSession`` annotation, which is now deprecated but otherwise equivalent. - `_. - private ISession $session; +.. warning:: - public function __construct($appName, IRequest $request, ISession $session) { - parent::__construct($appName, $request); - $this->session = $session; - } + If your controller method aggressively keeps sessions open, it may block other requests from the same user + or process (for example, a second browser tab, AJAX request, or background job), resulting in delays or + deadlocks. - #[UseSession] - public function writeASessionVariable(): Response { - // read a session variable - $value = $this->session['value']; +**Available ISession Methods:** - // write a session variable - $this->session['value'] = 'new value'; - } +The entire ``OCP\\ISession`` API: - } +- ``set(key, value)``, ``get(key)``, ``exists(key)``, ``remove(key)``, ``clear()`` +- ``reopen()``, ``close()`` +- ``getId()``, ``regenerateId()`` +See https://github.com/nextcloud/server/blob/master/lib/public/ISession.php for specifics. Setting cookies ^^^^^^^^^^^^^^^