0

我正在编写脚本以将旧链接转换为对 seo 友好的 url。

索引.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);
    }
...

我的问题:每次使用getSefUrl方法时,我都会从外部文件加载路由。可以吗?或者我可以优化某种上面的代码吗?如果是 - 如何?谢谢!

4

2 回答 2

1

您可以通过打破循环来避免循环中的多次提取和解码。

在 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];
}
于 2015-12-09T02:07:21.720 回答
0

您可以用 require_once 或更好地使用 autoloading 替换该 require:

您可以定义一个自动调用的 __autoload() 函数,以防您尝试使用尚未定义的类/接口。通过调用此函数,脚本引擎在 PHP 因错误而失败之前获得了最后一次加载类的机会。

创建一个文件夹并将所有需要的类放在此文件夹中:

function __autoload($class) {
    require_once "Classes" . $class . '.php';
}
于 2015-12-08T22:51:24.333 回答