samsonasik/redirect-handler-module

Laminas 模块用于处理 URL 重定向

3.0.0 2020-01-07 17:03 UTC

README

PHP version Software License Build Status Coverage Status Downloads

RedirectHandlerModule 是一个模块,用于处理在给定的 URL 重定向插件未在您的 Laminas 应用程序中注册时的重定向。它简单地覆盖了现有的 Laminas 重定向插件,因此我们可以直接使用它。

这是版本 ^3.0 的 README,它仅支持 Laminas 3 和 php ^7.1。

对于版本 2,您可以在 版本 2 的 README 中阅读,它仍然支持 ZF3,并具有 php ^7.1 的支持。

对于版本 1,您可以在 版本 1 的 README 中阅读,它仍然支持 ZF2,并具有 php ^5.6|^7.0 的支持。

例如,我们在控制器中使用 redirect() 插件

$redirect = '/foo'; // may be a variable from GET
return $this->redirect()->toUrl($redirect);

如果传递的 $redirect 作为 URL 是有效的并且在路由中已注册,则使用默认的 redirect() 实现,否则将重定向到在 config/autoload/redirect-handler-module.local.php 中注册的默认 default_url

例如,我们定义

return [
    'redirect_handler_module' => [
        'allow_not_routed_url' => false,
        'default_url' => '/',
        'options' => [
            'exclude_urls' => [
                // 'https://www.github.com/samsonasik/RedirectHandlerModule',
            ], // to allow excluded urls to always be redirected
            'exclude_hosts' => [
                // 'www.github.com'
            ],
        ],
    ],
];

这意味着,我们不允许重定向到未注册的路由之外,每当发现路由中的未注册 URL 时,我们将重定向到默认的 default_url。它还禁用了重定向到自身,因此您不能重定向到自身。

对于一些特殊 URL,即使未在路由中注册,也可以重定向,您可以在 exclude_urls/exclude_hosts 选项中注册。

如果您定义了 exclude_urls/exclude_hosts 选项,其中一个是您自己的当前 URL/主机/域名,那么您仍然可能遇到“无限”的重定向循环。因此,请确保 exclude_urls/exclude_hosts 不是您自己的当前内容。

默认实现的重定向到自身是静默的,您可以在 Module::onBootstrap($e) 中触发您的监听器来处理重定向到自身。

class Module
{
    public function onBootstrap($e)
    {
        $app           = $e->getApplication();
        $eventManager  = $app->getEventManager();
        $sharedManager = $eventManager->getSharedManager();

        $sharedManager->attach('RedirectHandlerModule\Controller\Plugin\Redirect', 'redirect-same-url', function() {
            die('You need to use different URL for Redirect');
        });

        $plugin = $app->getServiceManager()->get('ControllerPluginManager')->get('redirect');
        $plugin->setEventManager($eventManager);
    }
}

安装

通过 composer 需要

composer require samsonasik/redirect-handler-module

完成 composer 需要 后,您可以将 vendor/samsonasik/redirect-handler-module/config/redirect-handler-module.local.php.dist 复制到 config/autoload/redirect-handler-module.local.php 并根据需要进行修改。

最后,注册到 config/application.config.php

return [
    'modules' => [
        // ...
        'RedirectHandlerModule',
    ],
];

贡献

欢迎贡献。请阅读 CONTRIBUTING.md

致谢