douxin8383 2018-11-19 16:51
浏览 28

too long

I set up a cron script that runs every minute in the CPanel of my webhost. The cron runs properly, but I am encountering a script path related issue that I have no idea how to resolve properly. Most of my website uses /home/mysite/public_html/ as the root path, but the cron script uses /home/mysite/ as root path without the public_html part.

This causes a lot of issue with file inclusion, as I am forced to fix this in my class loaders by checking both the default path, and an alternative path prefixed by public_html/:

spl_autoload_register(function($class){
    $className = str_replace("\\", "/", $class);
    $classPath = "{$className}.php";
    $altClassPath = "public_html/{$classPath}";
    if(file_exists($classPath)) require $classPath;
    elseif(file_exists($altClassPath)) require $altClassPath;
    else throw new ClassNotFoundException("Fatal Error: Class {$class} either does not exist, or has its include path mis-configured!");
});

This feels tedious and error prone, and I do not like it at all. Is there a better way to handle this problem? I tried to use set_include_path on the cron script but it seems it doesnt help with the autoloader either.

  • 写回答

1条回答 默认 最新

  • dqnrk44682 2019-01-15 13:55
    关注

    Had the same problem just a minute ago. It seems a simple one, but those are often the hardest ones to get because everybody knows that, so nobody say it aloud.

    In my case using so called magic constant of PHP solved it. The variable is:

    __DIR__
    

    And it holds a path to the script it is used in. No matter if run directly or included in some other php file. So you can use it to write relative paths, that always start where your file is. Like that one:

     include(__DIR__ . "/../somewhere/something.php");
    

    Some more useful magic constants

    评论

报告相同问题?

悬赏问题

  • ¥100 iOS开发关于快捷指令截屏后如何将截屏(或从截屏中提取出的文本)回传给本应用并打开指定页面
  • ¥15 unity连接Sqlserver
  • ¥15 图中这种约束条件lingo该怎么表示出来
  • ¥15 VSCode里的Prettier如何实现等式赋值后的对齐效果?
  • ¥15 流式socket文件传输答疑
  • ¥20 keepalive配置业务服务双机单活的方法。业务服务一定是要双机单活的方式
  • ¥50 关于多次提交POST数据后,无法获取到POST数据参数的问题
  • ¥15 win10,这种情况怎么办
  • ¥15 如何在配置使用Prettier的VSCode中通过Better Align插件来对齐等式?(相关搜索:格式化)
  • ¥100 在连接内网VPN时,如何同时保持互联网连接