1

I am working with CakePHP for quite a while and think that I have a pretty good understanding of the mvc-principle. But today, I encountered a little problem that I do not now how to solve while sticking with mvc.

In my database, there is a table for variations of my views. It works a lot like A/B-testing. When my view is shown, I need to select one of the variations saved in the database.

So in my view, there needs to be something like this:

<?php
    $variant = $this->Helper->getVariant();

    switch($variant) {
        case 'a':
            echo "some link or content";
            break;
        case 'b':
            echo "some other content";
            break;
    }
?>

But by accessing getVariant(), the chosen variant has to be updated in the database, the number of views has to be updated. This is why I do not want to have getVariant() in the Controller, because it must only be run when the View actually needs it. Because the logic (Controller) and the display (view) are separated, I can not determine in the controller if the getVariant() is needed or not. What to do?

Lars Ebert
  • 3,487
  • 2
  • 24
  • 46

1 Answers1

1

Create an action in your controller that will updates the database. Then use Ajax in your view to call that function without refreshing or altering the page.

Phillaf
  • 142
  • 1
  • 9
  • But what if JavaScript is disabled in the browser? Plus it will result in a slightly delayed update of the database. Why is it better to send an ajax-call to the controller (which the user easily could disable or manipulate) than including a Model in the Helper? – Lars Ebert Jul 14 '13 at 16:03
  • 2
    Use an image beacon (an image that points at the action which bumps the counter) and there's then no js required – AD7six Jul 14 '13 at 18:19
  • @LarsEbert The whole purpose of MVC is to separate database and logic from presentation. Helpers are part of the presentation layer. Their role is to hold presentation elements shared by multiple views, not to hold code related to database / logic. – Phillaf Jul 15 '13 at 18:20