MageWork

Back to home

Rewrite

To rewrite a route, add a model rewrite class in your package. If the package is named acme, the class will be Acme_Model_Rewrite.

Create the packages/acme/app/Acme/Model/Rewrite.php file.

<?php
    
declare(strict_types=1);

class Acme_Model_Rewrite extends Core_Model
{
    public function execute(): void
    {
        $route = App::getRoute(); // The current route without query parameters and the final /
        
        // /my-page.html = /my-page.html
        // /my-page/     = /my-page
        // /my-page/?q=1 = /my-page
        // /my-page?q=1  = /my-page
    }
}

Then, write a regular expression to check if the route matches what you want.

If the route matches, you can update the current route and add the parameters.

<?php
    
declare(strict_types=1);

class Acme_Model_Rewrite extends Core_Model
{
    public function execute(): void
    {
        $route = App::getRoute();

        if (preg_match('/^\/customer\/(?P<id>[0-9]*)$/', $route, $matches)) { // /customer/{id}
            $this->setData('route', '/customer/');
            $_GET['id'] = $matches['id'];
        }
    }
}

In this example, the route /customer/?id=10 can be rewritten in /customer/10.