Search code examples
phptemplatescakephpcakephp-helper

Alter database row from Helper or Component - which ist better?


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?


Solution

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