priti narang
priti narang

Reputation: 236

Calling of afterSave method in application.php file slowing down complete platform and showing memory_limit exceed error

I am calling afterSave method in application.php to perform action on all models saving event. Issue is whenever I using SAVE method inside afterSave method application showing fatal error:

SQLSTATE[HY000]: General error: 2006 MySQL server has gone away

Point is same method working fine in specific model, without any memory exhausted error, I think there is something that need to be fixed over database connection. Below is the code which one I am trying.

//Application.php file

namespace App;
...
...
\Cake\Event\EventManager::instance()->on(
    'Model.afterSave',
    function (
        \Cake\Event\EventInterface $event,
        \Cake\Datasource\EntityInterface $entity,
        \ArrayObject $options
    ) {
    $auth_data = isset($_SESSION['Auth'])?$_SESSION['Auth']:[];
    $ActionLogs = TableRegistry::get('ActionLogs');
    $ActionLogsEntity = $ActionLogs->newEmptyEntity();
    $ActionLogsEntity->change_log = $change_log;
    $ActionLogsEntity->action_taken_by = $auth_data->username;
    $ActionLogs->save($ActionLogsEntity); //This statement working fine in specific modelTable

class Application extends BaseApplication
implements AuthenticationServiceProviderInterface
   {
    ...
    ...
   }

 

Upvotes: 0

Views: 136

Answers (1)

ndm
ndm

Reputation: 60463

Aside from the fact that the code should go into the Application class' bootstrap() method as mentioned in the comments, when you save inside of an afterSave event that listens to all models, then you naturally create a recursion, as saving the log will trigger an afterSave event too.

You have to put a safeguard in place that prevents the logging logic from running when the afterSave event belongs to the logging model, for example:

if ($event->getSubject() instanceof \App\Model\Table\ActionLogsTable) {
    return;
}

// ...

Upvotes: 1

Related Questions