【问题标题】:Load configuration file just once只加载一次配置文件
【发布时间】:2015-12-08 22:43:24
【问题描述】:

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

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 方法时,我都会从外部文件加载路由。可以吗?或者我可以优化某种上面的代码吗?如果是 - 如何? 谢谢!

【问题讨论】:

    标签: php routes file-get-contents altorouter


    【解决方案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];
    }
    

    【讨论】:

      【解决方案2】:

      你可以用 require_once 替换那个 require 或者更好地使用自动加载:

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

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

      function __autoload($class) {
          require_once "Classes" . $class . '.php';
      }
      

      【讨论】:

        猜你喜欢
        • 2011-04-12
        • 2011-09-15
        • 1970-01-01
        • 2021-06-07
        • 2022-11-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多