admad/cakephp-glide

CakePHP 插件,用于使用 Glide 图片处理库。

资助包维护!
ADmad

安装次数: 97 487

依赖关系: 3

建议者: 0

安全: 0

星标: 34

关注者: 9

分支: 11

开放问题: 0

类型:cakephp-plugin

6.0.0 2023-09-28 20:23 UTC

README

Build Status Coverage Status Total Downloads License

CakePHP 插件,帮助使用 Glide 图片处理库。

插件由一个中间件、视图辅助工具和 Glide 响应类组成。

安装

通过 composer 安装插件

composer require admad/cakephp-glide

使用 CLI 加载插件

bin/cake plugin load ADmad/Glide

使用方法

中间件

在你的 config/routes.php 中为所需的范围设置 GlideMiddleware,它拦截请求并服务由 Glide 生成的图像。例如:

$routes->scope('/images', function ($routes) {
    $routes->registerMiddleware('glide', new \ADmad\Glide\Middleware\GlideMiddleware([
        // Run this middleware only for URLs starting with specified string. Default null.
        // Setting this option is required only if you want to setup the middleware
        // in Application::middleware() instead of using router's scoped middleware.
        // It would normally be set to same value as that of server.base_url below.
        'path' => null,

        // Either a callable which returns an instance of League\Glide\Server
        // or config array to be used to create server instance.
        // http://glide.thephpleague.com/1.0/config/setup/
        'server' => [
            // Path or League\Flysystem adapter instance to read images from.
            // http://glide.thephpleague.com/1.0/config/source-and-cache/
            'source' => WWW_ROOT . 'uploads',

            // Path or League\Flysystem adapter instance to write cached images to.
            'cache' => WWW_ROOT . 'cache',

            // URL part to be omitted from source path. Defaults to "/images/"
            // http://glide.thephpleague.com/1.0/config/source-and-cache/#set-a-base-url
            'base_url' => '/images/',

            // Response class for serving images. If unset (default) an instance of
            // \ADmad\Glide\Response\PsrResponseFactory() will be used.
            // http://glide.thephpleague.com/1.0/config/responses/
            'response' => null,
        ],

        // http://glide.thephpleague.com/1.0/config/security/
        'security' => [
            // Boolean indicating whether secure URLs should be used to prevent URL
            // parameter manipulation. Default false.
            'secureUrls' => false,

            // Signing key used to generate / validate URLs if `secureUrls` is `true`.
            // If unset value of Cake\Utility\Security::salt() will be used.
            'signKey' => null,
        ],

        // Cache duration. Default '+1 days'.
        'cacheTime' => '+1 days',

        // Any response headers you may want to set. Default null.
        'headers' => [
            'X-Custom' => 'some-value',
        ],

        // Allowed query string params. If for e.g. you are only using glide presets
        // then you can set allowed params as `['p']` to prevent users from using
        // any other image manipulation params.
        'allowedParams' => null
    ]));

    $routes->applyMiddleware('glide');

    $routes->connect('/*');
});

对于上面显示的示例配置,对于类似 domain.com/images/user/profile.jpg 的 URL,源图像应位于 webroot/uploads/user/profile.jpg 下。

注意:确保图像 URL 不要直接映射到 webroot 下的图像。否则,根据 CakePHP 的默认 URL 转换规则,图像将由 web 服务器本身提供服务,并且请求不会达到你的 CakePHP 应用。

异常

如果你已启用安全 URL 并且查询字符串中没有有效的令牌,中间件将抛出 ADmad\Glide\Exception\SignatureException 异常。

如果 Glide 库无法生成响应图像,则默认情况下中间件将抛出 ADmad\Glide\Exception\ResponseException。在这种情况下,还将触发 Glide.response_failure 事件。你可以为此事件设置一个监听器,并从其中返回一个响应实例。在这种情况下,该响应将被发送到客户端,并且不会抛出 ResponseException

\Cake\Event\EventManager::instance()->on(
    \ADmad\Glide\Middleware\GlideMiddleware::RESPONSE_FAILURE_EVENT,
    function ($event) {
        return (new Response())
            ->withFile('/path/to/default-image.jpg');
    }
);

辅助工具

提供的 GlideHelper 帮助创建用于生成图像的 URL 和图像标签。你可以在下面的示例中将其加载到 AppView::initialize()

public function initialize(): void
{
    // All option values should match the corresponding options for `GlideFilter`.
    $this->loadHelper('ADmad/Glide.Glide', [
        // Base URL.
        'baseUrl' => '/images/',
        // Whether to generate secure URLs.
        'secureUrls' => false,
        // Signing key to use when generating secure URLs.
        'signKey' => null,
    ]);
}

以下是 GlideHelper 的可用方法

    /**
     * Creates a formatted IMG element.
     *
     * @param string $path Image path.
     * @param array $params Image manipulation parameters.
     * @param array $options Array of HTML attributes and options.
     *   See `$options` argument of `Cake\View\HtmlHelper::image()`.
     * @return string Complete <img> tag.
     */
    GlideHelper::image(string $path, array $params = [], array $options = []): string

    /**
     * URL with query string based on resizing params.
     *
     * @param string $path Image path.
     * @param array $params Image manipulation parameters.
     * @return string Image URL.
     */
    GlideHelper::url(string $path, array $params = []): string

使用此辅助工具的主要好处是,根据 secureUrls 配置的值,生成的 URL 将包含一个令牌,该令牌将由中间件验证。这防止了查询字符串参数的修改。