### MVC Controller Example in PHP Source: https://context7.com/phalcon/ide-stubs/llms.txt Demonstrates the structure and common actions of a Phalcon MVC Controller, including accessing services, handling requests, and interacting with views. It shows how to define actions like index, show, create, and delete. ```php view->products = $products; } public function showAction($id) { $product = Products::findFirst($id); if (!$product) { // Forward to another action return $this->dispatcher->forward([ "controller" => "products", "action" => "notFound", ]); } $this->view->product = $product; } public function createAction() { if ($this->request->isPost()) { $product = new Products(); $product->assign( $this->request->getPost(), ["name", "price", "description"] ); if ($product->save()) { $this->flash->success("Product created successfully"); return $this->response->redirect("products/index"); } foreach ($product->getMessages() as $message) { $this->flash->error($message); } } } public function deleteAction($id) { $product = Products::findFirst($id); if ($product && $product->delete()) { $this->flash->success("Product deleted"); } return $this->response->redirect("products/index"); } } ``` -------------------------------- ### Install Phalcon IDE Stubs via Composer Source: https://github.com/phalcon/ide-stubs/blob/master/README.md Installs the Phalcon IDE Stubs package as a development dependency using Composer. This command ensures that the stubs are available for your project's development environment. ```bash composer require --dev phalcon/ide-stubs ``` -------------------------------- ### Phalcon Encryption: Symmetric Encryption with OpenSSL Source: https://context7.com/phalcon/ide-stubs/llms.txt Illustrates the use of Phalcon\Encryption\Crypt for symmetric encryption and decryption via OpenSSL. It supports various cipher algorithms and padding schemes. Examples cover setting ciphers, keys, encrypting/decrypting text, using Base64 encoding for transport, and configuring signing with HMAC. ```php setCipher("aes-256-ctr"); // Set encryption key (should be cryptographically secure) $key = "T4\xb1\x8d\xa9\x98\x05\\x8c\xbe\x1d\x07&[\x99\x18\xa4~Lc1\xbeW\xb3"; $crypt->setKey($key); // Encrypt text $plaintext = "The message to be encrypted"; $encrypted = $crypt->encrypt($plaintext); // Decrypt text $decrypted = $crypt->decrypt($encrypted); // Encrypt/decrypt with inline key $encrypted = $crypt->encrypt($plaintext, $key); $decrypted = $crypt->decrypt($encrypted, $key); // Base64 encoding for safe transport $encrypted = $crypt->encryptBase64($plaintext, $key); $decrypted = $crypt->decryptBase64($encrypted, $key); // URL-safe base64 $encrypted = $crypt->encryptBase64($plaintext, $key, true); $decrypted = $crypt->decryptBase64($encrypted, $key, true); // Configure padding $crypt->setPadding(Crypt::PADDING_PKCS7); $crypt->setPadding(Crypt::PADDING_ANSI_X_923); $crypt->setPadding(Crypt::PADDING_ISO_10126); // Enable/disable message signing (HMAC) $crypt->useSigning(true); // Set hash algorithm for signing $crypt->setHashAlgorithm("sha512"); // Get available ciphers $ciphers = $crypt->getAvailableCiphers(); // Get available hash algorithms $hashAlgorithms = $crypt->getAvailableHashAlgorithms(); // Get current settings $currentCipher = $crypt->getCipher(); $currentKey = $crypt->getKey(); $hashAlgo = $crypt->getHashAlgorithm(); // GCM/CCM mode with authentication data $crypt->setCipher("aes-256-gcm"); $crypt->setAuthData("additional authenticated data"); $crypt->setAuthTagLength(16); $encrypted = $crypt->encrypt($plaintext, $key); $authTag = $crypt->getAuthTag(); // Decrypt with auth tag $crypt->setAuthTag($authTag); $crypt->setAuthData("additional authenticated data"); $decrypted = $crypt->decrypt($encrypted, $key); ``` -------------------------------- ### HTTP Request Handling in PHP Source: https://context7.com/phalcon/ide-stubs/llms.txt Illustrates how to use the Phalcon\Http\Request class to access various aspects of an HTTP request, including methods, parameters, headers, client information, and file uploads. It covers filtering, sanitization, and retrieving data from different request types (GET, POST, PUT, etc.). ```php isPost() && $request->isAjax()) { echo "POST AJAX request received"; } // Method checks $request->isGet(); $request->isPut(); $request->isPatch(); $request->isDelete(); $request->isSecure(); // HTTPS check $request->isSoap(); // Get values from $_REQUEST with sanitization $userEmail = $request->get("user_email", "email"); $userId = $request->get("id", "int", 0); // With default value // Get values from $_POST $username = $request->getPost("username", "string"); $password = $request->getPost("password"); // Get values from $_GET (query string) $page = $request->getQuery("page", "int", 1); $search = $request->getQuery("q", "string"); // Get PUT/PATCH data $data = $request->getPut("data", "string"); $patchData = $request->getPatch("field"); // Get raw body (useful for JSON APIs) $rawBody = $request->getRawBody(); $jsonData = $request->getJsonRawBody(true); // As associative array // Check if parameter exists if ($request->has("token")) { $token = $request->get("token"); } // HTTP headers $contentType = $request->getHeader("Content-Type"); $authHeader = $request->getHeader("Authorization"); $headers = $request->getHeaders(); $userAgent = $request->getUserAgent(); $referer = $request->getHTTPReferer(); // Client information $clientIp = $request->getClientAddress(); $clientIpTrusted = $request->getClientAddress(true); // Trust proxy headers $httpHost = $request->getHttpHost(); $serverAddress = $request->getServerAddress(); $serverName = $request->getServerName(); $port = $request->getPort(); $scheme = $request->getScheme(); // http or https $uri = $request->getURI(); // Language/Content negotiation $languages = $request->getLanguages(); $bestLanguage = $request->getBestLanguage(); $acceptableContent = $request->getAcceptableContent(); $bestAccept = $request->getBestAccept(); $charsets = $request->getClientCharsets(); $bestCharset = $request->getBestCharset(); // File uploads if ($request->hasFiles()) { $files = $request->getUploadedFiles(); foreach ($files as $file) { echo $file->getName(); echo $file->getSize(); echo $file->getTempName(); echo $file->getType(); $file->moveTo("/uploads/" . $file->getName()); } } // Basic/Digest authentication $basicAuth = $request->getBasicAuth(); $digestAuth = $request->getDigestAuth(); ``` -------------------------------- ### Phalcon Cache: PSR-16 Compliant Caching Interface Source: https://context7.com/phalcon/ide-stubs/llms.txt Demonstrates how to use the Phalcon\Cache\Cache class for PSR-16 compliant caching. It supports multiple backend adapters like Redis, Memcached, APCu, and file-based storage. The examples show storing, retrieving, checking existence, deleting, and managing multiple cache entries with time-to-live (TTL) settings. ```php newInstance( "redis", [ "host" => "127.0.0.1", "port" => 6379, "index" => 0, "persistent" => true, "defaultSerializer" => "php", "lifetime" => 3600, ] ); $cache = new Cache($adapter); // Store value with TTL (time-to-live) $cache->set("my-key", ["data" => "value"], 3600); // Store with DateInterval $cache->set("another-key", $data, new DateInterval("PT1H")); // Retrieve value $data = $cache->get("my-key"); // Retrieve with default value $data = $cache->get("missing-key", "default-value"); // Check if key exists if ($cache->has("my-key")) { echo "Key exists in cache"; } // Delete a key $cache->delete("my-key"); // Store multiple values $cache->setMultiple([ "key1" => "value1", "key2" => "value2", "key3" => "value3", ], 3600); // Retrieve multiple values $values = $cache->getMultiple(["key1", "key2", "key3"]); $values = $cache->getMultiple(["key1", "key2"], "default"); // Delete multiple keys $cache->deleteMultiple(["key1", "key2"]); // Clear entire cache $cache->clear(); // Using different adapters $memcachedAdapter = $adapterFactory->newInstance( "libmemcached", [ "servers" => [ ["host" => "127.0.0.1", "port" => 11211, "weight" => 1], ], "defaultSerializer" => "json", "lifetime" => 7200, ] ); $apcuAdapter = $adapterFactory->newInstance( "apcu", [ "defaultSerializer" => "php", "lifetime" => 3600, ] ); $streamAdapter = $adapterFactory->newInstance( "stream", [ "storageDir" => "/tmp/cache/", "defaultSerializer" => "php", "lifetime" => 86400, ] ); ``` -------------------------------- ### Manage Services with Phalcon Dependency Injection Container (PHP) Source: https://context7.com/phalcon/ide-stubs/llms.txt Demonstrates how to use the Phalcon\Di\Di class to register, resolve, and manage services within an application. It covers lazy loading, shared services, constructor arguments, and loading configurations from files. This class is central to implementing the Inversion of Control pattern in Phalcon. ```php set("request", Request::class, true); // Register a shared service using anonymous function $di->setShared( "response", function () { return new Response(); } ); // Register a service with constructor arguments $di->set( "view", function () { $view = new View(); $view->setViewsDir("/app/views/"); return $view; } ); // Check if service exists if ($di->has("request")) { // Get the service (resolves the definition) $request = $di->get("request"); } // Get shared instance (same instance every time) $response = $di->getShared("response"); // Set as default container for static access Di::setDefault($di); // Access default container anywhere in application $defaultDi = Di::getDefault(); // Load services from PHP configuration file $di->loadFromPhp("path/services.php"); // Load services from YAML file $di->loadFromYaml("path/services.yaml"); // Remove a service $di->remove("obsoleteService"); // Array syntax access $di["myService"] = new MyService(); $service = $di["myService"]; ``` -------------------------------- ### Configure Phalcon Autoloader for Namespaces, Classes, Directories, and Files Source: https://context7.com/phalcon/ide-stubs/llms.txt This snippet demonstrates how to configure the Phalcon Autoloader to manage namespaces (PSR-4 compliant), individual classes, directories for fallback loading, and specific files. It also covers setting file extensions and performance optimizations. ```php setNamespaces([ "App\Controllers" => "/app/controllers/", "App\Models" => "/app/models/", "App\Services" => "/app/services/", ]); // Add single namespace $loader->addNamespace("App\Library", "/app/library/"); // Add namespace with multiple directories $loader->addNamespace( "App\Plugins", ["/app/plugins/", "/vendor/plugins/"] ); // Register specific classes $loader->setClasses([ "MyCustomClass" => "/app/library/MyCustomClass.php", "AnotherClass" => "/app/library/AnotherClass.php", ]); // Add single class $loader->addClass("SpecialClass", "/app/special/SpecialClass.php"); // Register directories for fallback loading $loader->setDirectories([ "/app/library/", "/app/plugins/", ]); // Add single directory $loader->addDirectory("/app/helpers/"); // Register files (non-class files, functions) $loader->setFiles([ "/app/functions.php", "/app/helpers.php", ]); // Add single file $loader->addFile("/app/bootstrap.php"); // Set file extensions $loader->setExtensions(["php", "inc"]); $loader->addExtension("phpt"); // Performance optimization $loader->setFileCheckingCallback("stream_resolve_include_path"); // Or disable file checking $loader->setFileCheckingCallback(null); // Register the autoloader $loader->register(); // Register with prepend (priority) $loader->register(true); // Check if registered if ($loader->isRegistered()) { echo "Autoloader is active"; } // Unregister $loader->unregister(); // Debug information $classes = $loader->getClasses(); $namespaces = $loader->getNamespaces(); $directories = $loader->getDirectories(); $files = $loader->getFiles(); $extensions = $loader->getExtensions(); // Path information $foundPath = $loader->getFoundPath(); $checkedPath = $loader->getCheckedPath(); ``` -------------------------------- ### Configure Phalcon ACL for Role-Based Access Control Source: https://context7.com/phalcon/ide-stubs/llms.txt This snippet illustrates how to set up a Phalcon Access Control List (ACL) using the Memory adapter. It covers defining roles, components (resources), actions, granting and denying permissions, and checking access. ```php setDefaultAction(Enum::DENY); // Define roles $acl->addRole(new Role("Guest")); $acl->addRole(new Role("User")); $acl->addRole(new Role("Admin")); // Role inheritance $acl->addRole("SuperAdmin", "Admin"); $acl->addRole("Moderator", ["User", "Editor"]); // Define components (resources) with actions $acl->addComponent( new Component("Posts"), ["index", "create", "edit", "delete"] ); $acl->addComponent("Comments", ["index", "create", "delete"]); $acl->addComponent("Users", ["index", "create", "edit", "delete"]); // Grant permissions $acl->allow("Guest", "Posts", "index"); $acl->allow("User", "Posts", ["index", "create"]); $acl->allow("User", "Comments", ["index", "create"]); $acl->allow("Admin", "Posts", "*"); // All actions $acl->allow("Admin", "Users", "*"); // Deny specific permissions $acl->deny("User", "Posts", "delete"); $acl->deny("Moderator", "Users", ["create", "delete"]); // Wildcard permissions $acl->allow("*", "Posts", "index"); // Any role can view posts $acl->allow("Admin", "*", "*"); // Admin can do anything // Check permissions if ($acl->isAllowed("User", "Posts", "create")) { echo "User can create posts"; } if ($acl->isAllowed("Guest", "Posts", "delete")) { echo "Guest can delete posts"; } else { echo "Access denied"; } // Check with callback function $acl->allow( "User", "Posts", "edit", function (array $parameters) { return $parameters["userId"] === $parameters["postOwnerId"]; } ); $canEdit = $acl->isAllowed( "User", "Posts", "edit", ["userId" => 1, "postOwnerId" => 1] ); // Get information $roles = $acl->getRoles(); $components = $acl->getComponents(); $inheritedRoles = $acl->getInheritedRoles("SuperAdmin"); // Check existence $acl->isRole("Admin"); $acl->isComponent("Posts"); ``` -------------------------------- ### Generate Phalcon Stubs using Zephir Source: https://github.com/phalcon/ide-stubs/blob/master/README.md This sequence of commands generates Phalcon stubs from the cphalcon project using Zephir. It involves cleaning previous builds, generating the project, and then specifically generating the stubs. ```bash php zephir.phar fullclean php zephir.phar generate php zephir.phar stubs ``` -------------------------------- ### Phalcon MVC Model ORM Implementation Source: https://context7.com/phalcon/ide-stubs/llms.txt Demonstrates the usage of Phalcon\Mvc\Model for defining ORM models, including table mapping, relationships, behaviors, validation, and CRUD operations. It covers creating, finding, updating, and deleting records, as well as accessing related data and tracking changes. ```php setSource("robots_table"); // Define relationships $this->hasMany("id", RobotsParts::class, "robots_id", [ "alias" => "parts" ]); $this->belongsTo("type_id", RobotTypes::class, "id", [ "alias" => "robotType" ]); // Add automatic timestamp behavior $this->addBehavior( new Timestampable([ "beforeCreate" => [ "field" => "created_at", "format" => "Y-m-d H:i:s", ], ]) ); // Enable dynamic updates (only changed fields) $this->useDynamicUpdate(true); // Keep snapshots for change tracking $this->keepSnapshots(true); } public function validation() { $validator = new Validation(); $validator->add( "name", new PresenceOf(["message" => "Name is required"]) ); $validator->add( "type", new PresenceOf(["message" => "Type is required"]) ); return $this->validate($validator); } } // Create a new record $robot = new Robots(); $robot->name = "Astro Boy"; $robot->type = "mechanical"; $robot->year = 1952; if ($robot->save() === false) { foreach ($robot->getMessages() as $message) { echo $message . PHP_EOL; } } else { echo "Robot saved with ID: " . $robot->id; } // Find all records $robots = Robots::find(); // Find with conditions $mechanicalRobots = Robots::find([ "type = 'mechanical'", "order" => "name", "limit" => 100, ]); // Find first matching record $robot = Robots::findFirst("id = 100"); $robot = Robots::findFirst([ "type = 'virtual'", "order" => "name DESC", ]); // Query with bound parameters $robots = Robots::find([ "conditions" => "type = :type: AND year > :year:", "bind" => [ "type" => "mechanical", "year" => 1950, ], ]); // Aggregations $count = Robots::count(); $count = Robots::count("type = 'mechanical'"); $average = Robots::average(["column" => "year"]); $sum = Robots::sum(["column" => "price", "type = 'mechanical'"]); $max = Robots::maximum(["column" => "year"]); $min = Robots::minimum(["column" => "year"]); // Update record $robot = Robots::findFirst("id = 100"); $robot->name = "Updated Name"; $robot->update(); // Delete record $robot = Robots::findFirst("id = 100"); $robot->delete(); // Access related records $robot = Robots::findFirst(); $parts = $robot->parts; // Uses alias defined in initialize() $parts = $robot->getRelated("parts", ["order" => "name"]); // Check for changes if ($robot->hasChanged("name")) { echo "Name was changed"; } $changedFields = $robot->getChangedFields(); ``` -------------------------------- ### Handle HTTP Responses with Phalcon\Http\Response Source: https://context7.com/phalcon/ide-stubs/llms.txt The Phalcon\Http\Response class allows you to manage HTTP response generation. It supports setting status codes, content, headers, redirects, and file downloads. It also provides methods for caching and sending the response to the client. ```php setStatusCode(200, "OK"); $response->setStatusCode(404, "Not Found"); $response->setStatusCode(500, "Internal Server Error"); // Set response content $response->setContent("
Hello World"); $response->appendContent(""); // Set JSON content (automatically sets Content-Type header) $response->setJsonContent([ "status" => "success", "data" => [ "id" => 1, "name" => "Example" ] ]); // Set headers $response->setHeader("Content-Type", "text/plain"); $response->setHeader("X-Custom-Header", "value"); $response->setContentType("application/pdf"); $response->setContentType("text/html", "UTF-8"); $response->setContentLength(1024); // Check/remove headers if ($response->hasHeader("X-Custom-Header")) { $response->removeHeader("X-Custom-Header"); } $response->resetHeaders(); // Caching headers $response->setCache(60); // Cache for 60 minutes $response->setExpires(new DateTime("+1 day")); $response->setLastModified(new DateTime()); $response->setEtag(md5($content)); $response->setNotModified(); // 304 response // Redirects $response->redirect("posts/index"); $response->redirect("http://example.com", true); // External $response->redirect("http://example.com", true, 301); // Permanent // Named route redirect $response->redirect([ "for" => "blog-post", "slug" => "my-article", ]); // File download $response->setFileToSend("/path/to/file.pdf"); $response->setFileToSend("/path/to/file.pdf", "download.pdf"); $response->setFileToSend("/path/to/file.pdf", "download.pdf", true); // Send response to client if (!$response->isSent()) { $response->send(); } // Send only headers $response->sendHeaders(); // Send only cookies $response->sendCookies(); // Get response details $content = $response->getContent(); $headers = $response->getHeaders(); $statusCode = $response->getStatusCode(); $reasonPhrase = $response->getReasonPhrase(); ``` -------------------------------- ### Manage URL Routing with Phalcon\Mvc\Router Source: https://context7.com/phalcon/ide-stubs/llms.txt The Phalcon\Mvc\Router class is used for parsing URIs into controller, action, and parameters. It supports regular expressions, HTTP method constraints, named routes, and default route configurations. It also includes a handler for not found routes. ```php add( "/products", [ "controller" => "products", "action" => "index", ] ); // Route with parameters $router->add( "/products/{id:[0-9]+}", [ "controller" => "products", "action" => "show", ] ); // Route with regex patterns $router->add( "/docs/{chapter}/{name}\.{type:[a-z]+}", [ "controller" => "documentation", "action" => "show", ] ); // HTTP method-specific routes $router->addGet("/api/users", "Api\Users::list"); $router->addPost("/api/users", "Api\Users::create"); $router->addPut("/api/users/{id}", "Api\Users::update"); $router->addDelete("/api/users/{id}", "Api\Users::delete"); $router->addPatch("/api/users/{id}", "Api\Users::patch"); // Route with multiple HTTP methods $router->add( "/api/login", "Api\Auth::login", ["GET", "POST"] ); // Set default routes $router->setDefaultModule("frontend"); $router->setDefaultNamespace("App\Controllers"); $router->setDefaultController("index"); $router->setDefaultAction("index"); // Named routes $router->add( "/blog/{slug}", [ "controller" => "blog", "action" => "show", ] )->setName("blog-post"); // Not found handler $router->notFound([ "controller" => "errors", "action" => "notFound", ]); // Handle the URI $router->handle("/products/123"); // Get routing results $controller = $router->getControllerName(); $action = $router->getActionName(); $params = $router->getParams(); $module = $router->getModuleName(); $namespace = $router->getNamespaceName(); $matchedRoute = $router->getMatchedRoute(); $wasMatched = $router->wasMatched(); // Get route by name or ID $route = $router->getRouteByName("blog-post"); $route = $router->getRouteById(1); $allRoutes = $router->getRoutes(); // Remove extra slashes $router->removeExtraSlashes(true); // Clear all routes $router->clear(); ``` -------------------------------- ### Rename Stubs Files Source: https://github.com/phalcon/ide-stubs/blob/master/README.md This command renames all files with the .zep extension to have no extension within the ide/ directory. This is a step in processing generated stubs. ```bash find ide/ -type f -exec rename 's/\.zep//' '{}' \; ``` -------------------------------- ### Fix Code Style with PHP_CodeSniffer Source: https://github.com/phalcon/ide-stubs/blob/master/README.md Applies code style fixes to the source files using PHP_CodeSniffer's phpcbf tool, adhering to the PSR12 standard. Ensure you have the latest .phar release. ```bash # Pick latest .phar from here: https://github.com/squizlabs/PHP_CodeSniffer/releases php phpcbf.phar --standard=PSR12 src ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.