MagewirePHP

repository·main·Indexed 42 days ago

https://github.com/magewirephp/magewire

A library for Magento 2 that enables reactive, server-driven UI development using only PHP. Inspired by Laravel Livewire, it allows developers to build dynamic frontend components—such as real-time search, product forms, and filters—without writing custom JavaScript. Version 3.0 is a rewrite based on Livewire v3, requiring PHP >=8.2.

Tokens
3.5K
Snippets
13
Records
17
Agent score
54%

What's inside Magewire

  1. Overview of MagewirePHP

    main
    MagewirePHP is a library for Magento 2 that enables reactive, server-driven UI development using only PHP. Inspired by Laravel Livewire, it allows developers to build dynamic frontend components (such as real-time search, product forms, filters, modals, and configurators) without writing custom JavaScript. The component logic is maintained in PHP and is fully integrated with Magento's architecture.
  2. Magewire 3.0 vs Upstream Livewire v3 Differences

    main

    If you are familiar with Laravel Livewire v3, note these Magewire-specific implementation details:

    • Component Discovery: Magewire does not use Livewire::component(). Components are discovered via Magento layout XML (e.g., <block class="..."/>) and resolved by ResolveComponents.
    • Service Registration: Mechanisms and Features are registered via area-scoped Magento DI (etc/frontend/di.xml or etc/adminhtml/di.xml), not via global service providers.
    • The app() Bridge: Calls to app('livewire') or app('redirect') are supported; Containers maps these to Magento DI bindings.
    • Update Endpoint: AJAX updates are POSTed to magewire/update (a custom router), not /livewire/update.
    • Template Compiler: The compiler is opt-in per directive area and can be extended via DI virtualTypes to allow themes to add custom directive namespaces.
  3. Handle Breaking Changes in wire:model and Entangle

    main

    In Magewire 3.0, updates are deferred by default. If you require the immediate update behavior found in v1, you must use specific modifiers.

    wire:model

    To make wire:model live (updating on every input/change), use the .live modifier:

    - <input wire:model="query" />
    + <input wire:model.live="query" />

    Entangle

    Similarly, @entangle now defers updates. To match v1 behavior, use the .live or .blur modifiers:

    @entangle('prop').live
    // or
    @entangle('prop').blur

    Note: If you have applied the #[HandleBackwardsCompatibility] attribute to your component, plain wire:model and @entangle('prop') will be mapped back to their v1 live semantics automatically.

    <input wire:model.live="query" />
  4. Upgrading from Magewire 1.x

    main

    Magewire 1.x is no longer actively maintained and only receives security-related updates. For new features and regular bug fixes, you should upgrade to the latest major version.

    Key migration areas include:

    • Dependency changes
    • The #[HandleBackwardsCompatibility] attribute (opt-in)
    • Changes to wire:model semantics

    For detailed migration steps, refer to the UPGRADING.md file in the repository.

  5. Enable Backwards Compatibility for Magewire 1.x Components

    main

    Most Magewire 1.x components can continue working using a Backwards Compatibility (BC) layer. You must opt-in per-component by applying the #[HandleBackwardsCompatibility] attribute to your component class.

    Without this attribute, the component will use Magewire 3.0 semantics. When applied, it flips a bc memo flag in the component snapshot to maintain v1 behavior.

    use Magewirephp\Magewire\Features\SupportMagewireBackwardsCompatibility\Attributes\HandleBackwardsCompatibility;
    
    #[HandleBackwardsCompatibility]
    class MyComponent extends \Magewirephp\Magewire\Component
    {
        // v1-style code keeps working
    }
  6. Upgrade from Magewire 1.x to 3.0

    main

    Magewire 3 is a full rewrite based on a port of Laravel Livewire v3. To upgrade from 1.x, follow these steps:

    1. Update Requirements

    • PHP: Upgrade to >=8.2.
    • Magento: Any 2.x version.

    2. Update Composer Dependencies

    Change your composer.json constraint for Magewire:

    - "magewirephp/magewire": "^1.13"
    + "magewirephp/magewire": "^3.0"

    Note on dependencies:

    • rakit/validation is replaced by magewirephp/validation. This is a drop-in fork using the same Rakit\Validation\ namespace. If you explicitly require rakit/validation in your own composer.json, remove it.
    • magento/framework is no longer a required dependency of Magewire.

    3. Run Magento Upgrade Commands

    After updating composer, execute the following to refresh the environment:

    composer update magewirephp/magewire --with-all-dependencies
    bin/magento setup:upgrade
    bin/magento setup:di:compile
    bin/magento cache:flush
  7. Use multiple paginators in a Magewire component

    main

    When using the WithPagination trait, you can manage multiple independent paginated sets within a single Magewire component by providing a unique name to the pagination methods.

    • Default Paginator: Methods like getPage() and nextPage() without arguments operate on the default paginator.
    • Named Paginators: Methods like getPage('name'), nextPage('name'), and previousPage('name') allow you to control a specific paginated instance identified by the string 'name'.
    // Using the default paginator
    $page = $this->getPage();
    $this->nextPage();
    
    // Using a named paginator
    $itemPage = $this->getPage('item-page');
    $this->nextPage('item-page');
    $this->previousPage('item-page');
  8. Implement pagination lifecycle hooks

    main

    Magewire provides lifecycle hooks that are triggered when a page changes. The naming convention for these hooks depends on whether you are using the default paginator or a named one:

    1. Default Paginator: Use the updatedPage(int $page) method.
    2. Named Paginators: Use the kebab-cased name of the paginator in the method name: updated{KebabCasedName}(int $page). For example, a paginator named item-page triggers updatedItemPage(int $page).
    // Triggered when the default page changes
    public function updatedPage(int $page): void
    {
        // logic here
    }
    
    // Triggered when the 'item-page' changes
    public function updatedItemPage(int $page): void
    {
        // logic here
    }
  9. Configure Portman transformations and renaming

    main

    The transformations section allows you to modify the code structure during the porting process. This is primarily used for namespace remapping and cleaning up incompatible methods.

    • Namespace Renaming: Map an existing namespace to a new one using the rename key. For example, mapping Livewire\ to Magewirephp\Magewire\.
    • Class Renaming: Within a namespace transformation, you can target specific classes and use rename to change their names.
    • Method Removal: Use remove-methods to strip out methods that are incompatible with the target environment (e.g., removing Laravel-specific routing methods when porting to Magento). This can be applied to specific classes within the children array of a namespace transformation.
    • Docblock Modification: Use file-doc-block to overwrite the file-level docblock for a specific namespace, which is useful for updating copyright information.
    'transformations' => [
        'Livewire\' => [
            'rename' => 'Magewirephp\Magewire\',
            'children' => [
                'LivewireManager' => [
                    'rename' => 'MagewireManager',
                    'remove-methods' => [
                        'setProvider',
                        'provide',
                    ]
                ]
            ]
        ],
        'Magewirephp\Magewire\' => [
            'file-doc-block' => '/**
     * Magewire copyright © Willem Poortman 2024-present.
     */',
        ]
    ]
  10. Configure Portman post-processors

    main

    The post-processors configuration allows you to enable or disable automated code styling and refactoring tools that run after the transformation process is complete.

    Supported keys:

    • rector: Boolean to enable/disable Rector for automated refactoring.
    • php-cs-fixer: Boolean to enable/disable PHP CS Fixer for code style enforcement.
    'post-processors' => [
        'rector' => false,
        'php-cs-fixer' => false
    ]
  11. Configure Portman directory settings

    main

    The directories configuration defines how Portman identifies, filters, and processes source files. It is divided into source, augmentation, and output sections.

    • source: Defines the input files. You can specify a path (e.g., portman/lib/Livewire) and provide a composer configuration block to map the package name, version, and base path. Use glob to define file patterns and ignore to exclude specific files or directories using glob patterns.
    • augmentation: Specifies additional directories or packages to include in the process.
    • output: Defines the destination directory for the processed files (e.g., dist).
    return [
        'directories' => [
            'source' => [
                'portman/lib/Livewire' => [
                    'composer' => [
                        'name'   => 'livewire/livewire',
                        'version'   => '~3.7.15',
                        'version-lock'   => '3.7.15',
                        'base-path'   => 'src'
                    ],
                    'glob' => '**/*.php',
                    'ignore' => [
                        'Exceptions/*',
                        'Features/SupportEvents/TestsEvents.php',
                    ]
                ]
            ],
            'augmentation' => [
                'portman/Livewire'
            ],
            'output' => 'dist'
        ],
    ];