🖥️ Controllers, Routing y CLI — 4 modulos
Actualizado: 2026-04
#democontrollertabs — Controllers modernos + Tabs
Demuestra como crear controllers modernos Symfony en el BO y asociarles Tabs (entradas en el menu del BO). Requiere PS 9.0+.
Repositorio
github.com/PrestaShop/example-modules/tree/master/democontrollertabs
Registrar Tabs en install()
php
<?php
// Registrar tabs (menu entries) al instalar el modulo
public function install(): bool
{
return parent::install()
&& $this->installTabs();
}
private function installTabs(): bool
{
// Tab padre (seccion en menu)
$parentTab = new Tab();
$parentTab->class_name = 'DemoControllerTabsParent';
$parentTab->module = $this->name;
$parentTab->id_parent = (int) Tab::getIdFromClassName('CONFIGURE');
$parentTab->icon = 'settings';
foreach (Language::getLanguages(true) as $lang) {
$parentTab->name[$lang['id_lang']] = 'Demo Tabs';
}
$parentTab->add();
// Sub-tabs
$tabs = [
['class' => 'DemoControllerTabsSimple', 'name' => 'Simple controller'],
['class' => 'DemoControllerTabsForm', 'name' => 'Form controller'],
['class' => 'DemoControllerTabsGrid', 'name' => 'Grid controller'],
];
foreach ($tabs as $t) {
$tab = new Tab();
$tab->class_name = $t['class'];
$tab->module = $this->name;
$tab->id_parent = $parentTab->id;
foreach (Language::getLanguages(true) as $lang) {
$tab->name[$lang['id_lang']] = $t['name'];
}
$tab->add();
}
return true;
}
Controller Symfony con routing YAML
php
<?php
// src/Controller/Admin/DemoSimpleController.php
namespace PrestaShop\Module\DemoControllerTabs\Controller\Admin;
use PrestaShopBundle\Controller\Admin\PrestaShopAdminController;
use Symfony\Component\HttpFoundation\Response;
class DemoSimpleController extends PrestaShopAdminController
{
public function indexAction(): Response
{
return $this->render(
'@Modules/democontrollertabs/views/templates/admin/simple.html.twig',
[
'layoutTitle' => 'Demo Simple Controller',
'message' => 'Hello from Symfony controller!',
]
);
}
}
// config/routes.yml
demo_controller_tabs_simple:
path: /demo-controller-tabs/simple
methods: [GET]
defaults:
_controller: 'PrestaShop\Module\DemoControllerTabs\Controller\Admin\DemoSimpleController::indexAction'
_legacy_controller: DemoControllerTabsSimple
_legacy_link: DemoControllerTabsSimple
#demojsrouting — JS Router component
Ilustra como usar el Javascript Router component de PrestaShop para generar URLs de rutas Symfony desde JavaScript en el BO.
Repositorio
github.com/PrestaShop/example-modules/tree/master/demojsrouting
Usar el Router JS del BO
javascript
// El Router JS esta disponible globalmente en el BO de PS 9+
// Genera URLs de rutas Symfony sin hardcodear paths
// Obtener URL de una ruta con parametros
const editUrl = window.prestashop.instance.router.generate(
'admin_products_edit',
{ productId: 42 }
);
// Resultado: /admin123/products/42/edit
// Usar en fetch para AJAX
const url = window.prestashop.instance.router.generate(
'demo_js_routing_ajax_action',
{ itemId: 15 }
);
fetch(url, {
method: 'POST',
headers: {
'X-Requested-With': 'XMLHttpRequest',
},
})
.then(response => response.json())
.then(data => console.log(data));
Exponer ruta al JS Router
php
<?php
// config/routes.yml — la ruta debe existir en Symfony
demo_js_routing_ajax_action:
path: /demo-js-routing/ajax/{itemId}
methods: [POST]
defaults:
_controller: 'PrestaShop\Module\DemoJsRouting\Controller\Admin\AjaxController::actionAction'
options:
expose: true # CLAVE: esto expone la ruta al JS Router
#demomoduleroutes — Hook moduleRoutes
Ilustra el uso del hook moduleRoutes para registrar URLs amigables custom en el front office. Compatible desde PS 8.0.
Repositorio
github.com/PrestaShop/example-modules/tree/master/demomoduleroutes
Hook moduleRoutes — URLs amigables FO
php
<?php
public function hookModuleRoutes(): array
{
return [
'module-demomoduleroutes-list' => [
'rule' => 'demo/items',
'keywords' => [],
'controller' => 'list',
'params' => [
'fc' => 'module',
'module' => 'demomoduleroutes',
],
],
'module-demomoduleroutes-detail' => [
'rule' => 'demo/item/{id}',
'keywords' => [
'id' => [
'regexp' => '[0-9]+',
'param' => 'id',
],
],
'controller' => 'detail',
'params' => [
'fc' => 'module',
'module' => 'demomoduleroutes',
],
],
];
}
// Resultado:
// https://tutienda.com/demo/items → ListController
// https://tutienda.com/demo/item/42 → DetailController
#democonsolecommand — Comando Symfony CLI
Muestra como implementar un comando de consola Symfony ejecutable via bin/console. Requiere PS 9.0+.
Repositorio
github.com/PrestaShop/example-modules/tree/master/democonsolecommand
Implementar un comando CLI
php
<?php
namespace PrestaShop\Module\DemoConsoleCommand\Command;
use Symfony\Component\Console\Attribute\AsCommand;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputOption;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
#[AsCommand(
name: 'demo:greet',
description: 'Demo console command that greets a user',
)]
class GreetCommand extends Command
{
protected function configure(): void
{
$this
->addArgument('name', InputArgument::REQUIRED, 'Who to greet')
->addOption('uppercase', 'u', InputOption::VALUE_NONE, 'Uppercase the greeting');
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$name = $input->getArgument('name');
$greeting = sprintf('Hello, %s!', $name);
if ($input->getOption('uppercase')) {
$greeting = strtoupper($greeting);
}
$io->success($greeting);
return Command::SUCCESS;
}
}
Registrar el comando en services.yml
yaml
# config/services.yml
services:
PrestaShop\Module\DemoConsoleCommand\Command\GreetCommand:
tags:
- { name: 'console.command' }
Ejecutar el comando
bash
# Ejecutar con --app-id para usar el kernel correcto
php bin/console demo:greet "World" --app-id=admin
php bin/console demo:greet "World" -u --app-id=admin
# En PS 9.x hay tres kernels:
# --app-id=admin (AdminKernel)
# --app-id=admin-api (AdminAPIKernel)
# --app-id=front (FrontKernel - experimental)
Descargar en Markdown
Pensado para pegar en ChatGPT, Claude u otra IA. Incluye solo el contenido de esta pagina.