### Install True Framework Source: https://context7.com/truecastdesign/truefw/llms.txt Use Composer to create a new project with the True Framework. ```sh composer create-project truecastdesign/truefw project-name ``` -------------------------------- ### Define API Route with GET Method Source: https://github.com/truecastdesign/truefw/blob/master/README.md Example of defining a GET route for an API endpoint using the App class. It demonstrates how to handle request parameters and render a view. ```php $App->get('/api/person/:value', function($request) use ($App) { $vars = []; # if the code is short you can put it in here and if too long include a controller here and put your code in the controller file. $App->view->render('_api/person.phtml', $vars); }); ``` -------------------------------- ### View Routing Example Source: https://github.com/truecastdesign/truefw/blob/master/README.md Illustrates how URL paths map to view files within the app/views directory. Subdirectories are created based on URL segments. ```code http://www.domain.com/about -> about.phtml http://www.domain.com/about/staff -> about/staff.phtml ``` -------------------------------- ### Include Routes File Source: https://github.com/truecastdesign/truefw/blob/master/docs/Routes.md Ensure the app/routes.php file is included after all object setups in init.php. ```php require 'app/routes.php'; ``` -------------------------------- ### Example Task Script with PHPMailer Source: https://github.com/truecastdesign/truefw/blob/master/docs/TaskQueue.md An example of a task script that uses PHPMailer to send an email. It retrieves configuration from an INI file and uses variables passed from the addTask method. ```php $config = $App->getConfig('contact-email-info.ini'); $Mail = new \PHPMailer\PHPMailer(true); try { //Server settings $Mail->isSMTP(); $Mail->Host = $config->host; $Mail->SMTPAuth = true; $Mail->Username = $config->username; $Mail->Password = $config->password; $Mail->SMTPSecure = 'tls'; $Mail->Port = $config->port; //TCP port to connect to; use 587 if you have set `SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS` $Mail->setFrom($config->from_email, $config->from_name); $Mail->addAddress($config->to_email, $config->to_name); $Mail->addReplyTo($taskData->email, $taskData->fullName); $Mail->isHTML(true); $Mail->Subject = $config->subject; $Mail->Body = $taskData->message; $Mail->send(); } catch (Exception) { error_log("Message could not be sent. Mailer Error: {$Mail->ErrorInfo}", 3, BP.'/php-error.log'); } ``` -------------------------------- ### Manage True Task Queue Runner Source: https://context7.com/truecastdesign/truefw/llms.txt Instructions for installing and managing the task runner service using systemd or a watched process. Ensure the PHP binary path is correctly configured. ```sh # Install and start the task runner as a system service (requires root) cp vendor/truecastdesign/true/workers/taskRunner.service /etc/systemd/system/ # Edit ExecStart in the service file to match your PHP binary and path, then: systemctl daemon-reload systemctl enable --now taskRunner.service # Check status / restart / stop systemctl status taskRunner.service systemctl restart taskRunner.service systemctl stop taskRunner.service # No root access? Use watch instead: nohup watch -n 2 /usr/local/bin/php /home/user/vendor/truecastdesign/true/workers/taskRunner.php \ > /home/user/logs/taskqueue.log 2>&1 & ``` -------------------------------- ### Systemd Service Configuration Source: https://github.com/truecastdesign/truefw/blob/master/docs/TaskQueue.md Example ExecStart line for a systemd service file to run the task runner script. Ensure the PHP executable path and script path are correct for your environment. ```service ExecStart=/usr/local/bin/ea-php56 /home/username/vendor/truecastdesign/true/cron/taskRunner.php ``` -------------------------------- ### AuthMiddleware Implementation Source: https://github.com/truecastdesign/truefw/blob/master/docs/Routes.md An example middleware class with an __invoke method that performs authentication. It returns true if authentication succeeds, false otherwise. ```php authenticate(['type'=>'bearer'])) { return true; } else { return false; } } } ``` -------------------------------- ### Define Routes for Specific HTTP Methods Source: https://github.com/truecastdesign/truefw/blob/master/docs/Routes.md Use specific methods like get, post, put, etc., to match requests with the exact HTTP method. ```php $App->router->get(...); $App->router->post(...); $App->router->put(...); $App->router->patch(...); $App->router->delete(...); $App->router->options(...); ``` -------------------------------- ### Run Nonce Tests Source: https://github.com/truecastdesign/truefw/blob/master/docs/Nonce.md Executes the unit tests for the Nonce class using PHPUnit. Ensure PHPUnit is installed and configured in your project. ```shell % phpunit tests/NonceTest.php ``` -------------------------------- ### map(['GET', 'POST', 'PUT'], '/contact') Source: https://context7.com/truecastdesign/truefw/llms.txt Handles requests to the /contact endpoint using GET, POST, or PUT methods, rendering the 'contact.phtml' view. ```APIDOC ## map(['GET', 'POST', 'PUT'], '/contact') ### Description Accepts GET, POST, or PUT requests to the /contact endpoint and renders the `contact.phtml` view. The framework will look for and include a corresponding controller file if it exists. ### Method GET, POST, PUT ### Endpoint `/contact` ### Parameters No explicit parameters are defined for this route, but it accepts data via the request body for POST and PUT methods. ``` -------------------------------- ### View Meta Data Example Source: https://github.com/truecastdesign/truefw/blob/master/README.md Shows the format for meta data at the top of .phtml view files, including title, description, CSS, and JS includes. This data is processed by the template engine. ```php title="Title of the page for the title tag" description="The meta description content." {endmeta} ``` -------------------------------- ### Get Configuration Object from File Source: https://github.com/truecastdesign/truefw/blob/master/docs/App.md Retrieve a configuration object from a specified .ini file without loading it into the App object. This method can also fetch a single value if a key is provided. ```php $configObj = $App->getConfig('configfile.ini'); echo $configObj->key; ``` ```php $value = $App->getConfig('configfile.ini', 'key'); ``` -------------------------------- ### Create Nonce with Custom Length Source: https://github.com/truecastdesign/truefw/blob/master/docs/Nonce.md Generates a nonce token with a specified length by passing the desired length as the first argument to the create method. This example creates a 16-character nonce. ```php $nonce = \True\Nonce::create(16); echo $nonce; ``` -------------------------------- ### GET /api/user/:id Source: https://context7.com/truecastdesign/truefw/llms.txt Retrieves a user by their ID from the database. ```APIDOC ## GET /api/user/:id ### Description Fetches a user record from the database using the provided user ID from the URL segment. ### Method GET ### Endpoint `/api/user/:id` ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the user to retrieve, captured from the URL. ### Response #### Success Response (200) - **(object)** - A JSON object representing the user, or an error object if not found. ``` -------------------------------- ### Systemd Service Management Commands Source: https://github.com/truecastdesign/truefw/blob/master/docs/TaskQueue.md Commands to manage the systemd task runner service. Use daemon-reload after modifying the service file, enable and start the service, and check its status. ```shell systemctl daemon-reload systemctl enable --now taskRunner.service ``` ```shell systemctl status taskRunner.service ``` ```shell systemctl stop taskRunner.service systemctl disable taskRunner.service ``` ```shell systemctl restart taskRunner.service ``` ```shell systemctl daemon-reload ``` -------------------------------- ### GET /api/orders/*:id Source: https://context7.com/truecastdesign/truefw/llms.txt Retrieves details for a specific order using its ID, within an API route group protected by authentication middleware. ```APIDOC ## GET /api/orders/*:id ### Description Fetches details for a specific order identified by its ID. This route is part of a group that requires authentication. ### Method GET ### Endpoint `/api/orders/*:id` ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the order to retrieve, captured from the URL. ### Response #### Success Response (200) - **order_id** (string) - The ID of the order. ``` -------------------------------- ### Instantiate True\App with Configuration Files Source: https://github.com/truecastdesign/truefw/blob/master/docs/App.md Initialize the App class by passing an array of configuration file paths to the constructor. This loads settings from the specified .ini files. ```php $App = new \True\App(['config1.ini', 'config2.ini']); ``` -------------------------------- ### Initialize True Framework Application Source: https://context7.com/truecastdesign/truefw/llms.txt Bootstrap the application by including the autoloader, defining the base path, and instantiating the App container with configuration files. Core services like Request, Response, Router, and PhpView are attached to the App container. Optionally, a database connection can be established. ```php config->site->title, $App->config->site->debug, etc. are now available // Attach core services $App->request = new True\Request; $App->response = new True\Response; $App->router = new True\Router($App->request); $App->view = new True\PhpView; // Optionally add a database connection (Hopper is a PDO wrapper) try { $dbConfig = $App->getConfig('MySQL.ini'); if (is_object($dbConfig)) { $App->db = new Truecast\Hopper($dbConfig); } } catch (PDOException $ex) { echo $ex->getMessage(); } // Load a config file later (e.g., inside a controller) $App->load('mailer.ini'); echo $App->config->mailer->host; // value from [mailer] section // Read a flat config file (no section heading) into a variable $smtpConfig = $App->getConfig('smtp.ini'); echo $smtpConfig->host; // Read a single value from a flat config file $apiKey = $App->getConfig('keys.ini', 'stripe_key'); // Write a single value back to a config file $App->configUpdate('site', 'debug', 'true'); // section already loaded $App->configUpdate('other.ini', 'key', 'val'); // file not yet loaded // Redirect $App->go('/dashboard'); // Error handling — trigger errors anywhere; display them in the layout trigger_error("Record not found.", 256); // E_USER_ERROR trigger_error("Cache miss.", 512); // E_USER_WARNING trigger_error("Using default.", 1024); // E_USER_NOTICE // In the layout template: // displayErrors();?> // Benchmarking a code block $App->benchmarkStart(); // ... expensive operation ... echo $App->benchmarkEnd(); // "Completed in 12 ms" ``` -------------------------------- ### Initialize Request and Router Instances Source: https://github.com/truecastdesign/truefw/blob/master/docs/Routes.md Set up the Request and Router objects in your init.php file. The Router requires an instance of the Request class. ```php $App->request = new True\Request; $App->router = new True\Router($App->request); ``` -------------------------------- ### Initialize App with Request, Response, Router, and View Source: https://github.com/truecastdesign/truefw/blob/master/docs/App.md Assign core application components like Request, Response, Router, and View to the App object. The Router requires the Request object during initialization. ```php $App->request = new True\Request; $App->response = new True\Response; $App->router = new True\Router($App->request); $App->view = new True\PhpView; ``` -------------------------------- ### Initialize TrueFW Auth Component Source: https://context7.com/truecastdesign/truefw/llms.txt Instantiate the `TrueAuth` component, optionally specifying a custom path for token storage. ```php auth = new True\Auth; // or custom path: $App->auth = new True\Auth(['bearerTokensFile' => BP.'/app/data/auth-tokens']); ``` -------------------------------- ### Initialize PHP View Engine Source: https://github.com/truecastdesign/truefw/blob/master/README.md This line in init.php sets up the default PHP view engine. It can be modified to use other templating systems like Twig. ```php $App->view = new \True\PhpView(); ``` -------------------------------- ### Initialize Task Queue Source: https://github.com/truecastdesign/truefw/blob/master/docs/TaskQueue.md Instantiate the TaskQueue class in your init.php file. You can specify a custom database path; it will be created if it doesn't exist. Pass any necessary objects to the task scripts using passObjects. ```php $App->TaskQueue = new True\TaskQueue(BP.'/data/tasks.sqlite'); $App->TaskQueue->passObjects(['App'=>$App]); ``` -------------------------------- ### Instantiate the True\App Class Source: https://github.com/truecastdesign/truefw/blob/master/docs/App.md Create a new instance of the App class. This object acts as a container for general application objects. ```php $App = new \True\App; ``` -------------------------------- ### Redirect to Another Page Source: https://github.com/truecastdesign/truefw/blob/master/docs/App.md Use the go method for simple redirects. It sets the appropriate header and exits the script. ```php $App->go('/path/page'); ``` -------------------------------- ### Enqueue Background Task with True Task Queue Source: https://context7.com/truecastdesign/truefw/llms.txt Initialize the task queue and enqueue a background task from a controller. Ensure the task script exists at the specified path. ```php TaskQueue = new True\TaskQueue(BP.'/data/tasks.sqlite'); $App->TaskQueue->passObjects(['App' => $App]); // In a controller — enqueue a background task after form submission $App->router->post('/contact', function($request) use ($App) { $input = $request->post; // sanitised POST data try { // Looks for the script at /app/tasks/send-contact-email.php $App->TaskQueue->addTask('send-contact-email.php', [ 'fullName' => $input->fullName, 'email' => $input->email, 'message' => $input->message, ]); echo json_encode(['result' => 'Message received — we will reply shortly.']); } catch (Exception $e) { trigger_error($e->getMessage(), 256); echo json_encode(['result' => 'error', 'message' => $e->getMessage()]); } }); ``` -------------------------------- ### Set Dynamic View Metadata and Render Source: https://context7.com/truecastdesign/truefw/llms.txt Set dynamic metadata like title, description, and OG image before rendering a view. Requires the `TruePhpView` component. ```php view->title = "User Profile — ACME"; $App->view->description = "View and edit your ACME account profile."; $App->view->ogImage = "https://example.com/assets/images/profile-og.jpg"; $App->view->render('user/profile.phtml', [ 'user' => $user, 'posts' => $posts, ]); ``` -------------------------------- ### Define a Catch-All Route Source: https://github.com/truecastdesign/truefw/blob/master/docs/Routes.md Use a catch-all pattern '/*:path' to handle any path not explicitly defined. It includes a controller and renders a view based on the path. ```php $App->router->any('/*:path', function($request) use ($App) { $vars = []; @include $App->router->controller($request->route->path); # check selected nav item $vars['selNav'] = ['/'.$request->route->path => true]; $App->view->render($request->route->path.'.phtml', $vars); }); ``` -------------------------------- ### Load Configuration Files Dynamically Source: https://github.com/truecastdesign/truefw/blob/master/docs/App.md Use the load method to dynamically load configuration files into the App object. This is useful within controllers or other scripts. It accepts a single filename or an array of filenames. ```php $App->load('configfile.ini'); $App->load(['config1.ini', 'config2.ini']); ``` -------------------------------- ### Define a Redirect Route Source: https://github.com/truecastdesign/truefw/blob/master/docs/Routes.md Use the redirect method to set up a 301 redirect for a given request URI, using a JSON lookup file. ```php $App->router->redirect(['request'=>$_SERVER['REQUEST_URI'], 'lookup'=>BP.'/redirects.json', 'type'=>'301']); ``` -------------------------------- ### Catch-all Route Source: https://context7.com/truecastdesign/truefw/llms.txt A convention-based route that matches any remaining URL path, rendering a corresponding view file and optionally including a controller. ```APIDOC ## Catch-all Route (`/*:path`) ### Description This route acts as a fallback, matching any URL path not explicitly defined by other routes. It attempts to render a view file named after the path and can optionally include a controller file if one exists. ### Method ANY ### Endpoint `/*:path` ### Parameters #### Path Parameters - **path** (string) - Required - The remaining part of the URL path. ### Behavior 1. Checks for a controller file at `app/controllers/{path}`. 2. If found, the controller file is included. 3. Renders a view file located at `{path}.phtml`. 4. Passes application configuration and selected navigation data to the view. ``` -------------------------------- ### Instantiate TrueAuth with Default Token Path Source: https://github.com/truecastdesign/truefw/blob/master/docs/Auth.md Instantiates the True\Auth class using the default path for storing bearer tokens. ```php # default path $App->auth = new True\Auth; ``` -------------------------------- ### Define Routes with TrueFW Router Source: https://context7.com/truecastdesign/truefw/llms.txt Declare routes in app/routes.php, ordered from most specific to most general. Supports redirects, named-method routes, and convention-based catch-all routes. ```php router->redirect([ 'request' => $_SERVER['REQUEST_URI'], 'lookup' => BP.'/redirects.json', 'type' => '301' ]); // Named-method routes (GET, POST, PUT, PATCH, DELETE, OPTIONS) $App->router->get('/api/user/:id', function($request) use ($App) { $userId = $request->route->id; // captured from :id segment $user = $App->db->row("SELECT * FROM users WHERE id = ?", [$userId]); echo json_encode($user ?: ['error' => 'Not found']); }); $App->router->post('/api/user', function($request) use ($App) { $data = json_decode(file_get_contents('php://input'), true); // ... create user ... echo json_encode(['result' => 'created']); }); // Accept several HTTP methods at once $App->router->map(['GET', 'POST', 'PUT'], '/contact', 'contact.php'); // Framework looks for /app/controllers/contact.php and includes it; // $App and $request are automatically in scope inside that file. // Route groups — middleware runs before child routes are evaluated $App->router->group('/api/*', function() use ($App) { $App->router->get('/api/orders/*:id', function($request) use ($App) { echo json_encode(['order_id' => $request->route->id]); }); $App->router->delete('/api/orders/*:id', function($request) use ($App) { // ... delete logic ... echo json_encode(['result' => 'deleted']); }); }, [ new App\AuthMiddleware ]); // middleware class with __invoke returning bool // Convention-based catch-all (always last) $App->router->any('/*:path', function($request) use ($App) { $vars = []; // Optionally include a matching controller if (file_exists($App->router->controller($request->route->path))) { @include $App->router->controller($request->route->path); } $vars['config'] = $App->config; $vars['selectedNav'] = (object) [$request->route->path => ' class="sel"']; $App->view->render($request->route->path . '.phtml', $vars); }); ``` -------------------------------- ### Base Layout with Dynamic Assets Source: https://context7.com/truecastdesign/truefw/llms.txt A base layout template that includes dynamic title, meta description, and automatically merged/minified CSS and JS assets via `$App->view->cssoutput` and `$App->view->jsoutput`. ```php view->isset('title')): <?= $App->view->title ?> view->isset('description')): view->cssoutput ?> displayErrors(); ?> view->html ?> view->jsoutput ?> ``` -------------------------------- ### Benchmark Process Execution Time Source: https://github.com/truecastdesign/truefw/blob/master/docs/App.md Measure the execution time of a code block using benchmarkStart and benchmarkEnd methods. The benchmarkEnd method returns the elapsed time. ```php $App->benchmarkStart(); // run some code echo $App->benchmarkEnd(); ``` -------------------------------- ### Run Task Runner with Watch Command Source: https://github.com/truecastdesign/truefw/blob/master/docs/TaskQueue.md Alternative method to run the task runner script using the 'watch' command for environments without root access. This command runs the script every 2 seconds and logs output to a specified file. ```shell nohup watch -n 2 /usr/local/bin/ea-php56 /home/username/vendor/truecastdesign/true/workers/taskRunner.php > /home/username/logs/taskqueue.log 2>&1 & ``` -------------------------------- ### Update Configuration Value in File Source: https://github.com/truecastdesign/truefw/blob/master/docs/App.md Write a single configuration value to a .ini file using the configUpdate method. If the file is loaded, provide the section and key. Otherwise, specify the filename or path. ```php $App->configUpdate('mysection', 'key', 'value'); ``` -------------------------------- ### Define View Metadata and Content Source: https://context7.com/truecastdesign/truefw/llms.txt Define view metadata (title, description, CSS, JS) in an INI-style block and provide HTML content. Supports including partials using `{partial:filename.phtml}`. ```php

name) ?>

bio) ?>

title) ?>

excerpt) ?>

{partial:sidebar.phtml} ``` -------------------------------- ### Define a Route with Controller File Source: https://github.com/truecastdesign/truefw/blob/master/docs/Routes.md Specify a route that directly maps to a controller file within the /app/controllers directory. The $App and $request objects are available in the included script. ```php $App->router->get('/path/:id', 'filename.php'); ``` -------------------------------- ### Instantiate TrueAuth with Custom Token Path Source: https://github.com/truecastdesign/truefw/blob/master/docs/Auth.md Instantiates the True\Auth class with a custom path for storing bearer tokens. ```php # custom path $App->auth = new True\Auth(['bearerTokensFile'=>BP.'/app/other-path/auth-tokens']); ``` -------------------------------- ### Debugging Helper Functions in PHP Source: https://context7.com/truecastdesign/truefw/llms.txt Use these functions for debugging purposes. `pr()` provides preformatted HTML output, `p()` provides plain text output, `dump()` provides labeled var_dump, and `pMethods()` lists object methods. ```php config); // Output:
stdClass Object ( [site] => ... ) 
``` ```php // p($item) — plain print_r p(['key' => 'value']); ``` ```php // dump($obj, $label) — labeled var_dump dump($user, 'User object'); ``` ```php // pMethods($obj) — list all methods of an object (API exploration) pMethods($App->db); // Output: Array ( [0] => query [1] => row [2] => ... ) ``` -------------------------------- ### Define a Dynamic Route with Controller Inclusion Source: https://github.com/truecastdesign/truefw/blob/master/docs/Routes.md Create a route that accepts a dynamic ID parameter. It includes a controller file and sets view meta data before rendering. ```php $App->router->any('/path/:id', function($request) use ($App) { $vars = []; # include controller require BP.'/app/controllers/filename.php'; # set the title and description meta data if the page is dynamically generated $App->view->title = "Title Tag Text"; $App->view->description = "Meta description text."; # render the view $App->view->render('_layouts/filename.phtml', $vars); }); ``` -------------------------------- ### Create a Route Group Source: https://github.com/truecastdesign/truefw/blob/master/docs/Routes.md Group routes under a common path prefix (e.g., '/api/*'). This can improve routing efficiency and allows for middleware application. ```php $App->router->group('/api/*', function() use ($App) { # code in here only runs if path matches /api/ and /api/[any further path parts] $App->router->get('/api/user/*:id', function($request) use ($App) { echo $request->route->id; }); }); ``` -------------------------------- ### Access Configuration Values Source: https://github.com/truecastdesign/truefw/blob/master/docs/App.md Retrieve configuration values loaded into the App object via the config property. Values are accessed using section and key notation. ```php echo $App->config->mysection->key; ``` -------------------------------- ### Map Route to Multiple HTTP Methods Source: https://github.com/truecastdesign/truefw/blob/master/docs/Routes.md Use the map method to associate a single route with multiple HTTP methods. ```php $App->router->map(['GET', 'POST', 'PUT'], '/path', 'controller.php'); ``` -------------------------------- ### Apply Middleware to Route Groups Source: https://github.com/truecastdesign/truefw/blob/master/docs/Routes.md Assign middleware classes to a route group. Middleware runs before the route handler and can prevent execution by returning false. ```php $App->router->group('/api/*', function() use ($App) { $App->router->get('/api/user/*:id', function($request) use ($App) { echo $request->route->id; }); }, [ new \App\AuthMiddleware ]); ``` -------------------------------- ### Generate Bearer Token with TrueAuth Source: https://github.com/truecastdesign/truefw/blob/master/docs/Auth.md Generates a new Bearer token and saves it to a file. The token file location can be customized during class instantiation. ```php echo $App->auth->requestToken(); ``` -------------------------------- ### Process Background Task with True Task Queue Source: https://context7.com/truecastdesign/truefw/llms.txt This script runs as a background task, processing data passed from the enqueueing script. It uses injected objects and configuration to send an email. ```php getConfig('contact-email-info.ini'); $Mail = new \PHPMailer\PHPMailer(true); try { $Mail->isSMTP(); $Mail->Host = $config->host; $Mail->SMTPAuth = true; $Mail->Username = $config->username; $Mail->Password = $config->password; $Mail->SMTPSecure = 'tls'; $Mail->Port = $config->port; $Mail->setFrom($config->from_email, $config->from_name); $Mail->addAddress($config->to_email); $Mail->addReplyTo($taskData->email, $taskData->fullName); $Mail->isHTML(true); $Mail->Subject = $config->subject; $Mail->Body = nl2br(htmlspecialchars($taskData->message)); $Mail->send(); } catch (Exception $e) { error_log("Mailer Error: {$Mail->ErrorInfo}", 3, BP.'/php-error.log'); } ``` -------------------------------- ### Create Default Nonce Source: https://github.com/truecastdesign/truefw/blob/master/docs/Nonce.md Generates a nonce token with the default length of 32 characters. The output will be a string of alphanumeric characters. ```php $nonce = \True\Nonce::create(); echo $nonce; ``` -------------------------------- ### AuthMiddleware::__invoke Source: https://context7.com/truecastdesign/truefw/llms.txt The middleware method that performs authentication checks. ```APIDOC ## AuthMiddleware::__invoke ### Description This method is automatically called by route groups to authenticate requests. It returns `true` if authentication is successful, allowing the request to proceed, and `false` otherwise. ### Method `__invoke` ### Parameters - **request** (` equest` object) - Required - The incoming request object. ### Return Value - **bool** - `true` if authenticated, `false` otherwise. ``` -------------------------------- ### Add Task to Queue Source: https://github.com/truecastdesign/truefw/blob/master/docs/TaskQueue.md Call addTask on the TaskQueue instance to queue and run a script in the background. By default, it looks in BP.'/app/tasks/'. You can pass an array of variables that will be available in the task script. ```php try { $App->TaskQueue->addTask('task.php', ['var1'=>1]); } catch (Exception $e) { trigger_error($e->getMessage(), 256); } ``` -------------------------------- ### Implement Route Middleware with __invoke Source: https://context7.com/truecastdesign/truefw/llms.txt Middleware classes are invoked automatically by route groups. Return true to allow routes to run, or false to block them. Ensure the middleware class is correctly namespaced. ```php authenticate(['type' => 'bearer']); } } // Usage in routes.php: $App->router->group('/admin/*', function() use ($App) { $App->router->get('/admin/dashboard', function($request) use ($App) { $App->view->render('admin/dashboard.phtml', []); }); }, [ new App\AuthMiddleware ]); // If AuthMiddleware::__invoke returns false, /admin/dashboard is never reached. ``` -------------------------------- ### Redirect Route Source: https://context7.com/truecastdesign/truefw/llms.txt Defines a 301 redirect based on the request URI and a JSON lookup file. ```APIDOC ## Redirect Route ### Description Sets up a 301 redirect by looking up the current request URI in a specified JSON file. ### Method `redirect` ### Parameters - **request** (string) - Required - The current request URI (e.g., `$_SERVER['REQUEST_URI']`). - **lookup** (string) - Required - The path to the JSON file containing redirect mappings. - **type** (string) - Required - The type of redirect, typically '301'. ``` -------------------------------- ### Authenticate User with Username and Password (Login Token) Source: https://github.com/truecastdesign/truefw/blob/master/docs/Auth.md Authenticates a user based on a login token, typically stored in a cookie. Returns the user ID if authentication is successful. ```php $userId = $App->auth->authenticate(['type'=>'login-token', 'token'=>$_COOKIE['login_cookie']]); if (is_numeric($userId)) { echo json_encode(['result'=>'success', 'page'=>$output]); } else { echo json_encode(['result'=>'not logged in']); } ``` -------------------------------- ### Temporarily Set Configuration Value Source: https://github.com/truecastdesign/truefw/blob/master/docs/App.md Modify a configuration value in memory. This change is temporary and not written to the config file. ```php $App->config->mysection->key = 'value'; ``` -------------------------------- ### POST /api/user Source: https://context7.com/truecastdesign/truefw/llms.txt Creates a new user based on the data provided in the request body. ```APIDOC ## POST /api/user ### Description Creates a new user by processing JSON data sent in the request body. ### Method POST ### Endpoint `/api/user` ### Parameters #### Request Body - **(JSON)** - Required - Contains the data for the new user. ### Response #### Success Response (200) - **result** (string) - Indicates the outcome of the user creation (e.g., 'created'). ``` -------------------------------- ### Create Nonce with Custom Timestamp Source: https://github.com/truecastdesign/truefw/blob/master/docs/Nonce.md Generates a nonce token using a specific timestamp. This is typically not needed as the library uses the current time by default. The first argument specifies the length, and the second argument is the Unix timestamp. ```php $nonce = \True\Nonce::create(32, 1660338149); ``` -------------------------------- ### Authenticate Session-Based Login with Cookie Source: https://context7.com/truecastdesign/truefw/llms.txt Authenticate a user based on a login-token cookie. If the token is valid, it returns the user ID; otherwise, it redirects to the login page. ```php $App->router->get('/account', function($request) use ($App) { $userId = $App->auth->authenticate([ 'type' => 'login-token', 'token' => $_COOKIE['login_cookie'] ?? '' ]); if (is_numeric($userId)) { $user = $App->db->row("SELECT * FROM users WHERE id = ?", [$userId]); $App->view->render('account.phtml', ['user' => $user]); } else { $App->go('/login'); } }); ``` -------------------------------- ### Route Groups with Middleware Source: https://context7.com/truecastdesign/truefw/llms.txt Groups routes under a common path prefix and applies middleware to protect them. ```APIDOC ## Route Groups with Middleware ### Description Organizes routes into logical groups and applies middleware to all routes within the group. The middleware must return `true` for the routes to be executed. ### Usage ```php $App->router->group('/api/*', function() use ($App) { // Routes within this group $App->router->get('/api/orders/*:id', ...); $App->router->delete('/api/orders/*:id', ...); }, [ new amespace o he\AuthMiddleware ]); ``` ### Parameters - **path_prefix** (string) - The prefix for all routes within the group (e.g., `/api/*`). - **callback** (callable) - A closure containing the route definitions for the group. - **middleware** (array) - An array of middleware instances to apply to the group. ``` -------------------------------- ### Generate and Use Nonce Tokens with True Nonce Source: https://context7.com/truecastdesign/truefw/llms.txt Create cryptographically seeded nonce tokens of configurable length for security purposes. Use the generated nonce for CSRF protection by embedding it in forms and validating on submission. ```php "> // Validate on form submission $App->router->post('/settings', function($request) use ($App) { if (!hash_equals($_SESSION['csrf_nonce'] ?? '', $request->post->csrf ?? '')) { http_response_code(403); echo json_encode(['result' => 'CSRF validation failed']); return; } // safe to process... }); ``` -------------------------------- ### Display System Errors Source: https://github.com/truecastdesign/truefw/blob/master/docs/App.md Render system errors nicely on the page using the displayErrors method of the App class. ```php displayErrors()?> ``` -------------------------------- ### Currency and Escaping Helper Functions in PHP Source: https://context7.com/truecastdesign/truefw/llms.txt Format numbers as currency strings or escape strings for safe output in various contexts. `currency()` formats numbers, while `esc()` handles HTML, email, URL, float, int, and nohtml contexts. ```php // currency($str) — format as US currency string echo currency(1234.5); // $1,234.50 echo currency('99'); // $99.00 ``` ```php // esc($str, $type) — context-aware output escaping echo esc(''); // HTML-safe string (default) echo esc('user@example.com', 'email'); // sanitised email echo esc('hello world/path', 'url'); // sanitised URL echo esc('3.14abc', 'float'); // numeric float echo esc('42xyz', 'int'); // numeric int echo esc('bold text', 'nohtml'); // strip tags + HTML encode ``` -------------------------------- ### Generate Bearer Token Source: https://context7.com/truecastdesign/truefw/llms.txt Generate a bearer token and persist it to the configured token file. This is typically a one-time operation to obtain a token for API clients. ```php // 1. Generate a token and persist it (run once; copy output to your API client) echo $App->auth->requestToken(); // Output written to /app/data/auth-tokens, e.g.: // aB3xQ7...64-char-token...zR9w ``` -------------------------------- ### Debug Task Script via Terminal Source: https://github.com/truecastdesign/truefw/blob/master/docs/TaskQueue.md Manually run the task runner script from the terminal for debugging purposes. Adjust the PHP version and script path as necessary. ```shell /usr/local/bin/ea-php82 /home/username/vendor/truecastdesign/true/workers/taskRunner.php ``` -------------------------------- ### Authenticate API Request with Bearer Token Source: https://context7.com/truecastdesign/truefw/llms.txt Verify a bearer token sent in the `Authorization` header for API requests. Returns `true` if authentication is successful, otherwise `false`. ```php // 3. In the route handler / controller — verify the bearer token $App->router->post('/api/orders', function($request) use ($App) { if ($App->auth->authenticate(['type' => 'bearer'])) { $data = json_decode(file_get_contents('php://input'), true); // ... process order ... echo json_encode(['result' => 'success', 'order_id' => 42]); } else { http_response_code(401); echo json_encode(['result' => 'bearer token invalid']); } }); ``` -------------------------------- ### Authenticate API Request with Bearer Token Source: https://github.com/truecastdesign/truefw/blob/master/docs/Auth.md Checks if an incoming API request is authorized using a Bearer token. The token should be provided in the 'Authorization: Bearer ' header. ```php if ($App->auth->authenticate(['type'=>'bearer'])) { echo json_encode(['result'=>'success']); } else { echo json_encode(['result'=>'bearer token invalid']); } ``` -------------------------------- ### Trigger Errors Source: https://github.com/truecastdesign/truefw/blob/master/docs/App.md Utilize the trigger_error function with specific error codes to log or display errors. Different constants (256, 512, 1024) correspond to Error, Warning, and Notice levels. ```php trigger_error("Error message!", 256); ``` ```php trigger_error("Error message!", 512); ``` ```php trigger_error("Error message!", 1024); ``` -------------------------------- ### DELETE /api/orders/*:id Source: https://context7.com/truecastdesign/truefw/llms.txt Deletes a specific order using its ID, within an API route group protected by authentication middleware. ```APIDOC ## DELETE /api/orders/*:id ### Description Deletes a specific order identified by its ID. This route is part of a group that requires authentication. ### Method DELETE ### Endpoint `/api/orders/*:id` ### Parameters #### Path Parameters - **id** (string) - Required - The ID of the order to delete, captured from the URL. ### Response #### Success Response (200) - **result** (string) - Indicates the outcome of the deletion (e.g., 'deleted'). ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.