How to create custom router in Joomla 4

Select your language

It is tutorial for Joomla 4.x versions
NOTE: go to libraries/src/Router/Router.php file and comment this code on line 153 inside parse function:

// throw new RouteNotFoundException(Text::_('JERROR_PAGE_NOT_FOUND'));

- Create file router.php inside your-component-name->src->Service->router.php

- declare namespace like:

namespace Abdul\Component\Onlytags\Site\Service;

- import necassary classes

use Abdul\Component\Advertise\Site\Service\OnlytagsNomenuRules as NomenuRules;

use Joomla\CMS\Component\Router\Rules\MenuRules;
use Joomla\CMS\Component\Router\Rules\StandardRules;
use Joomla\CMS\Menu\AbstractMenu;

use Joomla\CMS\Component\Router\RouterBase;
use Joomla\CMS\Factory;

- create class router, which extend routerbase

class Router extends RouterBase

- create two functions parse and build to perform created sef url and parsing them.

/**
 * Function to convert a route to an internal URI
 *
 * @param   Uri   &$uri     The uri.
 * @param   bool  $setVars  Set the parsed data in the internal
 *                          storage for current-request-URLs
 *
 * @return  array
 *
 * @since   1.5
 * @throws  \Exception
 */
public function parse(&$segments)
{ }

- Add logic into both functions according to your requirements, I will working with this url

index.php?option=com_onlytags&view=onlytags&Itemid=127 (where 127 is menu created in admin for this onlytags view)

which after SEF url becomes:

index.php/only-tags/onlytags

public function parse(&$segments)
{
    $vars['view'] = $segments[0];
    /* This will be used for my next view 'tag' */
    $arr=(isset($segments[1])) ? explode(':',$segments[1]) : NULL;
    if(isset($segments[1])) :
        $vars['id'] = $segments[2];
        $vars['alias'] = (string) $segments[1];
    endif;

	return $vars;
}

And build function becomes:

public function build(&$query)
{
    $segments = array();
    if (isset($query['view']))
    {
        $segments[] = $query['view'];
        unset($query['view']);
    }

    if (isset($query['alias']))
    {
        $segments[] = $query['alias'];
        unset($query['alias']);
    }
    if (isset($query['id']))
    {
        $segments[] = $query['id'];explode(':',$query['id']);
        unset($query['id']);
    }

    return $segments;
}

- That's all. Still have trouble with custom router development. Just ask me, I will be happy to have my serivce for you.

www.abdulwaheed.pk

Whatsapp: +923455128238

Skype : abdul.wahed1234