Skip to content

Controllers – API Reference

Namespace: Alxarafe\Base\Controller

The controller hierarchy in Alxarafe follows a layered inheritance pattern where each level adds capabilities: menus, views, authentication, database, and CRUD operations.

Inheritance Diagram

mermaid
graph TD
    A["GenericController<br/>(abstract)"] --> B["ViewController<br/>(abstract)"]
    B --> C["Controller<br/>(abstract)"]
    B --> D["GenericPublicController<br/>(abstract)"]
    C --> E["ResourceController<br/>(abstract)"]
    D --> F["PublicResourceController<br/>(abstract)"]
    
    A -. "uses" .-> G["ViewTrait"]
    C -. "uses" .-> H["DbTrait"]
    D -. "uses" .-> H
    E -. "uses" .-> I["ResourceTrait"]
    F -. "uses" .-> I
    E -. "implements" .-> J["ResourceInterface"]
    F -. "implements" .-> J

When to Extend Each Controller

ControllerAuthDBViewsCRUDUse Case
GenericControllerMinimal base, CLI scripts
ViewControllerStatic pages without auth/DB
GenericPublicControllerPublic pages with DB (login, registration)
ControllerAuthenticated pages with custom logic
ResourceControllerStandard CRUD for Eloquent models
PublicResourceControllerPublic CRUD (rare, e.g. public catalog)

GenericController (abstract)

Namespace: Alxarafe\Base\Controller\GenericController
Source: [GenericController.php](file:///home/rsanjose/Desarrollo/Alxarafe/alxarafe/src/Core/Base/Controller/GenericController.php)

Base controller providing action dispatch, menu building, and trait auto-initialization. All controllers ultimately extend this class.

Properties

PropertyTypeDescription
$actionstringCurrent action name (from $_GET['action'] or constructor)
$topMenuarrayTop navigation menu items
$sidebar_menuarraySidebar menu items (legacy Blade support)
$backUrl?stringAuto-computed "back" URL
$titlestringPage title
$datamixedArbitrary data passed to the controller

Key Methods

MethodSignatureDescription
index()public index(bool $executeActions = true): boolDefault entry point. Calls executeAction().
executeAction()protected executeAction(): boolResolves do{Action}() method and runs beforeAction()doAction()afterAction() chain.
beforeAction()public beforeAction(): boolHook: override for pre-processing. Returns false to abort.
afterAction()public afterAction(): boolHook: override for post-processing.
getModuleName()public static getModuleName(): stringExtracts module name from namespace (e.g. Modules\Admin\...'Admin').
getControllerName()public static getControllerName(): stringExtracts controller name (strips Controller suffix).
url()public static url($action = 'index', $params = []): stringGenerates URL for this controller. Attempts friendly URL via Router::generate().
getMenu()public static getMenu(): string|array|falseReads the MENU constant if defined.
getSidebarMenu()public static getSidebarMenu(): array|falseReads MENU + SIDEBAR_MENU constants.
getActions()public static getActions(): array<string>Lists all do* methods (available actions).
jsonResponse()protected jsonResponse(array $data): voidOutputs JSON and exits.

Example

php
class MyController extends GenericController
{
    public function doProcess(): bool
    {
        // Business logic here
        $this->jsonResponse(['status' => 'ok']);
        return true;
    }
}

ViewController (abstract)

Namespace: Alxarafe\Base\Controller\ViewController
Extends: GenericController
Uses: ViewTrait
Source: [ViewController.php](file:///home/rsanjose/Desarrollo/Alxarafe/alxarafe/src/Core/Base/Controller/ViewController.php)

Adds Blade template support, configuration loading, and translation helpers.

Additional Properties

PropertyTypeDescription
$config?objectConfiguration from config.json
$debugboolDebug mode flag
$alertsarrayMessages/alerts to display in view

Key Methods

MethodSignatureDescription
trans()public trans(string $key, array $replace = [], ?string $domain = null): stringTranslation helper for templates ($me->trans('key')).
_()public static _(string $key, ...): stringStatic translation proxy.
getRenderHeader()public getRenderHeader(): stringReturns DebugBar header HTML if debug enabled.
getRenderFooter()public getRenderFooter(): stringReturns DebugBar footer HTML if debug enabled.
afterAction()public afterAction(): boolLoads messages and calls $this->render().

ViewTrait Methods (mixed in)

MethodSignatureDescription
setDefaultTemplate()public setDefaultTemplate(?string $name = null): voidInitializes or updates the template name.
addVariable()public addVariable(string $name, mixed $value): voidInjects a variable into the Blade view.
addVariables()public addVariables(array $vars): voidBulk-injects variables.
setTemplatesPath()public setTemplatesPath(array $paths): voidSets template search paths.
addTemplatesPath()public addTemplatesPath(string $path): voidAppends a template path.
render()public render(?string $viewPath = null): stringCompiles and returns the Blade template output.

Controller (abstract)

Namespace: Alxarafe\Base\Controller\Controller
Extends: ViewController
Uses: DbTrait
Source: [Controller.php](file:///home/rsanjose/Desarrollo/Alxarafe/alxarafe/src/Core/Base/Controller/Controller.php)

Adds authentication, authorization, module activation checks, and database connectivity.

Additional Properties

PropertyTypeDescription
$username?stringAuthenticated user's name

Constructor Behavior

  1. Calls ViewController::__construct() (config, templates, menus)
  2. Authentication: Checks Auth::isLogged(), redirects to login if not
  3. Module check: Verifies module is enabled via MenuManager::isModuleEnabled()
  4. Authorization: Calls Auth::$user->can($action, $controller, $module)

Key Methods

MethodSignatureDescription
shouldEnforceAuth()protected shouldEnforceAuth(): boolOverride to return false to skip auth (e.g., during installation).

DbTrait Methods (mixed in)

MethodSignatureDescription
connectDb()public static connectDb(?stdClass $dbConfig = null): boolSingleton database connection. Auto-called via initDbTrait().

GenericPublicController (abstract)

Namespace: Alxarafe\Base\Controller\GenericPublicController
Extends: ViewController
Uses: DbTrait
Source: [GenericPublicController.php](file:///home/rsanjose/Desarrollo/Alxarafe/alxarafe/src/Core/Base/Controller/GenericPublicController.php)

Provides view and database access without authentication. Used for login pages, public forms, and error pages.


ResourceController (abstract)

Namespace: Alxarafe\Base\Controller\ResourceController
Extends: Controller
Implements: ResourceInterface
Uses: ResourceTrait
Source: [ResourceController.php](file:///home/rsanjose/Desarrollo/Alxarafe/alxarafe/src/Core/Base/Controller/ResourceController.php)

The primary controller for CRUD operations. Provides automatic list/edit mode detection, form generation from model metadata, and component-based UI assembly.

ResourceTrait Key Methods

MethodSignatureDescription
getModelClass()abstract protected getModelClass(): string|arrayReturns model FQCN or array of tab→model mappings.
getListColumns()protected getListColumns(): arrayDefine columns for list view. Empty = auto-scaffold from model.
getEditFields()protected getEditFields(): arrayDefine fields for edit form. Empty = auto-scaffold from model.
getFilters()protected getFilters(): arrayDefine list view filters.
getTabs()protected getTabs(): arrayGenerate Tab objects for tabbed forms.
getTabVisibility()protected getTabVisibility(): array<string, callable(): bool>Define conditional tab visibility.
getTabBadges()protected getTabBadges(): array<string, callable(): ?int>Define badge counts for tabs.
doIndex()public doIndex(): boolDefault action: runs privateCore().
doSave()public doSave(): boolSave action: runs privateCore().
doDelete()public doDelete(): boolDelete action with hook support.
doCreate()public doCreate(): boolCreation entry point.
beforeConfig()protected beforeConfig(): voidHook: before configuration building.
beforeList()protected beforeList(): voidHook: before list mode processing.
beforeEdit()protected beforeEdit(): voidHook: before edit mode processing.
afterSaveRecord()protected afterSaveRecord(Model $model, array $data): voidHook: after saving a record.
setup()protected setup(): voidConfigure default buttons (New, Save, Back).
insertTabAfter()protected insertTabAfter(array $tabs, string $afterKey, Tab $newTab): arrayHelper to insert a tab after a specific key.

Example: Complete ResourceController

php
namespace Modules\Blog\Controller;

use Alxarafe\Base\Controller\ResourceController;
use Alxarafe\Component\Fields\Text;
use Alxarafe\Component\Fields\Textarea;
use Alxarafe\Component\Fields\Select;
use Alxarafe\Component\Fields\DateTime;
use Modules\Blog\Model\Post;

class PostController extends ResourceController
{
    protected function getModelClass(): string
    {
        return Post::class;
    }

    protected function getListColumns(): array
    {
        return [
            new Text('title', 'Title'),
            new Select('status', 'Status', ['options' => ['draft', 'published']]),
            new DateTime('created_at', 'Created'),
        ];
    }

    protected function getEditFields(): array
    {
        return [
            'general' => [
                'label' => 'General',
                'fields' => [
                    new Text('title', 'Title', ['required' => true]),
                    new Textarea('body', 'Content', ['required' => true]),
                    new Select('status', 'Status', [
                        'options' => ['draft' => 'Draft', 'published' => 'Published']
                    ]),
                ],
            ],
            'metadata' => [
                'label' => 'Metadata',
                'fields' => [
                    new Text('slug', 'URL Slug'),
                    new Text('meta_description', 'Meta Description'),
                ],
            ],
        ];
    }
}

PublicResourceController (abstract)

Namespace: Alxarafe\Base\Controller\PublicResourceController
Extends: GenericPublicController
Implements: ResourceInterface
Uses: ResourceTrait
Source: [PublicResourceController.php](file:///home/rsanjose/Desarrollo/Alxarafe/alxarafe/src/Core/Base/Controller/PublicResourceController.php)

Same as ResourceController but without authentication. Rarely used; suitable for public catalogs.


ApiController (abstract)

Namespace: Alxarafe\Base\Controller\ApiController
Source: [ApiController.php](file:///home/rsanjose/Desarrollo/Alxarafe/alxarafe/src/Core/Base/Controller/ApiController.php)

Base controller for REST API endpoints. Handles JWT authentication and JSON responses.

Key Methods

MethodSignatureDescription
jsonResponse()protected jsonResponse(array $data): voidOutput JSON and exit
badApiCall()protected badApiCall(string $msg, int $code = 400): voidOutput error JSON and exit

ResourceInterface

Namespace: Alxarafe\Base\Controller\Interface\ResourceInterface
Source: [ResourceInterface.php](file:///home/rsanjose/Desarrollo/Alxarafe/alxarafe/src/Core/Base/Controller/Interface/ResourceInterface.php)

Defines the mode constants and method contracts for CRUD controllers.

Constants

ConstantValueDescription
MODE_LIST'list'Listing mode
MODE_EDIT'edit'Edit/create mode