Jump to content

getting infinite loop on simple redirect module


Marc
 Share

Recommended Posts

I am trying to make a simple wiredata module that lets me select a page I want all visitors to be redirected to. I have this working in ready.php but then I decided on putting it in a module and I can't get it to work. Here's the relevant bits:

    public function ready()
    {
        $this->addHookBefore('Page::render', $this, 'redirectUsers');
    }

    public function redirectUsers(HookEvent $e)
    {
        $page = $e->object;

        // The page we want to redirect to.
        $redirect = $e->pages->get($this->redirectPage);

        if ($page->id == $redirect->id) return; // Prevent infinite loop.

    	if (!$e->user->isLoggedin()) {
        	$e->session->redirect($redirect, false); // 'false' indicates 302 temp redirect.
    	}
    }

I left some checks out for simplification. Whenever I'm not on the page that I want to redirect to, an infinite redirect loop starts. Could anybody explain why that is?

Link to comment
Share on other sites

Also as a side note. Not sure what the $this->redirectPage is but you don't need to pages->get() it when you compare the id anyway.

Also if you have already an autoload module with ready() you could do it directly in there instead of a hook. $this->wire("page") being the page requested about to get rendered.

public function ready() {
	$redirectPage = $this->wire("pages")->get(1001);
	if($this->wire("page") === $redirectPage) return;
	$this->wire("session")->redirect($redirectPage->url, false);
}
  • Like 1
Link to comment
Share on other sites

14 hours ago, Soma said:

How about redirect to the url page->url not the page object which would be the id.

Thank you, that's it of course :-[

14 hours ago, Soma said:

Also i would use $this->wire ('pages')->... not $event->pages...

I was using the wire way at first but searching the forums I noticed someone using $event object for this so I decided to give it a try, not really understanding the differences.

Link to comment
Share on other sites

15 minutes ago, Marc said:

I was using the wire way at first but searching the forums I noticed someone using $event object for this so I decided to give it a try, not really understanding the differences.

 

Quote

$event is the HookEvent object, that's passed into each hooked function. It holds all the information needed about the hooked function, arguments, objects, return values and so on. (by @LostKobrakai)

You could also use TracyDebugger to debug $event and see what the object contain.

 

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...