【问题标题】:File system path for images图像的文件系统路径
【发布时间】:2017-06-07 09:21:59
【问题描述】:

我正在编写一个扩展 HtmlHelper 的自定义帮助程序,并覆盖 \HtmlHelper::image() 方法来计算图像尺寸并将它们添加为 HTML 属性。到目前为止,我所拥有的对于普通图片来说效果很好:

public function image($path, $options = array()) {
    if (!array_key_exists('width', $options) && !array_key_exists('height', $options)) {
        $stamp = Configure::read('Asset.timestamp');
        Configure::write('Asset.timestamp', false);

        $path = $this->assetUrl($path, $options + array('pathPrefix' => Configure::read('App.imageBaseUrl')));
        list($width, $height) = @getimagesize(rtrim(WWW_ROOT, '\\/') . $path);
        if (!is_null($width)) {
            $options['width'] = $width;
        }
        if (!is_null($height)) {
            $options['height'] = $height;
        }

        Configure::write('Asset.timestamp', $stamp);
    }
    return parent::image($path, $options);
}

……但有以下缺陷:

  • 来自插件的图片不能位于磁盘上(它们应该),例如:

    echo $this->Html->image('/debug_kit/img/cake.icon.png', array('alt' => 'CakePHP'));
    

    ... 生成此文件系统路径:

    …\src\webroot/debug_kit/img/cake.icon.png
    

    ...因此getimagesize() 失败,因为实际位置是:

    …\src\Plugin\DebugKit\webroot\img\cake.icon.png"
    
  • 外部图片(应忽略)经过全流程:

    echo $this->Html->image('http://placekitten.com/200/300');
    …\src\webroothttp://placekitten.com/200/300
    

我一直在寻找一种内置方法来将 CakePHP 图片 URL(以\HtmlHelper::image() 接受的任何格式转换为文件系统路径(o 类似 null 时不适用)但我不能找到任何。需要磁盘路径的本机功能,例如 \Helper::assetTimestamp() 被包装在大量不可重用的代码中。

有没有优雅的解决方案?

【问题讨论】:

    标签: cakephp cakephp-2.9


    【解决方案1】:

    我想说几乎只有 3 个选项:

    • 提交补丁以将资产文件系统路径检索功能添加到核心。
    • 从帮助程序(assetUrl()webroot()assetTimestamp())复制大量代码。
    • 对本地 URL 使用 Web 请求(最好与缓存结合使用)。

    【讨论】:

      【解决方案2】:

      尝试使用 DS 而不是使用 \ 或 /,它们有时会导致操作系统出现问题。 DS 是 cakephp 提供的目录分隔符 PHP 的 DIRECTORY_SEPARATOR 的缩写,在 Linux 上为 /,在 Windows 上为 \。 Check the doc

      【讨论】:

      • 我认为这不是真的。 PHP 可以毫无问题地处理这两者。路径分隔符不会改变路径缺少多个组件的事实(例如Plugin\DebugKit)。 (顺便说一句,我使用的是 CakePHP/2,而不是 3。)
      • 您是否尝试过将其与 Plugin name.path 一起使用,请参阅此文档:- book.cakephp.org/2.0/en/core-libraries/helpers/…
      • 不确定您的确切意思。我对image()方法本身没有任何问题,插件图片工作得很好。我想做一些额外的处理,我需要资产的完整文件系统路径。我可以编写 50 行代码来复制核心 PHP 功能,但我想避免这种情况。
      猜你喜欢
      • 1970-01-01
      • 2011-09-30
      • 1970-01-01
      • 2014-05-24
      • 1970-01-01
      • 1970-01-01
      • 2016-07-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多