### Install Phalcon using PIE Source: https://github.com/phalcon/cphalcon/blob/master/README.md Use the PIE installer for a modern PHP extension installation. This is the recommended method. ```bash pie install phalcon/cphalcon ``` -------------------------------- ### Setup Codeception Configuration and Docker Source: https://github.com/phalcon/cphalcon/blob/master/tests/README.md Copy the default environment file for Codeception configuration and start Docker containers in detached mode. ```shell cp tests/_config/.env.default .env cd tests docker-compose up -d cd .. ``` -------------------------------- ### Start Nanobox Environment Source: https://github.com/phalcon/cphalcon/blob/master/tests/README.md Initiates the Nanobox development environment. This command builds and starts the container, mounting local source code and providing access to tools like Zephir. ```shell $ nanobox run ``` -------------------------------- ### Install Phalcon Framework Source: https://context7.com/phalcon/cphalcon/llms.txt Instructions for installing the Phalcon PHP extension using PIE or PECL, and enabling it in php.ini. ```bash # Using PIE (recommended) pie install phalcon/cphalcon # Using PECL pecl install phalcon # Enable in php.ini echo "extension=phalcon.so" >> /etc/php/8.1/cli/php.ini ``` -------------------------------- ### Install Composer Dependencies Source: https://github.com/phalcon/cphalcon/blob/master/tests/README.md Run this command from the project root to install necessary Composer packages for the testing suite. ```shell composer install --prefer-source ``` -------------------------------- ### Setup Databases with Nanobox Script Source: https://github.com/phalcon/cphalcon/blob/master/tests/README.md Executes a Nanobox-specific script to set up the databases. This script populates the databases with necessary data for testing. ```shell /app $ tests/_ci/nanobox/setup-dbs-nanobox.sh ``` -------------------------------- ### Install Phalcon using PECL Source: https://github.com/phalcon/cphalcon/blob/master/README.md Install the Phalcon extension using the PECL package manager. Ensure PECL is configured correctly. ```bash pecl install phalcon ``` -------------------------------- ### Phalcon Session Management with File Adapter Source: https://context7.com/phalcon/cphalcon/llms.txt Illustrates session management using Phalcon's Session Manager with a file-based adapter. Covers starting, setting, getting, checking existence, removing, and destroying session data. Also shows the usage of session bags for namespaced storage. ```php use Phalcon\Session\Manager; use Phalcon\Session\Adapter\Stream as SessionStream; use Phalcon\Storage\SerializerFactory; $serializer = new SerializerFactory(); // File-based session handler $adapter = new SessionStream([ "savePath" => "/tmp/sessions", ]); $session = new Manager(["uniqueId" => "myapp"]); $session->setAdapter($adapter); $session->start(); // Store values $session->set("user_id", 42); $session->set("auth", ["role" => "admin", "token" => bin2hex(random_bytes(16))]); // Retrieve $userId = $session->get("user_id"); $auth = $session->get("auth"); // Check existence if ($session->has("user_id")) { echo "Logged in as user " . $session->get("user_id"); } // Remove a key $session->remove("auth"); // Destroy the session (logout) $session->destroy(); // Session bag (namespaced storage per class/component) $bag = new \Phalcon\Session\Bag($session, "cart"); $bag->set("items", [["sku" => "P1", "qty" => 2]]); $bag->set("total", 49.99); echo $bag->get("total"); // 49.99 ``` -------------------------------- ### Copy Environment File Source: https://github.com/phalcon/cphalcon/blob/master/tests/README.md Copies the example environment file to .env. This file typically contains database credentials and other configuration settings. ```shell /app $ cp tests/_ci/nanobox/.env.example .env ``` -------------------------------- ### Check Zephir Installation Source: https://github.com/phalcon/cphalcon/blob/master/tests/README.md Verify that Zephir is installed and accessible within the Nanobox environment. This command should display the Zephir help screen. ```shell /app $ zephir ``` -------------------------------- ### Phalcon MVC Application Setup Source: https://context7.com/phalcon/cphalcon/llms.txt Sets up a Phalcon MVC application, including registering database and view services, and handling both single-module and multi-module architectures. Includes basic exception handling. ```php use Phalcon\Di\FactoryDefault; use Phalcon\Mvc\Application; // public/index.php $di = new FactoryDefault(); // Register DB $di->setShared("db", function () { return new \Phalcon\Db\Adapter\Pdo\Mysql([ "host" => "localhost", "username" => "root", "password" => "", "dbname" => "myapp", ]); }); // Register view $di->setShared("view", function () { $view = new \Phalcon\Mvc\View(); $view->setViewsDir(APP_PATH . "/views/"); return $view; }); try { $app = new Application($di); // Multi-module registration $app->registerModules([ "frontend" => [ "className" => \Frontend\Module::class, "path" => APP_PATH . "/modules/frontend/Module.php", ], "backend" => [ "className" => \Backend\Module::class, "path" => APP_PATH . "/modules/backend/Module.php", ], ]); $response = $app->handle($_SERVER["REQUEST_URI"]); $response->send(); } catch (\Exception $e) { echo "Error: " . $e->getMessage(); } ``` -------------------------------- ### Initialize and Use Phalcon Cache with Redis Source: https://context7.com/phalcon/cphalcon/llms.txt Demonstrates setting up the Cache component with a Redis adapter and performing basic operations like set, get, has, delete, setMultiple, getMultiple, deleteMultiple, and clear. Supports storing values with TTL using DateInterval or seconds. ```php use Phalcon\Cache\Cache; use Phalcon\Cache\AdapterFactory; use Phalcon\Storage\SerializerFactory; $serializer = new SerializerFactory(); $factory = new AdapterFactory($serializer); // Redis adapter $redisAdapter = $factory->newInstance("redis", [ "host" => "127.0.0.1", "port" => 6379, "index" => 0, "defaultTtl" => 3600, "prefix" => "myapp-", ]); $cache = new Cache($redisAdapter); // Store a value with TTL (DateInterval or seconds) $cache->set("user:42", ["name" => "Alice", "role" => "admin"], new \DateInterval("PT1H")); // Retrieve (returns null or $default on miss) $user = $cache->get("user:42"); if ($user === null) { $user = Users::findFirst(42)->toArray(); $cache->set("user:42", $user, 3600); } // Check existence if ($cache->has("user:42")) { echo "Cached!"; } // Delete single key $cache->delete("user:42"); // Multiple operations $cache->setMultiple([ "cfg:theme" => "dark", "cfg:language" => "en", ], 86400); $values = $cache->getMultiple(["cfg:theme", "cfg:language"]); $cache->deleteMultiple(["cfg:theme", "cfg:language"]); // Flush all keys $cache->clear(); ``` -------------------------------- ### Phalcon Autoloader Setup Source: https://context7.com/phalcon/cphalcon/llms.txt Configure the Phalcon Autoloader to manage class loading via PSR-4/PSR-0 namespaces, explicit class-to-file mappings, or by scanning directories. It can also include arbitrary files and be activated/deactivated. ```php use Phalcon\Autoload\Loader; $loader = new Loader(); // Register PSR-4 namespaces $loader->setNamespaces([ "App\Controllers" => APP_PATH . "/controllers/", "App\Models" => APP_PATH . "/models/", "App\Services" => APP_PATH . "/services/", "Vendor\Lib" => BASE_PATH . "/vendor/lib/src/", ]); // Register explicit class-to-file mappings $loader->setClasses([ "SpecialClass" => APP_PATH . "/special/SpecialClass.php", ]); // Register directories to scan (slower — use namespaces when possible) $loader->setDirectories([APP_PATH . "/library/"]); // Add additional file extensions to look for $loader->setExtensions(["php", "inc"]); // Include arbitrary files on every request $loader->setFiles([ APP_PATH . "/config/constants.php", APP_PATH . "/config/helpers.php", ]); // Activate $loader->register(); // Debug: trace the loader's resolution steps $loader->setDebug(true); $loader->loadClass("App\Controllers\HomeController"); print_r($loader->getDebug()); /* Array( [0] => Load: App\Controllers\HomeController [1] => Find: App/Controllers/HomeController.php [2] => Require: /var/www/app/controllers/HomeController.php ) */ // De-register when no longer needed $loader->unregister(); ``` -------------------------------- ### Phalcon HTTP Request Methods Source: https://context7.com/phalcon/cphalcon/llms.txt Checks the HTTP method of the incoming request (GET, POST, AJAX) and security (HTTPS). ```php use Phalcon\Http\Request; $request = new Request(); // Method checks $request->isGet(); // bool $request->isPost(); // bool $request->isAjax(); // bool (checks X-Requested-With header) $request->isSecure(); // bool (HTTPS?) ``` -------------------------------- ### Run Codeception with Debug Output Source: https://github.com/phalcon/cphalcon/blob/master/tests/README.md Use the --debug flag to get detailed output during test execution. This is useful for troubleshooting. ```shell /app $ php vendor/bin/codecept run --debug # Detailed output ``` -------------------------------- ### Available Environment Options Source: https://github.com/phalcon/cphalcon/blob/master/tests/README.md List of available environment options that can be used with the --env flag for targeted test execution. ```shell --env mysql ``` ```shell --env sqlite ``` ```shell --env pgsql ``` -------------------------------- ### Phalcon Logger with File Stream and Custom Formatting Source: https://context7.com/phalcon/cphalcon/llms.txt Demonstrates setting up a PSR-3 compatible logger using the file stream adapter with a custom line formatter. Shows how to log messages at various PSR-3 levels and configure multiple adapters for fan-out logging. ```php use Phalcon\Logger\Logger; use Phalcon\Logger\Adapter\Stream; use Phalcon\Logger\Formatter\Line; // File-stream adapter with custom format $formatter = new Line("[%date%][%type%] %message%", "Y-m-d H:i:s"); $adapter = new Stream("/var/log/app.log"); $adapter->setFormatter($formatter); $logger = new Logger("myLogger", ["main" => $adapter]); // PSR-3 log levels $logger->debug("Cache miss for key: user-42"); $logger->info("User {username} logged in", ["username" => "alice"]); $logger->notice("Deprecated method called"); $logger->warning("Disk space low: {percent}%", ["percent" => 85]); $logger->error("Failed to connect to {host}", ["host" => "db.internal"]); $logger->critical("Payment gateway unreachable"); $logger->alert("Database down — waking on-call engineer"); $logger->emergency("System is unusable"); // Multiple adapters (fan-out logging) $syslog = new \Phalcon\Logger\Adapter\Syslog("app", ["option" => LOG_CONS, "facility" => LOG_USER]); $logger2 = new Logger("multi", ["file" => $adapter, "sys" => $syslog]); $logger2->info("Logged to both file and syslog"); ``` -------------------------------- ### Phalcon\Mvc\Micro API Routes Source: https://context7.com/phalcon/cphalcon/llms.txt Defines GET and POST routes for a micro application, including a route with a named parameter and a middleware for authentication. ```APIDOC ## GET /api/users/{id:[0-9]+} ### Description Retrieves a user by their ID. ### Method GET ### Endpoint /api/users/{id:[0-9]+} ### Parameters #### Path Parameters - **id** (int) - Required - The ID of the user to retrieve. ### Response #### Success Response (200) - **user** (object) - The user object if found. #### Error Response (404) - **error** (string) - "Not found" message if the user does not exist. ## POST /api/users ### Description Creates a new user with the provided data. ### Method POST ### Endpoint /api/users ### Parameters #### Request Body - **field** (type) - Required/Optional - Description of the field. ### Request Example ```json { "example": "request body" } ``` ### Response #### Success Response (201) - **id** (int) - The ID of the newly created user. #### Error Response - **errors** (array) - An array of validation error messages if the user creation fails. ## Middleware: before ### Description This middleware runs before every route. It checks for a valid API token in the request headers. ### Method Applies to all HTTP methods. ### Response #### Success Response (200) Returns `true` if the token is valid, allowing the request to proceed. #### Error Response (401) Returns `false` and stops the request if the token is invalid. ``` -------------------------------- ### Configure Sparse Static Analyzer Source: https://github.com/phalcon/cphalcon/wiki/Static-code-analyzers Sets up the Sparse static analyzer with specific compiler flags for enhanced type semantic analysis. ```bash cd ext phpize ./configure CC=cgcc CFLAGS="-Wsparse-all" ``` -------------------------------- ### Phalcon HTTP Request Input Filtering Source: https://context7.com/phalcon/cphalcon/llms.txt Retrieves and filters POST and GET parameters, providing default values and applying specified filters. ```php // Filtered input (second arg = filter name, third = default) $name = $request->getPost("name", "striptags", "Anonymous"); $age = $request->getPost("age", "int", 0); $email = $request->getPost("email", "email", ""); $page = $request->getQuery("page", "int", 1); ``` ```php // Apply multiple filters at once $username = $request->getPost("username", ["trim", "lower", "alnum"]); ``` -------------------------------- ### Phalcon Controller Actions and DI Access Source: https://context7.com/phalcon/cphalcon/llms.txt Extend Phalcon\Mvc\Controller to handle actions and access DI services. Use `initialize` for setup and DI properties for service access. ```php namespace App\Controllers; use Phalcon\Mvc\Controller; class ProductsController extends Controller { // Runs before every action in this controller public function initialize(): void { $this->view->setVar("title", "Products"); } public function indexAction(): void { // Access DI services as properties: $this->request, $this->response, // $this->session, $this->db, $this->flash, $this->security … $this->view->products = Products::find(["order" => "name ASC"]); } public function createAction(): void { if (!$this->request->isPost()) { return $this->dispatcher->forward(["action" => "index"]); } $product = new Products(); $product->name = $this->request->getPost("name", "striptags"); $product->price = $this->request->getPost("price", "float"); $product->stock = $this->request->getPost("stock", "int"); if (!$product->save()) { foreach ($product->getMessages() as $msg) { $this->flash->error((string) $msg); } return $this->dispatcher->forward(["action" => "new"]); } $this->flash->success("Product created successfully."); $this->response->redirect("/products"); } public function deleteAction(int $id): void { $product = Products::findFirstOrFail($id); if (!$product->delete()) { $this->flash->error("Cannot delete product."); } $this->response->redirect("/products"); } } ``` -------------------------------- ### Execute a Single Test File Source: https://github.com/phalcon/cphalcon/blob/master/tests/README.md Run a specific test file. ```shell /app $ php vendor/bin/codecept run tests/unit/some/folder/some/test/file.php ```