Skip to content

Commit a637254

Browse files
docs(basics/controllers): clarify session variable usage, locking, and API best practices
Signed-off-by: Josh <josh.t.richards@gmail.com>
1 parent fc54a7b commit a637254

File tree

1 file changed

+90
-47
lines changed

1 file changed

+90
-47
lines changed

developer_manual/basics/controllers.rst

Lines changed: 90 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -212,87 +212,130 @@ Headers, files, cookies and environment variables can be accessed directly from
212212
213213
}
214214
215-
Why should those values be accessed from the request object and not from the global array like $_FILES? Simple: `because it's bad practice <http://c2.com/cgi/wiki?GlobalVariablesAreBad>`_ and will make testing harder.
215+
Why should those values be accessed from the request object and not from the global array like $_FILES? Simple:
216+
`because it's bad practice <http://c2.com/cgi/wiki?GlobalVariablesAreBad>`_ and will make testing harder.
216217

217218
.. _controller-use-session:
218219

219-
Reading and writing session variables
220-
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
220+
Sessions and session variables
221+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
222+
223+
Introduction
224+
~~~~~~~~~~~~
225+
226+
Sessions allow your application to store data specific to a particular user across multiple HTTP
227+
requests. Variables are saved server-side and tied to a unique session identifier managed via a
228+
browser cookie.
229+
230+
Nextcloud uses PHP’s native session handling but adds several performance optimizations and a
231+
transparent encryption layer via the ``CryptoSessionData`` class. Data written through the
232+
``OCP\ISession`` API benefits from these optimizations and is automatically encrypted at rest.
233+
234+
.. danger::
235+
Never use PHP superglobals like ``$_SESSION``. This bypasses Nextcloud's encryption and
236+
lifecycle management. leading to race conditions or lost data.
221237

222-
To set, get or modify session variables, the ISession object has to be injected into the controller.
238+
Basic usage
239+
~~~~~~~~~~~
223240

224-
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.
241+
Inject the :class:`OCP\\ISession` object via your controller's constructor.
225242

226-
Alternatively, you can use the ``#[UseSession]`` attribute to automatically open and close the session for you.
243+
A more complete example:
227244

228245
.. code-block:: php
229-
:emphasize-lines: 2,7
246+
247+
<?php
248+
namespace OCA\MyApp\Controller;
230249
231250
use OCP\AppFramework\Controller;
232251
use OCP\AppFramework\Http\Attribute\UseSession;
233252
use OCP\AppFramework\Http\Response;
253+
use OCP\ISession;
254+
use OCP\IRequest;
234255
235256
class PageController extends Controller {
236-
237-
#[UseSession]
238-
public function writeASessionVariable(): Response {
239-
// ...
257+
public function __construct(
258+
$appName,
259+
IRequest $request,
260+
private ISession $session // PHP 8 property promotion
261+
) {
262+
parent::__construct($appName, $request);
240263
}
241264
242-
}
243-
244-
.. note:: The ``#[UseSession]`` was added in Nextcloud 26 and requires PHP 8.0 or later. If your app targets older releases and PHP 7.x then use the deprecated ``@UseSession`` annotation.
265+
// Simple (existing) variable retrieval
266+
public function simpleReads(): Response {
267+
$this->session->get('last_visit');
268+
return new Response();
269+
}
245270
246-
.. code-block:: php
247-
:emphasize-lines: 2
271+
// Default: Implicit locking per write. Good for single operations.
272+
public function simpleWrite(): Response {
273+
$this->session->set('last_visit', time());
274+
return new Response();
275+
}
248276
249-
/**
250-
* @UseSession
251-
*/
252-
public function writeASessionVariable(): Response {
253-
// ....
277+
// Optimization: Keeps session open for the entire method.
278+
#[UseSession]
279+
public function batchUpdate(): Response {
280+
$this->session->set('theme', 'dark');
281+
$this->session->set('font_size', '14px');
282+
$this->session->remove('fallback_theme');
283+
return new Response();
254284
}
285+
}
255286
287+
When to use ``#[UseSession]``
288+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
256289

257-
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.
290+
By default, Nextcloud uses an **on-demand locking strategy**: it closes the session immediately after the
291+
request starts to allow high concurrency, then briefly re-opens and closes it only during a ``set()`` or
292+
``remove()`` call. This default "close-early" behavior works for infrequent and standalone writing events
293+
and prevents one request from blocking another. Developers do not need to do anything special to enable
294+
this behavior.
258295

259-
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 <https://ma.ttias.be/php-session-locking-prevent-sessions-blocking-in-requests/>`_.
296+
However, in more advanced scenarios (e.g., calling ``set()`` five times in immediate succession) Nextcloud's
297+
default behavior means the session will open and close five times. This introduces significant I/O
298+
overhead (even if it does minimize locking). For these cases, Nextcloud supports an optional method-level
299+
attribute: ``#[UseSession]``. This attribute ensures the session is opened once at the start of your method and
300+
closed at the end, providing efficiency and correct locking in complex workflows.
260301

261-
Then session variables can be accessed like this:
302+
Use the ``#[UseSession]`` attribute when:
262303

263-
.. note:: The session is closed automatically for writing, unless you add the ``#[UseSession]`` attribute!
304+
* **Multiple Writes**: You are calling ``set()`` or ``remove()`` multiple times in one method (prevents
305+
I/O overhead from repeated open/close cycles).
306+
* **Reference Manipulation**: You need the session to remain open for complex logic or to ensure data
307+
consistency throughout the method.
264308

265-
.. code-block:: php
309+
.. note::
310+
The ``#[UseSession]`` attribute was introduced in Nextcloud 26. Previously, this feature used the
311+
``@UseSession`` annotation, which is now deprecated but otherwise equivalent.
266312

267-
<?php
268-
namespace OCA\MyApp\Controller;
313+
Performance and concurrency
314+
~~~~~~~~~~~~~~~~~~~~~~~~~~~
269315

270-
use OCP\ISession;
271-
use OCP\IRequest;
272-
use OCP\AppFramework\Controller;
273-
use OCP\AppFramework\Http\Attribute\UseSession;
274-
use OCP\AppFramework\Http\Response;
316+
PHP natively locks the session file while it is open for writing. If a controller keeps a session open
317+
unnecessarily, it may block other requests from the same user (e.g., parallel browser tabs or AJAX calls),
318+
resulting in delays or timeouts.
275319

276-
class PageController extends Controller {
320+
By keeping sessions closed except during the brief window of an actual write, Nextcloud ensures a
321+
responsive, multi-tab, and highly concurrent experience. For more technical background, see `PHP Session
322+
Locking and How to Prevent It <https://ma.ttias.be/php-session-locking-prevent-sessions-blocking-php-requests/>`_.
277323

278-
private ISession $session;
324+
.. warning::
279325

280-
public function __construct($appName, IRequest $request, ISession $session) {
281-
parent::__construct($appName, $request);
282-
$this->session = $session;
283-
}
326+
If your controller method aggressively keeps sessions open, it may block other requests from the same user
327+
or process (for example, a second browser tab, AJAX request, or background job), resulting in delays or
328+
deadlocks.
284329

285-
#[UseSession]
286-
public function writeASessionVariable(): Response {
287-
// read a session variable
288-
$value = $this->session['value'];
330+
**Available ISession Methods:**
289331

290-
// write a session variable
291-
$this->session['value'] = 'new value';
292-
}
332+
The entire ``OCP\\ISession`` API:
293333

294-
}
334+
- ``set(key, value)``, ``get(key)``, ``exists(key)``, ``remove(key)``, ``clear()``
335+
- ``reopen()``, ``close()``
336+
- ``getId()``, ``regenerateId()``
295337

338+
See https://github.com/nextcloud/server/blob/master/lib/public/ISession.php for specifics.
296339

297340
Setting cookies
298341
^^^^^^^^^^^^^^^

0 commit comments

Comments
 (0)