【问题标题】:Serving images with Yii that are outside of web application folder, performance issue使用 Yii 提供 Web 应用程序文件夹之外的图像,性能问题
【发布时间】:2014-01-17 17:38:48
【问题描述】:

我有以下控制器/动作:

<?php

class ImageController extends CController {

    public function actionView($folder, $name) {

        $ds = DIRECTORY_SEPARATOR;

        $file = Yii::app()->params['images_path'] . $ds . $folder . $ds . $name;

        $content = file_get_contents($file);

        Yii::app()->request->sendFile($file, $content);
    }

}

这将是一个基本的图像服务操作。我的图像位于网络根文件夹之外。问题是如何优化文件的读取。似乎每个请求都执行整个 Yii 应用程序只是为了提供一个图像。网站上有很多图片,这是一个很大的性能问题。任何想法如何解决这个问题?

【问题讨论】:

  • 这将是昂贵的;您正在读取图像文件的全部内容,将其分配给 PHP 变量并通过框架提供服务。理想情况下,您希望直接通过 HTTP 服务器提供静态文件,例如图像。

标签: php image performance yii


【解决方案1】:

实际上sendFile() 用于提供下载服务,而不是查看文件内容。 老实说,我无法理解您要做什么,但从我的实践来看-sendFile() 的文件可能已损坏。有不同的原因,其中一个是日志记录,它也会导致一些性能问题。 删除除 CFileLogRoute 之外的所有记录器。 可以在配置或基本控制器中完成:

public function disableProfilers()
{
    if (Yii::app()->getComponent('log')) {
        foreach (Yii::app()->getComponent('log')->routes as $route) {
            if (in_array(get_class($route), array('CProfileLogRoute', 'CWebLogRoute', 'YiiDebugToolbarRoute','DbProfileLogRoute'))) {
                $route->enabled = false;
            }
        }
    }
}

那么你的下载动作将是

    public function actionDownloadFile()
    {
        $this->disableProfilers();        
        $file = '/path/to/file/some_file.txt';
        Yii::app()->request->sendFile(basename($file),file_get_contents($file));
    }

使用 php 和 file_get_contents 提供文件是有效的操作,所以如果您有很多图像要提供 - 通过 HTTP 服务器提供它们。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-04
    • 2020-08-13
    • 2012-11-13
    • 2012-08-22
    • 1970-01-01
    • 2019-05-10
    • 2021-12-31
    • 2021-11-05
    相关资源
    最近更新 更多