You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Copy file name to clipboardExpand all lines: developer_manual/basics/controllers.rst
+90-47Lines changed: 90 additions & 47 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -212,87 +212,130 @@ Headers, files, cookies and environment variables can be accessed directly from
212
212
213
213
}
214
214
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.
216
217
217
218
.. _controller-use-session:
218
219
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.
221
237
222
-
To set, get or modify session variables, the ISession object has to be injected into the controller.
238
+
Basic usage
239
+
~~~~~~~~~~~
223
240
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.
225
242
226
-
Alternatively, you can use the ``#[UseSession]`` attribute to automatically open and close the session for you.
243
+
A more complete example:
227
244
228
245
.. code-block:: php
229
-
:emphasize-lines: 2,7
246
+
247
+
<?php
248
+
namespace OCA\MyApp\Controller;
230
249
231
250
use OCP\AppFramework\Controller;
232
251
use OCP\AppFramework\Http\Attribute\UseSession;
233
252
use OCP\AppFramework\Http\Response;
253
+
use OCP\ISession;
254
+
use OCP\IRequest;
234
255
235
256
class PageController extends Controller {
236
-
237
-
#[UseSession]
238
-
public function writeASessionVariable(): Response {
.. 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
+
}
245
270
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
+
}
248
276
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();
254
284
}
285
+
}
255
286
287
+
When to use ``#[UseSession]``
288
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
256
289
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.
258
295
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.
260
301
261
-
Then session variables can be accessed like this:
302
+
Use the ``#[UseSession]`` attribute when:
262
303
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.
264
308
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.
266
312
267
-
<?php
268
-
namespace OCA\MyApp\Controller;
313
+
Performance and concurrency
314
+
~~~~~~~~~~~~~~~~~~~~~~~~~~~
269
315
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.
275
319
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/>`_.
277
323
278
-
private ISession $session;
324
+
.. warning::
279
325
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.
284
329
285
-
#[UseSession]
286
-
public function writeASessionVariable(): Response {
0 commit comments