Documentation

AbstractCrudController extends BaseController
in package

AbstractYes

Abstract base controller providing standardized CRUD operations.

Extends BaseController with common patterns for Create, Read, Update, Delete operations. Controllers managing simple resources can extend this class to reduce boilerplate code.

Request Parameter Conventions

This controller expects these standard request parameters:

  • op=Save - Create a new record (from form submission)
  • op=Change - Update an existing record (from form submission)
  • marked[] - Array of IDs for bulk operations
  • markaction - Bulk action to perform on marked items
  • allaction - Action to perform on all filtered items

Note: Edit and delete operations use RESTful routes:

  • GET /{resource}/{id}/edit - Edit form
  • DELETE /{resource}/{id} - Delete record

Note: Create forms should use dedicated /new routes (e.g., /tags/new)

Usage

class MyResourceController extends AbstractCrudController
{
    protected string $pageTitle = 'My Resources';
    protected string $resourceName = 'resource';

    protected function handleCreate(): string { ... }
    protected function handleUpdate(int $id): string { ... }
    protected function handleDelete(int $id): string { ... }
    protected function renderList(string $message): void { ... }
    protected function renderCreateForm(): void { ... }
    protected function renderEditForm(int $id): void { ... }
}
Tags
category

Lwt

author

HugoFara hugo.farajallah@protonmail.com

license

Unlicense http://unlicense.org/

link
https://hugofara.github.io/lwt/docs/php/
since
3.0.0

Table of Contents

Properties

$pageTitle  : string
Page title for the resource index page.
$resourceName  : string
Singular name of the resource (for messages).
$showMenu  : bool
Whether to show the navigation menu.

Methods

__construct()  : mixed
Initialize controller.
index()  : void
Main index action - dispatches to appropriate CRUD operation.
dispatchView()  : void
Dispatch to the appropriate view based on request parameters.
endRender()  : void
End page rendering with standard LWT footer.
errorMessage()  : string
Display an error message.
execute()  : int
Execute an INSERT/UPDATE/DELETE query.
formatBulkActionMessage()  : string
Format bulk action result into a display message.
get()  : string
Get a string GET parameter.
getCurrentPage()  : int
Get current page number from request.
getCurrentQuery()  : string
Get current search query from request.
getCurrentSort()  : int
Get current sort order from request/database.
getIdParameterName()  : string
Get the name of the ID parameter for update operations.
getMarkedIds()  : array<string|int, int>
Get IDs from marked checkboxes.
getValue()  : mixed
Get a single value from the database.
handleBulkAction()  : array{success: bool, count: int, action: string, error?: string}
Handle a bulk action on the given IDs.
handleBulkDelete()  : array{success: bool, count: int, action: string}
Handle bulk delete operation.
handleCreate()  : string
Handle create operation.
handleDelete()  : string
Handle delete operation.
handleUpdate()  : string
Handle update operation.
hasParam()  : bool
Check if a parameter exists in the request.
isGet()  : bool
Check if the request is a GET request.
isPost()  : bool
Check if the request is a POST request.
json()  : JsonResponse
Return JSON response.
message()  : void
Display a message (success/error) to the user using Bulma notifications.
param()  : string
Get a string request parameter (GET, POST, or REQUEST).
paramArray()  : array<string|int, mixed>
Get an array request parameter.
paramInt()  : int|null
Get an integer request parameter.
post()  : string
Get a string POST parameter.
processActions()  : string
Process CRUD actions from request parameters.
processAllAction()  : array{success: bool, count: int, action: string, error?: string}
Process action on all filtered items.
processBulkAction()  : array{success: bool, count: int, action: string, error?: string}
Process bulk action on marked items.
query()  : mysqli_result|bool
Execute a database query using the LWT query wrapper.
redirect()  : RedirectResponse
Redirect to another URL.
render()  : void
Start page rendering with standard LWT header.
renderCreateForm()  : void
Render the create form.
renderEditForm()  : void
Render the edit form.
renderList()  : void
Render the list view.
requireInt()  : int
Get a required integer request parameter.
successMessage()  : string
Display a success message.

Properties

$resourceName

Singular name of the resource (for messages).

protected string $resourceName = 'item'

Methods

__construct()

Initialize controller.

public __construct() : mixed

index()

Main index action - dispatches to appropriate CRUD operation.

public index(array<string|int, mixed> $params) : void

This method handles the standard CRUD flow:

  1. Process any pending actions (delete, save, update, bulk)
  2. Display the appropriate view (list, create form, or edit form)

Override this method if you need custom routing logic.

Parameters
$params : array<string|int, mixed>

Route parameters

dispatchView()

Dispatch to the appropriate view based on request parameters.

protected dispatchView(string $message) : void

Note: Edit forms are now handled via RESTful /{resource}/{id}/edit routes.

Parameters
$message : string

Message from processed action

endRender()

End page rendering with standard LWT footer.

protected endRender() : void

errorMessage()

Display an error message.

protected errorMessage(string $error) : string
Parameters
$error : string

Error description

Return values
string

Formatted error message

execute()

Execute an INSERT/UPDATE/DELETE query.

protected execute(string $sql) : int
Parameters
$sql : string

SQL query

Tags
psalm-suppress

PossiblyUnusedReturnValue

Return values
int

Number of affected rows

formatBulkActionMessage()

Format bulk action result into a display message.

protected formatBulkActionMessage(array{success: bool, count: int, action: string, error?: string} $result) : string
Parameters
$result : array{success: bool, count: int, action: string, error?: string}

Bulk action result

Return values
string

Formatted message for display

get()

Get a string GET parameter.

protected get(string $key[, string $default = '' ]) : string
Parameters
$key : string

Parameter name

$default : string = ''

Default value if not set

Return values
string

Parameter value or default

getCurrentPage()

Get current page number from request.

protected getCurrentPage([string $requestKey = 'page' ][, string $sessionKey = 'currentpage' ][, int $default = 1 ]) : int
Parameters
$requestKey : string = 'page'

Request parameter name

$sessionKey : string = 'currentpage'

Unused, kept for BC (was session key)

$default : int = 1

Default page number

Return values
int

Current page number

getCurrentQuery()

Get current search query from request.

protected getCurrentQuery([string $requestKey = 'query' ][, string $sessionKey = 'currentquery' ][, string $default = '' ]) : string
Parameters
$requestKey : string = 'query'

Request parameter name

$sessionKey : string = 'currentquery'

Unused, kept for BC (was session key)

$default : string = ''

Default query

Return values
string

Current search query

getCurrentSort()

Get current sort order from request/database.

protected getCurrentSort([string $requestKey = 'sort' ][, string $dbKey = 'currentsort' ][, int $default = 1 ]) : int
Parameters
$requestKey : string = 'sort'

Request parameter name

$dbKey : string = 'currentsort'

Database setting key for persistence

$default : int = 1

Default sort order

Return values
int

Current sort order

getIdParameterName()

Get the name of the ID parameter for update operations.

protected getIdParameterName() : string

Override this if your ID parameter has a different name. Default is based on resource name (e.g., 'resourceId').

Return values
string

Parameter name

getMarkedIds()

Get IDs from marked checkboxes.

protected getMarkedIds(string|array<string|int, mixed> $marked) : array<string|int, int>
Parameters
$marked : string|array<string|int, mixed>

The 'marked' request parameter value

Tags
psalm-return

array

Return values
array<string|int, int>

Array of integer IDs

getValue()

Get a single value from the database.

protected getValue(string $sql) : mixed
Parameters
$sql : string

SQL query (should return single value as 'value')

Return values
mixed

The value or null

handleBulkAction()

Handle a bulk action on the given IDs.

protected handleBulkAction(string $action, array<string|int, int> $ids) : array{success: bool, count: int, action: string, error?: string}

Override this method to implement bulk operations.

Parameters
$action : string

The action code

$ids : array<string|int, int>

Array of record IDs

Return values
array{success: bool, count: int, action: string, error?: string}

Result data

handleBulkDelete()

Handle bulk delete operation.

protected handleBulkDelete(array<string|int, int> $ids) : array{success: bool, count: int, action: string}

Override this method to implement bulk delete with proper cleanup.

Parameters
$ids : array<string|int, int>

Array of record IDs to delete

Return values
array{success: bool, count: int, action: string}

Result data

handleCreate()

Handle create operation.

protected abstract handleCreate() : string

Called when op=Save is submitted. Read form data from request and create the new record.

Return values
string

Result message (e.g., "Created successfully")

handleDelete()

Handle delete operation.

protected abstract handleDelete(int $id) : string

Called from RESTful DELETE routes and bulk delete operations.

Parameters
$id : int

Record ID to delete

Return values
string

Result message (e.g., "Deleted")

handleUpdate()

Handle update operation.

protected abstract handleUpdate(int $id) : string

Called when op=Change is submitted. Read form data from request and update the existing record.

Parameters
$id : int

Record ID to update

Return values
string

Result message (e.g., "Updated successfully")

hasParam()

Check if a parameter exists in the request.

protected hasParam(string $key) : bool
Parameters
$key : string

Parameter name

Return values
bool

True if the parameter exists

isGet()

Check if the request is a GET request.

protected isGet() : bool
Return values
bool

isPost()

Check if the request is a POST request.

protected isPost() : bool
Return values
bool

json()

Return JSON response.

protected json(mixed $data[, int $status = 200 ]) : JsonResponse

Return this from a controller method; the router will send it.

Parameters
$data : mixed

Data to encode as JSON

$status : int = 200

HTTP status code (default: 200)

Return values
JsonResponse

message()

Display a message (success/error) to the user using Bulma notifications.

protected message(string $message[, bool $autoHide = true ]) : void
Parameters
$message : string

The message to display

$autoHide : bool = true

Whether to auto-hide the message (default: true)

param()

Get a string request parameter (GET, POST, or REQUEST).

protected param(string $key[, string $default = '' ]) : string
Parameters
$key : string

Parameter name

$default : string = ''

Default value if not set

Return values
string

Parameter value or default

paramArray()

Get an array request parameter.

protected paramArray(string $key[, array<string|int, mixed> $default = [] ]) : array<string|int, mixed>
Parameters
$key : string

Parameter name

$default : array<string|int, mixed> = []

Default value if not set

Return values
array<string|int, mixed>

Parameter value or default

paramInt()

Get an integer request parameter.

protected paramInt(string $key[, int|null $default = null ][, int|null $min = null ][, int|null $max = null ]) : int|null
Parameters
$key : string

Parameter name

$default : int|null = null

Default value if not set

$min : int|null = null

Minimum allowed value

$max : int|null = null

Maximum allowed value

Return values
int|null

Parameter value or default

post()

Get a string POST parameter.

protected post(string $key[, string $default = '' ]) : string
Parameters
$key : string

Parameter name

$default : string = ''

Default value if not set

Return values
string

Parameter value or default

processActions()

Process CRUD actions from request parameters.

protected processActions() : string

Handles the standard action flow:

  1. Bulk actions (markaction, allaction)
  2. Create/Update (op parameter)

Note: Single delete is handled via RESTful DELETE routes.

Return values
string

Result message from the action

processAllAction()

Process action on all filtered items.

protected processAllAction(string $action) : array{success: bool, count: int, action: string, error?: string}

Override this method to handle actions like "delete all matching filter".

Parameters
$action : string

The action code (e.g., 'delall')

Return values
array{success: bool, count: int, action: string, error?: string}

Result data

processBulkAction()

Process bulk action on marked items.

protected processBulkAction(string $action) : array{success: bool, count: int, action: string, error?: string}

Override this method to handle bulk operations like bulk delete, bulk status change, etc.

Parameters
$action : string

The action code (e.g., 'del', 'export')

Return values
array{success: bool, count: int, action: string, error?: string}

Result data

query()

Execute a database query using the LWT query wrapper.

protected query(string $sql) : mysqli_result|bool
Parameters
$sql : string

SQL query

Return values
mysqli_result|bool

Query result

redirect()

Redirect to another URL.

protected redirect(string $url[, int $statusCode = 302 ]) : RedirectResponse

Return this from a controller method; the router will send it.

Parameters
$url : string

URL to redirect to

$statusCode : int = 302

HTTP status code (default: 302)

Return values
RedirectResponse

render()

Start page rendering with standard LWT header.

protected render(string $title[, bool $showMenu = true ]) : void
Parameters
$title : string

Page title

$showMenu : bool = true

Whether to show navigation menu (default: true)

renderCreateForm()

Render the create form.

protected abstract renderCreateForm() : void

Called from RESTful /{resource}/new routes.

renderEditForm()

Render the edit form.

protected abstract renderEditForm(int $id) : void

Called from RESTful /{resource}/{id}/edit routes.

Parameters
$id : int

Record ID to edit

renderList()

Render the list view.

protected abstract renderList(string $message) : void

Called when no create/edit parameters are present.

Parameters
$message : string

Optional message to display (from previous action)

requireInt()

Get a required integer request parameter.

protected requireInt(string $key[, int|null $min = null ][, int|null $max = null ]) : int
Parameters
$key : string

Parameter name

$min : int|null = null

Minimum allowed value

$max : int|null = null

Maximum allowed value

Tags
throws
InvalidArgumentException

If parameter is missing or invalid

Return values
int

Parameter value

successMessage()

Display a success message.

protected successMessage(string $action) : string
Parameters
$action : string

Action that was performed (e.g., "Created", "Updated")

Return values
string

Formatted message


        
On this page

Search results