skip to Main Content

I’m working on my script to convert legacy links to seo friendly urls.

index.php

require 'AltoRouter.php';
$router = new AltoRouter();
$router->setBasePath('/router');

$urls = [
    'index.php?option=com_index&task=articles&id=1',
    'index.php?option=com_index&task=articles&slug=1-article-title',
    'index.php?option=com_index&task=articles.category&cid=100-category1',
    'index.php?option=com_shop&task=products&slug=100-amazing-product',
];

foreach($urls as $i=>$url) {
    echo $router->getSefUrl($url);
}

AltoRouter.php

...
public function getSefUrl($url) {

        $url_clean  = str_replace('index.php?', '', $url);
        parse_str($url_clean, $output);

        $component  = empty($output['option'])  ? 'com_index'   : $output['option'];
        $task               = empty($output['task'])        ? 'index'           : $output['task'];

        $path           = 'components/'.$component.'/routes/routes.json';
        $data           = json_decode(file_get_contents($path));

        if (!empty($data)) {
            foreach($data as $route) {
                $this->map($route[0], $route[1], $route[2], $route[2]);
            }
        }

        $route_info = $this->findUrlFromRoutes($task);
        return empty($route_info) ? $url : $this->generate($route_info->task, $output);
    }
...

My question: Every time when I’m using getSefUrl method I’m loading routes from external file. Is it ok? Or can I optimize code above some kind? If yes – how to?
Thanks!

2

Answers


  1. You can replace that require with require_once or better use autoloading :

    You may define an __autoload() function which is automatically called
    in case you are trying to use a class/interface which hasn’t been
    defined yet. By calling this function the scripting engine is given a
    last chance to load the class before PHP fails with an error.

    Create a folder and put all your required classs in this folder:

    function __autoload($class) {
        require_once "Classes" . $class . '.php';
    }
    
    Login or Signup to reply.
  2. You could avoid multiple fetches and decodes in your loop by breaking that out.

    In AltoRouter.php

    private $routes = array();
    
    function getComponentRoutes($component)
    {
        if(! isset($this->routes[$component])) {
            $path = 'components/'.$component.'/routes/routes.json';
            $this->routes[$component] = json_decode(file_get_contents($path));
        }
    
        return $this->routes[$component];
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search