Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to log database errors in MVC Architecture

Or any framework for that matter.

Using Zend Framework 2 as an example, I have the following table class:

<?php

namespace Contact\Model;

use Zend\Db\TableGateway\TableGateway;
use Zend\Db\TableGateway\AbstractTableGateway;
use Zend\Log\Logger;

class UserContactsTable extends AbstractTableGateway
{
    protected $tableGateway;

    /**
     *
     * @var \Zend\Log\Logger Instance
     */
    protected $logger;

    public function __construct(TableGateway $tableGateway, Logger $logger )
    {
        $this->tableGateway = $tableGateway;
        $this->logger       = $logger;
    }

    /**
     * Save a contact
     * 
     * @param \Sms\Model\UserContact $userContact
     */
    public function saveUserContact(UserContact $userContact)
    {
        $data = array(
            'user_id'       => $userContact->user_id,
            'contact_id'    => $userContact->contact_id
        );

        try {
            $this->tableGateway->insert($data);
        } catch (\Exception $e) {
                    //log
            $this->logger->crit($omeErrMsg);

        }
    }
}
?>

Should I be logging here? Should I tie my logger in to the table class? Should I let the saveUserContact function throw an exception if insert fails and catch in the controller and log there?

What are the best practises?

My original idea was to create a class with some constant error messages, such as insert and update failures to be used in the table class by the logger, but I'm not sure what is the correct process here.

This is not really limited to PHP or Zend Framework 2 but just so happens to be the language I am using.

like image 307
Aydin Hassan Avatar asked Feb 18 '23 21:02

Aydin Hassan


1 Answers

I'd be of the opinion that individual components of a system should be as decoupled as possible. So in this example, if saveUserContact happens to fail then it should probably result in an exception being thrown because this isn't the expected behaviour. This class doesn't need to know about what will happen 'further up the chain', such as error logging.

As you mentioned, it would be better to throw the exception and catch it in your controller (or some other form of listener perhaps), which would then handle the logging.

The benefit of such an approach is that your system will be much easier to test because you'll have less objects to stub when constructing your UserContactsTable (mock) object to test.

like image 192
RobMasters Avatar answered Feb 27 '23 09:02

RobMasters