Welcome to Abdul Malik Ikhsan's Blog

Zend Framework 2 : Handling Db connection Error

Posted in Tutorial PHP, Zend Framework 2 by samsonasik on June 2, 2013

zf2-zendframework2Db Connection error is not part of dispatch.error, so we should make a tricky way to handle it to make user happy when see the page. We should try the connection, and catch when failed. call ViewModel to set template with our custom error page, then render with ViewRenderer.
This is it :

//filename : module/YourModule/Module.php
namespace YourModule;
use Zend\Mvc\MvcEvent;

class Module
{
    public function onBootstrap(MvcEvent $e)
    {
        $application   = $e->getApplication();
        $sm            = $application->getServiceManager();
        
        //try to connect, and if not connected, then catch...
        try {
            $dbInstance = $application->getServiceManager()
                                      ->get('Zend\Db\Adapter\Adapter');
            $dbInstance->getDriver()->getConnection()->connect();
        } catch (\Exception $ex) {
            $ViewModel = $e->getViewModel();
            $ViewModel->setTemplate('layout/layout');
                
            $content = new \Zend\View\Model\ViewModel();
            $content->setTemplate('error/mydberrorpagecustompage');
            
            //set $this->layout()->"content" variable
            //with error/mydberrorpagecustompage.phtml
            $ViewModel->setVariable('content', $sm->get('ViewRenderer')
                                                  ->render($content));
            
            exit($sm->get('ViewRenderer')->render($ViewModel));
        }
    }
    
    public function getConfig() { /* common code here */ }
    public function getAutoloaderConfig(){ /*common code here */   }
}

Still want to using EventManager? use at Wildcard attachment to make $callback available in all events (we can’t rely on dispatch.error, render.error, or other), like the following :

//filename : module/YourModule/Module.php
namespace YourModule;
use Zend\Mvc\MvcEvent;

class Module
{
    public function onBootstrap(MvcEvent $e)
    {
        $application   = $e->getApplication();
        $eventManager  = $application->getEventManager();
        
        //using '*' to make $callback available in all events. 
        $eventManager->attach('*', array($this, 'dbInstanceError' ), 1000); 
    }

    public function dbInstanceError(MvcEvent $e)
    {
        $application   = $e->getTarget();
        $sm            = $application->getServiceManager();
        
        //try to connect, and if not connected, then catch...
        try {
            $dbInstance = $application->getServiceManager()
                                      ->get('Zend\Db\Adapter\Adapter');
            $dbInstance->getDriver()->getConnection()->connect();
        } catch (\Exception $ex) {
            $ViewModel = $e->getViewModel();
            $ViewModel->setTemplate('layout/layout');
                
            $content = new \Zend\View\Model\ViewModel();
            $content->setTemplate('error/mydberrorpagecustompage');
            
            //set $this->layout()->"content" variable
            //with error/mydberrorpagecustompage.phtml
            $ViewModel->setVariable('content', $sm->get('ViewRenderer')
                                                  ->render($content));
            
            echo $sm->get('ViewRenderer')->render($ViewModel);
            $e->stopPropagation();
        }
    } 
    
    public function getConfig() { /* common code here */ }
    public function getAutoloaderConfig(){ /*common code here */   }
}

If we are using EventManager, we can use :

$e->stopPropagation();

to stop further event.

About these ads

6 Responses

Subscribe to comments with RSS.

  1. […] mit der Datenbank zu loggen habe ich mich an dem Beispiel von Abdul Malik Ikhsan gehalten: Zend Framework 2 : Handling Db connection Error | Welcome to Abdul Malik Ikhsan's Blog Zweit Dinge gefallen mir allerdings nicht: 1. Wird die Überprüfung mehrmals ausgeführt. Gibt es […]

  2. Jeffery said, on September 7, 2013 at 7:43 am

    I would like to prevent exiting the code with exit statement, for which you have provided example. How can I get this to work while being able to listen to MvcEvent::EVENT_DISPATCH_ERROR as well? Here is my code:

    https://gist.github.com/anonymous/6471770

    The above code works, but I would like to prevent from using exit statement. Also is it possible to send a 503 header when the database connection fails?

    • samsonasik said, on September 7, 2013 at 1:20 pm

      for event specific, pass array of specific event:

      $eventmanager->attach(array('dispatch', 'dispatch.error'), ....
      

      of course, you can use response object as well :

      $response = $e->getResponse();
      $response->setStatusCode(503); //change status code here
      $response->setContent($contenthere);
      
      $response->send();
      

      You can stop event with :

      $e->stopPropagation();
      

      Instead of exit(); for specific event.

  3. […] Abdul Malik Ikhsan: Handling Db connection Error […]

  4. Jeffery said, on September 9, 2013 at 11:41 am

    Thanks, I got the status code working now :)


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 238 other followers

%d bloggers like this: