1

For an upcoming site build, I'm going to need to capture information on every page load for a number of sections. These will be pages based on standard entries, so I'd prefer to use traditional routing (so not handled through a custom controller). There will probably be three different sections that will each have the same information captured when the page is loaded – basically just a list of categories so we can track the most popular type of content and display it as a dashboard widget.

At first I assumed I could do this with an event, but it doesn't look like there are any events for a page being loaded. I'm currently thinking that I use JavaScript to fire an AJAX request to a plugin and send the data along. This will work, but generate extra page loads. I'm thinking it'd be more efficient if I could keep everything server side.

Is there some way to do this that I'm not seeing?

5

Add a init() method to your plugin and as long as it's installed and enabled, it'll be called on every request.

public function init()
{
    parent::init();

    /* Do your stuff */
}

If you want it to only happen on front-end requests, you can use:

if (craft()->request->isSiteRequest()) { ... }
| improve this answer | |
  • 3
    +1 Read my mind, great answer. Definitely heed the isSiteRequest advice... there are probably a lot of Craft requests in which you wouldn't want to trigger your behavior. – Lindsey D Apr 20 '16 at 18:07
  • Perfect, thank you! EDIT: Sorry, I was asking more about the craft()->request stuff, but I just confirmed that it can do what I need. Thanks again! – Gavin Anderegg Apr 20 '16 at 18:34
  • I also check to see that I'm in a specific page in the control panel sometimes like this. $pattern = '/mycraftplugin\/subpage$/'; $isCorrectSubpagePage = preg_match($pattern, craft()->request->requestUri ); // if we are in the control panel on the banner upload page, if ( craft()->request->isCpRequest() && $isCorrectSubpagePage ) { ... do something } – John Morton Apr 21 '16 at 15:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.