Phalcon IDE Stubs

repository·master·Indexed 41 days ago

https://github.com/phalcon/ide-stubs

PHP stubs for the Phalcon Framework designed to enable accurate autocompletion and type hinting in modern IDEs. Includes definitions for ADR Payload classes, Asset management, and Collections, with support for PHP versions 8.1 through 8.5.

Tokens
15.3K
Snippets
44
Records
81
Agent score
47%

What's inside Phalcon IDE Stubs

  1. Install Phalcon IDE Stubs via Git

    master

    Alternatively, you can install the stubs manually:

    1. Clone the Phalcon IDE Stubs repository to a common location on your machine.
    2. Configure your IDE to include this repository in its include path for autocompletion.
  2. Understand the difference between ERROR and FAILURE statuses in Phalcon ADR Payload

    master

    In the Phalcon ADR (Application Design Pattern) implementation, the Phalcon\ADR\Payload\Status class distinguishes between two types of unsuccessful outcomes. Understanding this distinction is critical for proper error handling and domain logic flow:

    • ERROR: Indicates that an exception was raised while the domain layer was executing. By convention, this status is paired with Payload::withException().
    • FAILURE: Indicates that the domain layer ran to completion successfully but declined the request (e.g., a business rule was not satisfied). No exception was raised in this case.

    Using FAILURE instead of ERROR allows you to represent expected business logic rejections without the overhead or flow-interruption of an exception.

  3. How CLI dispatching works in Phalcon

    master

    Dispatching is the process of taking command-line arguments and extracting the module name, task name, action name, and optional parameters. The Phalcon\Cli\Dispatcher then instantiates the corresponding task and calls the specified action on it.

    When an action method is called, any CLI options collected by the dispatcher are appended to the positional parameters. This means a task action receives options as trailing arguments after its declared positional parameters.

    use Phalcon\Di\Di;
    use Phalcon\Cli\Dispatcher;
    
    $di = new Di();
    
    $dispatcher = new Dispatcher();
    
    $dispatcher->setDi($di);
    
    $dispatcher->setTaskName("posts");
    $dispatcher->setActionName("index");
    $dispatcher->setParams([]);
    
    $handle = $dispatcher->dispatch();
  4. Use RouteInterface for CLI route type hinting

    master

    In Phalcon CLI routing, Phalcon\Cli\Router always constructs and returns the concrete Phalcon\Cli\Router\Route class. Because there is no injection point for externally built routes, RouteInterface serves primarily as a marker interface for type hinting in your application code rather than a contract you implement yourself.

    Note that the fluent route API (such as beforeMatch(), getBeforeMatch(), convert(), and getConverters()) is available on the concrete Route class, not on this interface.

  5. Use Phalcon\Di\FactoryDefault\Cli for CLI applications

    master

    The Phalcon\Di\FactoryDefault\Cli class is a specialized variant of the standard Phalcon\Di. It is designed specifically for CLI (Command Line Interface) applications.

    When instantiated, it automatically registers all framework services required for a CLI environment, such as Phalcon\Cli\Dispatcher and Phalcon\Cli\Router, saving the developer from registering each service individually.

    use Phalcon\Di\FactoryDefault\Cli;
    
    $di = new Cli();
    // The DI container is now pre-populated with services suitable for CLI usage.
  6. Use Phalcon\Auth\Manager to manage authentication and authorization

    master

    The Phalcon\Auth\Manager class acts as a single facade that composes both authentication (guards) and authorization (access gates).

    Authentication (Guards)

    Guards handle the identity of the user. You can manage multiple guards and switch between them using guard(). To access specific guard capabilities (like stateful behavior), use instanceof against the relevant interface (e.g., Phalcon\Contracts\Auth\Guard\GuardStateful).

    Authorization (Access)

    Access gates handle what an authenticated user is allowed to do. The manager provides methods like only() and except() to filter actions, and getAccess() to retrieve the active access instance.

    Key Methods

    • attempt(array $credentials, bool $remember): Attempts to authenticate the user with the provided credentials.
    • check(): Returns true if the user is currently authenticated.
    • guard(?string $name): Retrieves a specific guard by name, or the default guard if no name is provided.
    • user(): Returns the currently authenticated AuthUser or null.
    • logout(): Logs the user out.
    • id(): Returns the unique identifier of the authenticated user.
    • addGuard(string $name, Guard $guard, bool $isDefault): Registers a new guard.
    • addAccessList(array $accessList): Registers a list of access classes.
    // Example usage pattern
    $manager->addGuard('api', $apiGuard, true);
    $manager->addGuard('web', $webGuard);
    
    // Attempting login
    if ($manager->attempt(['username' => 'admin', 'password' => 'secret'])) {
        // User is authenticated
        $user = $manager->user();
        
        // Check authorization
        if ($manager->only('edit-post')->getAccess()) {
            // User has permission
        }
    }
    
    // Switching to a specific guard
    $apiGuard = $manager->guard('api');
  7. Use the Phalcon ADR Payload class

    master

    The Phalcon\ADR\Payload\Payload class is an immutable data structure produced by the domain layer in an ADR (Action-Domain-Responder) implementation. Because it is immutable, any method prefixed with with* (e.g., withResult(), withStatus()) will return a new instance of the payload, leaving the original object unchanged.

    Use the provided static factory methods to quickly create payloads with predefined statuses, such as success(), error(), or notFound().

    use Phalcon\ADR\Payload\Payload;
    
    // Create a success payload with a result
    $payload = Payload::success($someResult);
    
    // Create a new instance with additional messages (immutability)
    $payloadWithMessages = $payload->withMessages(['Operation completed successfully']);
    
    // Access data
    $status = $payloadWithMessages->getStatus();
    $result = $payloadWithMessages->getResult();
  8. Create a CLI task by extending Phalcon\Cli\Task

    master

    To implement a command-line task (such as migrations, cronjobs, or unit tests), you must extend the Phalcon\Cli\Task class.

    Tasks are composed of 'action' methods. By convention, these methods are named with an Action suffix (e.g., mainAction, findAction).

    When an action is executed, it receives routed parameters as positional arguments. Any CLI options collected by the dispatcher are appended as trailing arguments. To capture these options, declare optional trailing parameters in your method signature.

    class HelloTask extends \Phalcon\Cli\Task
    {
        // This action will be executed by default
        public function mainAction()
        {
            // Task logic here
        }
    
        public function findAction()
        {
            // Specific action logic here
        }
    }
  9. Define database indexes with Phalcon\Db\Index

    master

    The Phalcon\Db\Index class is used to define database indexes to enhance performance. It supports two initialization modes: a legacy positional form and a modern definition-array form. The definition-array form is required for advanced features like invisible indexes (MySQL 8.0+).

    Once an Index object is created, it can be passed to a database connection's addIndex method to apply it to a table.

    Initialization Modes

    1. Legacy Positional Form: Uses a plain array of column names. new Index(string $name, array $columns, string $type = '')

    2. Definition-Array Form: Uses an associative array with a columns key. This mode is preferred for modern features. new Index(string $name, array $definition)

    Database Compatibility

    • PostgreSQL: Supports concurrent building (using CONCURRENTLY) and partial-index WHERE predicates.
    • MySQL 8.0+: Supports invisible indexes.
    • SQLite: Supports partial-index WHERE predicates.
    • MySQL/SQLite: Ignore the concurrent flag and WHERE predicates.
    // Legacy positional form
    $unique = new 	ext{Phalcon\Db\Index}(
        'column_UNIQUE',
        [
            'column',
        ],
        'UNIQUE'
    );
    
    // Definition-array form (MySQL 8.0+ invisible index)
    $hidden = new 	ext{Phalcon\Db\Index}(
        'idx_hidden',
        [
            'columns'   => ['col1'],
            'type'      => '',
            'invisible' => true,
        ]
    );
    
    // Applying to a connection
    $connection->addIndex("co_invoices", null, $unique);
    $connection->addIndex("co_invoices", null, $hidden);