Zend Framework a useful error class

Am pornit de la clasa asta, si am "curatato un pic" dupa bunul meu plac si deasemenea am folosit Zend_Log nu Zend_Mail, ca nu am chef sa primesc 5000 precum ca niste idiotii nu au nimerit un url corect si etc, mai bine frumos totul scris!

ErrorController.php

<?php
class ErrorController extends Zend_Controller_Action
{
    public function errorAction()
    {
        
        // Ensure the default view suffix is used so we always return good
        // content
        $this->_helper->viewRenderer->setViewSuffi'phtml');
    
        // Grab the error object from the request
        $errors = $this->_getParam('error_handler');
    
        switch ($errors->type) {
          case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
          case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
            // 404 error -- controller or action not found
            $this->getResponse()->setHttpResponseCode(404);
            $this->view->message = 'Page not found';
            $this->view->code  = 404;
            if ($errors->type == Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER) {
              $this->view->info = sprintf(
                          'Unable to find controller "%s" in module "%s"',
                          $errors->request->getControllerName(),
                          $errors->request->getModuleName()
                        );
            }
            if ($errors->type == Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION) {
              $this->view->info = sprintf(
                          'Unable to find action "%s" in controller "%s" in module "%s"',
                          $errors->request->getActionName(),
                          $errors->request->getControllerName(),
                          $errors->request->getModuleName()
                        );
            }
            break;
          case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
          default:
            // application error
            $this->getResponse()->setHttpResponseCode(500);
            $this->view->message = 'Application error';
            $this->view->code  = 500;
            $this->view->info  = $errors->exception;
            break;
        }
        
       /*-------------------------------------------
          --START-- Logg the errors using Zend_Log
       --------------------------------------------*/
        $writer = new Zend_Log_Writer_Stream(Zend_Registry::get('root').'/logs/logs.ini');
        $logger = new Zend_Log($writer);
        
        $toLog  = $this->view->message." (".$this->view->code.")nn";
        $toLog .= "Zend Error Type: ".$errors->type."nn";
        $toLog .= "REQUEST_URI: ".$_SERVER['REQUEST_URI']."nn";
        if ( isset($_SERVER['HTTP_REFERER']) ) {
              $toLog .= "HTTP_REFERER: ".$_SERVER['HTTP_REFERER']."nn";
        }
        $toLog .= "Stack trace: nn". $errors->exception->getTraceAsString()."nn";
           
        $logger->log($toLog, Zend_Log::INFO);
       /*-------------------------------------------
          --END-- Logg the errors using Zend_Log
       --------------------------------------------*/
        
        $this->view->title = 'Error!';
        $this->view->heading = 'Oups! Error!';
    
        // pass the environment to the view script so we can conditionally
        // display more/less information
        $this->view->env   = $this->getInvokeArg('env');
    
        // pass the actual exception object to the view
        $this->view->exception = $errors->exception;
    
        // pass the request to the view
        $this->view->request = $errors->request;
        
    }
}

error.phtml

    <p>
        <h3><?=$this->message ?> (<?=$this->code ?></h3>
    </p>
    
    <?php
    if( $this->env == 'test' ):
     if ( isset($this->info ) ): ?>
         
    <? if ( 404 == $this->code ): ?>
      <p><b>Reason:</b> <?= $this->info ?></p>
    <?php elseif (500 == $this->code): ?>
      <p>Bad server, naughty server!<br />No donut for you!</p>
      <h4>Exception information:</h4>
     <p><b>Message:</b> <?= $this->info->getMessage() ?></p>
     <h4>Stack trace:</h4>
     <pre><?= $this->info->getTraceAsString() ?></pre>
    <?php endif; ?>
    
        <?php endif; ?>
    
    <?php endif; ?>
Scris in data de: 2009-12-17 | Fara comentarii
Iankulov Miodrag

Unixtime month&year conversion to normal string

Nu stiu daca titlul e prea maret, dar in fine sa va explic repede cum sta situatia.Daca aveti intr-un camp unixtime si vreti sa afisati toate luniile, din db pentru field-ul respectiv si faceti:

SELECT DISTINCT EXTRACT(YEAR_MONTH FROM FROM_UNIXTIME(date)) FROM `posts`

Veti primi un raspuns de genul:200908; well asta e superb, dar daca vreti sa faceti o archive, de genu cum au toate blogurile: August 2009 trebuie sa faceti cateva tricks.

Eu am scris un view helper pentru Zend Framework care face asta, sper sa va fie de folos:

class Zend_View_Helper_DateHelper extends Zend_View_Helper_Abstract
{   
    public function dateHelper($string = false)
    {
        if ($string !== false) {
            $_month = substr($string, -2);
            $_year = substr($string, 0, strlen(date("Y")));
            $months = array('01' => "January",
                            '02' => "February",
                            '03' => "March",
                            '04' => "April",
                            '05' => "May",
                            '06' => "June",
                            '07' => "July",
                            '08' => "August",
                            '09' => "September",
                            '10' => "October",
                            '11' => "Novemeber",
                            '12' => "December");
            return $months[$_month].' '.$_year;
        }else{
            return false;
        }
    }
}

Trebuie doar sa ii dati un string de genu 200908, si va prelucra el totul.Sper ca este cuiva de folos.

Scris in data de: 2009-08-20 | Fara comentarii
Iankulov Miodrag

Zend_Paginator custom url\'s

Inainte de toate vreau sa spun ca nu voi acoperii prea mult in acest post, decat basics, cum sa setati url-ul, presupun ca deja aveti basics cu Zend_Paginator so:

Ok, url-urile default pt Zend_Paginator sunt: controller/action/page/age, well astazi am avut nevoie de ceva diferit, din moment ce am mai avut m-ai multe pagina-ri pe o pagina.

In controller face-ti normal de exemplu:

    private function showData($_id)
    {
        $data = $this->artists_categories
                     ->select();
        $do = $this->db->fetchAll($data);
       
        if (count($do) > 0) {
            $paginator = Zend_Paginator::factory($do);
            $paginator->setItemCountPerPage(5)
                      ->setPageRange(5)
                      ->setCurrentPageNumber($_id);
            return $paginator;
        }else{
            return false;
        }
    }

In views/scripts/action_name/pag/file_name setati:

<?php if ($this->pageCount): ?>
  <ul class="top pag clearfix">
      <?php if(count($this->pagesInRange) >= 2): ?>
      <li>Go to page:</li>
      <?php endif;?>
<?php if (isset($this->previous)): ?>
      <li><a href="<?= $this->url(array('artists' => 'page', 'id' => $this->previous)); ?>">&laquo; Previous</a> </li>
<?php endif; ?>
<?php if(count($this->pagesInRange) >= 2): ?>
    <?php foreach ($this->pagesInRange as $page): ?>
          <li><a href="<?= $this->url(array('artists' => 'page', 'id' => $page)); ?>" <?php if($page == $this->current): ?>id="selected"<?php endif;?>><?=$page;?></a> </li>
    <?php endforeach; ?>
<?php endif; ?>
<?php if (isset($this->next)): ?>
      <li><a href="<?= $this->url(array('artists' => 'page', 'id' => $this->next)); ?>">Next &raquo;</a></li>
<?php endif; ?>
  </ul>
<?php endif; ?>

Url-ul setat mai sus arata cam asa controller/action/artists/page/id/Id-ul

Sa nu uitati sa setati si route

/* Artists */
$ad->addRoute( 'artists', new Zend_Controller_Router_Route('artists/index/page/artists/id/:id', array('module' => 'admin','controller' => 'artists', 'action' => 'index')) );

Sper sa va fie de folos.

Scris in data de: 2009-08-12 | 2 Comentarii
Iankulov Miodrag

Font pentru programatori

Cred ca este cel mai cool pe care l-am vazut pana acuma, thx to iamntz, font-ul se numeste Inconsolata, m-ai jos aveti si o poza, asa ca bonus de la mine , poate va convingeti asa:

http://content.screencast.com/users/mutu23/folders/Jing/media/3f3eae68-3caf-4bce-849e-972d78fe8a0c/2009-08-07_1546.png

Scris in data de: 2009-08-07 | 2 Comentarii
Iankulov Miodrag

Exemplu Zend Framework cu Zend_Log

In general la aplicatii mari, esti tampit daca nu faci si un easy debug, ca daca "pusca" ceva sa stii imediat unde sa repari, well solutia e logica: logs, dar cam 90% din mesajele de eroare nu vrei sa fie publice, pentru ca contin prea multe informatii, so daca scrii log-urile de eroare intr-un fisier e cel mai bine, si asta o face Zend_Log si mai bine.

Eu acuma am sa dau doar un exemplu, de genul cum gasiti in documentatie.

$writer = new Zend_Log_Writer_Stream(root.'/logs/logs.ini');
$logger = new Zend_Log($writer);       
$logger->log('Sunt in exstaz', Zend_Log::INFO);

root = path-ul de root al aplicatiei

/logs/logs.ini = folderul/numele fisierului unde se vor scrie datele

Zend_Log::INFO = Prioritate built-in de la ZF, mai jos aveti toate exemplele de prioritati.

EMERG = 0; // Emergency: system is unusable
ALERT = 1; // Alert: action must be taken immediately
CRIT = 2; // Critical: critical conditions
ERR = 3; // Error: error conditions
WARN = 4; // Warning: warning conditions
NOTICE = 5; // Notice: normal but significant condition
INFO = 6; // Informational: informational messages
DEBUG = 7; // Debug: debug messages

Ok, iar in logs.ini errorile vor avea urmatorul format:

2009-07-21T18:56:37+03:00 INFO (6): Sunt in exstaz

Mult noroc la curve!

Scris in data de: 2009-07-21 | Fara comentarii
Iankulov Miodrag