Jump to content

init.inc invoked multiple times?


bmacnaughton
 Share

Recommended Posts

We use init.inc in our site implementation. There is a class that is used across all our pages, a global variable referring to the instantiated class, and a function that returns the global variable so it's available within other functions.

Recently I've had issues with either the function or the class being redeclared.

How can init.inc be included more than once? Can it be set to use require_once in some fashion?

Link to comment
Share on other sites

If you're using that file with prepend/appendTemplateFile and you're rendering multiple pages in a single request (e.g. by using $page->render()), then this is expected behavior. At least since the introduction of init.php/ready.php using prepend/appendTemplateFile is not the correct place for any class instantiations or global variable invocations. Do this in init/ready.php and leave prepend/appendTemplateFile for anything that's part of your page rendering process, e.g. wrapping the body markup in the html skeleton or alike. 

  • Like 3
Link to comment
Share on other sites

Thank you, again. I had been reading an old post that highlighted prepend/append. It's in the "How to structure your template files" tutorial. https://processwire.com/docs/tutorials/how-to-structure-your-template-files/page4.

I don't believe I ever called $page->render() but did call $form->render() and $tree->render() (from MarkupSimpleNavigation).

Link to comment
Share on other sites

I've moved the class declaration to ready.php as it depends on some specific page information.

But I left function declarations in init.inc. It's not generally a problem, but is in one case - when I "throw new Wire404Exception()" it tries to redeclare the functions. Why does throwing that exception result in reloading init.inc? Shouldn't it just redirect to the 404 page?

Link to comment
Share on other sites

PW aborts the page in a case the page isn't viewable or not found and renders the 404 instead. A 404 is never a redirect to the 404 page. A 404 always stays at the requested URL and sends a 404 header instead. The rendering of the 404 page does a $page->render(), thus calling the init.php again.

That's why you should include() a functions php with required_once() or alike to avoid redeclarations.

  • Like 4
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...