We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

need to know which user has changed a record

Hello there in my models there must be a general behavior of tracking changes of sensitive data. Therefore i overwrite the save method of Mvc/Model

        $id = $this->readAttribute('id');
        $newData = $this->toArray();
        if(!is_numeric($id))
            $id = "'".$id."'";
        $oldData = $this->findFirst("id=".$id)->toArray();
        $recordSaved = parent::save($newData, $whitelist);
        $logger = $this->getDi()->getShared('logger');
        $logger->log("hello from save", Logger::INFO);
        if($recordSaved && ($newData != $oldData)) {
            //track changes
            echo "change found";
            $log = new Logs();
            $log->item = $this->readAttribute('id');
            $log->user = "SFE";
            $log->change_time = date("Y-m-d H:i:s");
            $log->changes = "Blaa";
            $log->save();
        }
        return $recordSaved;

now i miss some information in my "custom logs":

  1. which user identity made the change
  2. the host ip of the user who made the change

At the moment i cannot see how i can access any session or request object from within the model.

Thanks for your help.

Stefan

edited Jun '14

never mind a little di works wonders :)

            $log->item = $this->readAttribute('id');
            $identity = $this->getDi()->getAuth()->getIdentity();
            $log->user = $identity[0];
            $log->change_time = date("Y-m-d H:i:s");
            $log->source_ip = $this->getDi()->getRequest()->getClientAddress();
            $log->changes = "Blaa";