Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 30 ยท Back Office with Symfony

The Symfony Back Office

Add modern back office pages to a PrestaShop module: Symfony controllers, routes.yml, services, admin security and the difference from legacy admin controllers.

The PrestaShop back office has been moving from hand-written legacy pages to pages built on Symfony for many releases. Product pages, orders, customers, the module manager, most settings screens: they are Symfony controllers, Twig templates and services. Module authors can use the same stack. A module with its own admin page can register a route, point it at a controller class, inject services and protect it with the shop's permission system.

This lesson shows how those pieces fit: the folder layout, the routes.yml and services.yml files, a controller, the admin menu entry, the security check, and the choice between a modern page and a legacy controller. The module code is read-only here. The stand-ins model the router and the permission check so you can watch requests being matched and refused. Templates, forms and grids come in Twig, Forms and Grids.

Legacy and modern pages

PrestaShop supports two kinds of admin pages side by side:

Legacy admin controller Symfony controller
Location controllers/admin/AdminAcmeNoteController.php src/Controller/Admin/NoteController.php
Base class ModuleAdminController the PrestaShop admin controller base class
Template Smarty or HelperList/HelperForm Twig
URL index.php?controller=AdminAcmeNote&token=... a route from routes.yml
Services Context, static helpers Symfony dependency injection

Legacy controllers still work and are the quickest path for a tiny page. The Symfony way scales better: services can be tested without the core, the router gives clean URLs, forms and grids reuse core components, and it is where the core is heading. For a new module aimed at current versions, prefer Symfony controllers unless the page is trivial. If you must support very old versions, check which one you target first, because base class names and some features changed between PrestaShop 1.7, 8 and 9.

flowchart LR
    R["Request /admin/modules/acme/notes"] --> K["Symfony kernel"]
    K --> M["Route matched<br/>(routes.yml)"]
    M --> S{"Security check<br/>(employee profile)"}
    S -->|"allowed"| C["Controller action<br/>services from services.yml"]
    S -->|"denied"| X["403 / redirect"]
    C --> T["Twig template"]
    T --> O["Response"]

A modern admin request: route, permission check, controller, template.

Layout of a module with Symfony pages

TEXT
modules/acmenote/
  acmenote.php                         main Module class
  composer.json                        autoload for the Acme\Note namespace
  config/
    routes.yml                         back office routes
    services.yml                       services (can also be split in admin/ and front/)
  src/
    Controller/Admin/NoteController.php
    Repository/NoteRepository.php
  views/templates/admin/
    index.html.twig

Because the classes live under src/, they need an autoloader. Declare the namespace in composer.json ("psr-4": {"Acme\\Note\\": "src/"}) and ship the generated vendor/ folder with the module, as described in Anatomy of a Module.

Routes

A module's config/routes.yml is picked up by the Symfony router when the module is installed and enabled (clear the cache after you edit it). Each route has a name, a path, allowed methods and defaults that include the controller:

YAML
# modules/acmenote/config/routes.yml (read-only)
acme_note_index:
  path: /acme/notes
  methods: [GET]
  defaults:
    _controller: 'Acme\Note\Controller\Admin\NoteController::indexAction'
    _legacy_controller: AdminAcmeNote
    _legacy_link: AdminAcmeNote

acme_note_delete:
  path: /acme/notes/{noteId}/delete
  methods: [POST]
  defaults:
    _controller: 'Acme\Note\Controller\Admin\NoteController::deleteAction'
    _legacy_controller: AdminAcmeNote
  requirements:
    noteId: '\d+'

Details that matter:

  • methods lets the router answer a wrong verb with 405. Use POST (not GET) for anything that changes data.
  • requirements restricts a parameter with a regular expression. \d+ means a request for /acme/notes/abc/delete never reaches your code.
  • _legacy_controller names the admin "tab" this route belongs to. The permission system works per tab, so this is what ties the route to the employee profile's rights.
  • Route names are global. Give them your module prefix (acme_note_...) to avoid a clash.
  • PrestaShop adds a security token (_token) to back office URLs it generates and rejects requests whose token is missing or wrong. Generate links with the router ($this->generateUrl('acme_note_index') or Twig's path()), not by writing paths by hand, so the token is included.

Services

Symfony's dependency injection builds your classes for you. A module lists them in config/services.yml:

YAML
# modules/acmenote/config/services.yml (read-only)
services:
  _defaults:
    public: true

  Acme\Note\Repository\NoteRepository:
    arguments:
      - '@doctrine.dbal.default_connection'
      - '%database_prefix%'

  Acme\Note\Controller\Admin\NoteController:
    arguments:
      - '@Acme\Note\Repository\NoteRepository'

%database_prefix% is the Symfony parameter that carries the same prefix as _DB_PREFIX_, which keeps the repository testable: pass a fake connection and a test prefix, no global constants needed. Read Tables, Installers and Upgrades for why the prefix is never hard-coded.

Services make the layers clean: the controller handles HTTP and delegates; the repository talks to the database; neither calls Context::getContext() unless it has to.

The controller

PHP
<?php
// modules/acmenote/src/Controller/Admin/NoteController.php (read-only; the base class
// and the AdminSecurity namespace differ between PrestaShop 8 and 9: check your version)
declare(strict_types=1);

namespace Acme\Note\Controller\Admin;

use Acme\Note\Repository\NoteRepository;
use PrestaShopBundle\Controller\Admin\PrestaShopAdminController;
use PrestaShopBundle\Security\Attribute\AdminSecurity;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Response;

class NoteController extends PrestaShopAdminController
{
    public function __construct(private readonly NoteRepository $notes)
    {
    }

    #[AdminSecurity("is_granted('read', request.get('_legacy_controller'))")]
    public function indexAction(): Response
    {
        return $this->render('@Modules/acmenote/views/templates/admin/index.html.twig', [
            'notes' => $this->notes->findLatest(50),
        ]);
    }

    #[AdminSecurity(
        "is_granted('delete', request.get('_legacy_controller'))",
        redirectRoute: 'acme_note_index',
        message: 'You are not allowed to delete notes.'
    )]
    public function deleteAction(int $noteId): RedirectResponse
    {
        $this->notes->delete($noteId);
        $this->addFlash('success', $this->trans('Note deleted.', [], 'Modules.Acmenote.Admin'));

        return $this->redirectToRoute('acme_note_index');
    }
}

Points to read carefully:

  • The controller extends the admin base class, which gives you helpers such as render(), redirectToRoute(), addFlash() and trans(). In PrestaShop 8 the base class has another name (FrameworkBundleAdminController) and the security rule is an annotation instead of a PHP attribute; in 9 the base class and attribute shown above are used. Always check the version your module declares in ps_versions_compliance.
  • @Modules/acmenote/... is a Twig namespace pointing into the modules folder.
  • The action reads the id as int $noteId straight from the route, and the \d+ requirement already guaranteed it is digits.
  • Delete reacts to POST only, then redirects. Redirecting after a write stops a browser refresh from repeating the action.
  • Messages use the translation system with a module domain, see Translations and Multilingual Modules.

Security rules

AdminSecurity evaluates an expression for the current employee. is_granted('read', request.get('_legacy_controller')) asks: may this employee's profile read the tab named in the route? The four verbs you will use are read, create, update and delete. Merchants set them per profile in Advanced Parameters > Team > Permissions. If the check fails, the user is refused (or redirected to redirectRoute with the message). Always attach the rule to every action, and make it match the effect: a delete action needs delete, not read. A missing rule is a hole, since the route is reachable by every logged-in employee.

The admin menu entry

A page nobody can reach is not useful. A module adds a menu item through a back office tab. The simplest way is the $tabs property of the main class, which parent::install() turns into real tab rows:

PHP
// modules/acmenote/acmenote.php (read-only, shortened)
public function __construct()
{
    $this->name = 'acmenote';
    // ... other properties ...
    parent::__construct();

    $this->tabs = [
        [
            'name' => 'Notes',
            'class_name' => 'AdminAcmeNote',
            'route_name' => 'acme_note_index',
            'parent_class_name' => 'AdminParentCustomer',
            'visible' => true,
        ],
    ];
}

class_name must equal the _legacy_controller from the routes, and route_name points to the Symfony route the menu link opens. Check the keys supported by your PrestaShop version in its developer documentation. Tabs are removed again by parent::uninstall() for the tabs declared this way.

Match a request to a route (stand-in)

The real router is Symfony's. The stand-in below is a miniature with the same ideas: named routes with s, allowed methods, requirements and a 404/405 answer. It is small enough to read in one sitting and shows why a wrong verb or a non-numeric id never reaches the controller.

PHP Stand-in: a tiny router with methods and requirements

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

The 405 for GET /acme/notes/42/delete and the 404 for abc are exactly the two cheap protections that methods and requirements give you before any of your code runs.

Employee permissions (stand-in)

The second stand-in models the permission check: profiles with read, create, update and delete rights per tab, an AdminSecurity-style guard in front of every action and a token check for state-changing requests. The token is simplified to an HMAC of the employee id and the tab with a secret; PrestaShop's own token generation is different, and this only shows the principle.

PHP Stand-in: per-profile permissions and URL tokens

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with fgets(STDIN)), it gets the next line from this box.

A valid token does not replace a permission, and a permission does not replace a token: they answer different questions ("did this employee mean to do this?" and "may this employee do this?").

Choosing legacy or modern

  • Small settings form for a module: the legacy getContent() page (A Module Configuration Page) is fine, and runs on every version.
  • A list of records with filters and actions, or several screens: a Symfony controller with a grid, covered next.
  • You need to support old PrestaShop versions: keep the core of your logic in plain service classes that do not care about the controller type, so the page is a thin layer you can swap.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does _legacy_controller in a route's defaults do?

    Permissions in the back office are defined per tab. The legacy controller name links a Symfony route to that tab, for the permission check and for the menu.
  2. 2. Why should a state-changing admin route use methods: [POST]?

    Restricting the verb means a plain link, an image tag or a crawler cannot change data. Combine it with a token and a permission check.
  3. 3. An action has no AdminSecurity rule. What is the risk?

    Without a rule the action is not tied to the profile permissions. Attach a rule to every action and match the verb to the effect (read, create, update, delete).
  4. 4. Where does a module list the services its Symfony controllers need?

    Services, with their arguments, are declared in the module's config/services.yml (optionally split into admin and front files).
  5. 5. What does requirements: noteId: '\d+' protect against?

    The router refuses a path whose parameter does not match the pattern. It is cheap input validation, but you still validate and authorize inside the action.

Summary

  • Modern back office pages are Symfony controllers declared in config/routes.yml, with services in config/services.yml; legacy ModuleAdminController pages remain for simple cases.
  • Routes restrict verbs (methods) and parameter shapes (requirements); use POST plus the admin token for changes, and generate URLs with the router.
  • _legacy_controller ties a route to a tab, and AdminSecurity checks the employee's read, create, update or delete right; put one on every action.
  • A tab in $tabs adds the menu entry and is removed again on uninstall.
  • Base class and security attribute names changed between PrestaShop 8 and 9, so check the version you target.

Next: Twig, Forms and Grids