0

レガシー リンクを seo フレンドリーな URL に変換するスクリプトを作成中です。

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

私の質問: 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 を require_once に置き換えるか、autoloading を使用することをお勧めします。

まだ定義されていないクラス/インターフェースを使用しようとする場合に自動的に呼び出される __autoload() 関数を定義できます。この関数を呼び出すことで、PHP がエラーで失敗する前に、スクリプト エンジンにクラスをロードする最後のチャンスが与えられます。

フォルダーを作成し、必要なすべてのクラスをこのフォルダーに配置します。

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