Detect the page argument from request automatically

This commit is contained in:
huangzhhui 2019-06-16 01:47:28 +08:00
parent 0d74023801
commit 5e750905fc
2 changed files with 49 additions and 0 deletions

View File

@ -14,6 +14,7 @@ namespace Hyperf\Paginator;
use Hyperf\Contract\LengthAwarePaginatorInterface;
use Hyperf\Contract\PaginatorInterface;
use Hyperf\Paginator\Listener\PageResolverListener;
class ConfigProvider
{
@ -26,6 +27,9 @@ class ConfigProvider
],
'commands' => [
],
'listeners' => [
PageResolverListener::class,
],
'scan' => [
'paths' => [
],

View File

@ -0,0 +1,45 @@
<?php
namespace Hyperf\Paginator\Listener;
use Hyperf\Event\Contract\ListenerInterface;
use Hyperf\Framework\Event\BootApplication;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\Paginator\Paginator;
use Hyperf\Utils\ApplicationContext;
class PageResolverListener implements ListenerInterface
{
/**
* @return string[] returns the events that you want to listen
*/
public function listen(): array
{
return [
BootApplication::class,
];
}
/**
* Handle the Event when the event is triggered, all listeners will
* complete before the event is returned to the EventDispatcher.
*/
public function process(object $event)
{
Paginator::currentPageResolver(function ($pageName = 'page') {
if (! ApplicationContext::hasContainer() || ! interface_exists(RequestInterface::class)) {
return 1;
}
$container = ApplicationContext::getContainer();
$page = $container->get(RequestInterface::class)->input($pageName);
if (filter_var($page, FILTER_VALIDATE_INT) !== false && (int) $page >= 1) {
return (int) $page;
}
return 1;
});
}
}