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
You can replace that require with require_once or better use autoloading :
Create a folder and put all your required classs in this folder:
You could avoid multiple fetches and decodes in your loop by breaking that out.
In AltoRouter.php