SlideShare a Scribd company logo
1 of 66
Download to read offline
ZEND FRAMEWORK:
abordagem prática
ZEND FRAMEWORK:
abordagem prática


MARCELO DE FREITAS ANDRADE
http://mfandrade.wordpress.com 
mfandrade@gmail.com 
                                  2
ROTEIRO

     O padrão MVC
 ●




     Configurando o ZF
 ●




     Conhecendo o ZF
 ●




     Análise de situações comuns
 ●




                                   3
O PADRÃO MVC




Adaptado de
                      4
betterexplained.com
CONFIGURANDO O ZF




                    5
CONFIGURANDO O ZF




                    6
CONFIGURANDO O ZF


Tutorial Zend Framework:

http://framework.zend.com/docs/quickstart/




                                             7
CONFIGURANDO O ZF




                    8
CONFIGURANDO O ZF




                    9
CONFIGURANDO O ZF




          http://framework.zend.com/download



                                          10
CONFIGURANDO O ZF




          Configurar esta pasta para a raiz do
          servidor web (DocumentRoot).

                                                 11
CONFIGURANDO O ZF




           OBS: Necessário habilitar o 
           mod_rewrite para reescrita de URLs e 
           o suporte a arquivos .htaccess no 
           Apache, configurando­os de acordo 
           com o tutorial.



                                                12
/public/index.php
<?php
// Passo 1
define('APPLICATION_PATH', realpath(dirname(__FILE__) .
'/../application/'));
set_include_path(
    APPLICATION_PATH . '/../library'
    . PATH_SEPARATOR . get_include_path()
);

// Passo 2
require_once quot;Zend/Loader.phpquot;;
Zend_Loader::registerAutoload();

(continua...)




                                                          13
/public/index.php
// Passo 3
try {
    require '../application/bootstrap.php';
} catch (Exception $exception) {
    echo '<html><body><center>'
       . 'Uma exceção ocorreu!.';
    if (defined('APPLICATION_ENVIRONMENT')
        && APPLICATION_ENVIRONMENT != 'production'
    ){
        echo '<br /><br />' . $exception->getMessage() . '<br />'
           . '<div align=quot;leftquot;>Stack Trace:'
           . '<pre>' . $exception->getTraceAsString() .
'</pre></div>';
    }
    echo '</center></body></html>';
    exit(1);
}


// Passo 4
Zend_Controller_Front::getInstance()->dispatch();               14
/application/bootstrap.php
<?php
// Constante
defined('APPLICATION_PATH')
    or define('APPLICATION_PATH', dirname(__FILE__));

// Tipo de ambiente
defined('APPLICATION_ENVIRONMENT')
    or define('APPLICATION_ENVIRONMENT', 'development');

// Inicia os controllers
$frontController = Zend_Controller_Front::getInstance();

// Onde estão nosso controllers
$frontController->setControllerDirectory(APPLICATION_PATH .
'/controllers');

// Repassa a constante aos controllers
$frontController->setParam('env', APPLICATION_ENVIRONMENT);


                                                              15
/application/bootstrap.php
(continuação...)

// Teremos layouts de site?
Zend_Layout::startMvc(APPLICATION_PATH . '/layouts');

// Arquivo de configuração
$configuration = new Zend_Config_Ini(
    APPLICATION_PATH . '/config.ini',
    APPLICATION_ENVIRONMENT
);

// Registro
$registry = Zend_Registry::getInstance();
$registry->configuration = $configuration;
$registry->dbAdapter     = $dbAdapter;

// Limpa para encerrar
unset($frontController);


                                                        16
/application/controllers/IndexController.php
<?php
// application/controllers/IndexController.php

class IndexController extends Zend_Controller_Action
{
    public function indexAction()
    {
    }
}




/application/views/index/index.phtml
<? // application/views/index/index.phtml ?>
<h1 align=quot;centerquot;>
    Hello, Zend Framework MVC!
</h1>

                                                       17
/application/controllers/ErrorController.php
<?php
class ErrorController extends Zend_Controller_Action
{
    public function errorAction()
    {
        $this->_helper->viewRenderer->setViewSuffix('phtml');
        $errors = $this->_getParam('error_handler');

        switch ($errors->type) {
            case
Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
            case
Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:

                $this->getResponse()->setHttpResponseCode(404);
                $this->view->message = 'Página não encontrada.';
                break;
            default:
                $this->getResponse()->setHttpResponseCode(500);
                $this->view->message = 'Application error';
                break;                                             18
       }
/application/controllers/ErrorController.php
(continuação...)

        $this->view->env       = $this->getInvokeArg('env');

        $this->view->exception = $errors->exception;

        $this->view->request   = $errors->request;
    }
}




                                                               19
/application/views/error/error.phtml
<h1>Ocorreu um erro!</h1>
<h2><?= $this->message ?></h2>

<? if ('development' == $this->env): ?>
    <h3>Exceção ocorrida:</h3>
    <p>
        <b>Menssagem:</b> <?= $this->exception->getMessage() ?>
    </p>

   <h3>Stack trace:</h3>
   <pre><?= $this->exception->getTraceAsString() ?></pre>

    <h3>Parâmetros da requisição:</h3>
    <pre><? var_dump($this->request->getParams()) ?></pre>
<? endif ?>




                                                                  20
/application/layouts/layout.phtml
<?= $this->doctype() ?>
<html xmlns=quot;http://www.w3.org/1999/xhtmlquot;>
<head>
  <meta http-equiv=quot;Content-Typequot; content=quot;text/html; charset=utf-
8quot; />
  <title>ProjetoZF</title>
  <?= $this->headScript() ?>
  <?= $this->headLink()->appendStylesheet('/css/global.css') ?>
</head>
<body>
  <div id=”header”>
   <h1>Bem-vindo ao ProjetoZF!</h1>
   <a href=”<?= $this->url(array('controller'=> 'index', 'action'=>
'index')) ?>“>Página inicial</a>
  </div>

  <div id=”content”>
   <?= $this->layout()->content ?>
  </div>
</body>
</html>                                                         21
CONHECENDO O ZF




                  22
CONHECENDO O ZF


             MVC
                 Zend_Db_Table
             ●




                 Zend_Controller_Action
             ●




                 Zend_View_Helper
             ●




                                          23
CONFIGURANDO O BANCO

;; /application/config.ini
[producao]
database.adapter         = PDO_MYSQL
database.params.host     = dbserver.example.com
database.params.username = username
database.params.password = password
database.params.dbname = dbname

[teste : producao]
database.params.dbname   = dbname_test

[desenv : producao]
database.params.dbname   = dbname_desenv
database.params.host     = dbtest.example.com
                                                  24
PROGRAMANDO MODELS




                     25
PROGRAMANDO MODELS

<?php
class GenericModel extends Zend_Db_Table
{
   // insere dados do array em campos homônimos
   public function insert(array $data)
   {
      $fields = $this
        ->info(Zend_Db_Table_Abstract::COLS);

        foreach ($data as $field => $value)
          if (!in_array($field, $fields))
             unset($data[$field]);

        return parent::insert($data);
    }
}                                                 26
PROGRAMANDO MODELS




                     27
PROGRAMANDO MODELS

<?php
requice_once APPLICATION_PATH .
  '/models/GenericModel.php';

class Post extends GenericModel
{
   // lógica de negócio “blug do futuro”
   public function publicar($data)
   {
      $data['created']= date('Y-m-d',
       strtotime('now +7 days');
      return parent::insert($data);
    }

}
                                           28
ESCREVENDO CONTROLLERS




                         29
ESCREVENDO CONTROLLERS

<?php
class PostController extends
  Zend_Controller_Action
{
   // definir referência ao model
   protected $_Post;

  public function init()
  {
     // instanciar os models e outras operações
     require_once APPLICATION_PATH .
      '/models/Post.php';
     $this->_Post= new Post();
  }
                                                  30
ESCREVENDO CONTROLLERS

// (continuação...)
   // lista todos os posts e joga para a view
   public function indexAction()
   {
      $posts= $this->_Post->fetchAll();
      $this->view->posts= $posts->toArray();
   }
   // action para visualizar um dado post
   public function verAction()
   {
      $parms= $this->getRequest()->getParams();
      $postid= $parms['id'];
      $post= $this->_Post->find($postid);
      $this->view->post= $post;
   }
                                                  31
DEFININDO VIEWS

<!-- /application/views/post/index.phtml -->
<?php foreach($this->posts as $post): ?>

  <h2><a href=”<?php echo $this->url(
   array('controller'=> 'post'
   , 'action'=> 'ver'
   , 'id'=> $post['id'])); ?>”>
      <?php echo $post['titulo']; ?></a></h2>

  <h3>Publicado em: <?php
     echo $post['created']; ?></h3>

  <p><?php echo nl2br($post['texto']); ?></p>

<?php endfor; ?>                           32
ANÁLISE DE SITUAÇÕES COMUNS


    EXIBIÇÃO DE MENSAGENS
●




    FILTROS E VALIDAÇÕES
●




    POPULANDO CAMPOS
●




    ASSOCIANDO MODELS
●




    AUTENTICAÇÃO E AUTORIZAÇÃO
●




                                 33
ANÁLISE DE SITUAÇÕES COMUNS


    EXIBIÇÃO DE MENSAGENS
●




    FILTROS E VALIDAÇÕES
●




    POPULANDO CAMPOS
●




    ASSOCIANDO MODELS
●




    AUTENTICAÇÃO E AUTORIZAÇÃO
●




    http://framework.zend.com/manual/en/
                                           34
EXIBIÇÃO DE MENSAGENS




                        35
EXIBIÇÃO DE MENSAGENS

<?php
class GenericController extends
  Zend_Controller_Action
{
   protected $_mess; protected $_redir;

  public function init()
  {
     $this->_mens= $this->_helper
       ->getHelper('FlashMessenger');
     $this->_redir= $this->_helper
       ->getHelper('Redirector');
  }


                                          36
EXIBIÇÃO DE MENSAGENS

// (continuação...)

    protected function flash($msg, $to)
    {
       $this->_mess->addMessage($msg);
       $this->_redir->gotoUrl($to);
       exit;
    }

    public function postDispatch()
    {
       $this->view->messages= join(' ', $this
        ->_mess->getMessages());
       parent::postDispatch();
    }
}                                               37
EXIBIÇÃO DE MENSAGENS
<?= $this->doctype() ?>
<html xmlns=quot;http://www.w3.org/1999/xhtmlquot;>
<head>
  <meta http-equiv=quot;Content-Typequot; content=quot;text/html; charset=utf-
8quot; />
  <title>ProjetoZF</title>
  <?= $this->headScript() ?>
  <?= $this->headLink()->appendStylesheet('/css/global.css') ?>
</head>
<body>
  <div id=”header”>
   <h1>Bem-vindo ao ProjetoZF!</h1>
   <a href=”<?= $this->url(array('controller'=> 'index', 'action'=>
'index')) ?>“>Página inicial</a>
  </div>

 <div id=”messages”><?= $this->messages ?></div>

  <div id=”content”>
   <?= $this->layout()->content ?>
  </div>
                                                                38
</body>
</html>
FILTROS E VALIDAÇÕES




                       39
FILTROS E VALIDAÇÕES
// PostController.php
   public function novoAction()
   {
      $req= $this->getRequest();
      if( $req->isPosted() )
      {
        $data= $req->getParameters();
        $this->_Post->insert($data);
      }
   }




                                        40
FILTROS E VALIDAÇÕES
// PostController.php
   public function novoAction()
   {
      $req= $this->getRequest();
      if( $req->isPosted() )
      {
        $data= $req->getParameters();

       $filters= array('*'=> 'StringTrim');
       $validators= array('titulo'=>'Alpha');
       $input= new Zend_Input_Filter($filters,
        $validators, $data);

       if( $input->isValid() ):
         $this->_Post->insert($input);
         $this->flash('Sucesso!', '/index');     41
       endif;
POPULANDO CAMPOS




                   42
POPULANDO CAMPOS
<!-- /appplication/views/post/novo.phtml -->
<?php echo $this->form('novoForm',
  array('method'=> 'post'));
echo $this->formErrors(); ?>

<fieldset><legend>Novo Post</legend>

<?php echo $this->formLabel('titulo', 'Título:');
echo $this->formText('titulo');
echo $this->formLabel('texto', 'Texto:');
echo $this->formTextarea('texto', null,
  array('rows'=> 3, 'cols'=> 30));
echo $this->formSubmit('btnOk', 'Cadastrar'); ?>

</fieldset></form>
                                                43
POPULANDO CAMPOS
<!-- /appplication/views/post/novo.phtml -->
<?php echo $this->form('novoForm',
  array('method'=> 'post'));
echo $this->formErrors(); ?>

<fieldset><legend>Novo Post</legend>

<?php echo $this->formLabel('titulo', 'Título:');
echo $this->formText('titulo');
echo $this->formLabel('texto', 'Texto:');
echo $this->formTextarea('texto', null,
  array('rows'=> 3, 'cols'=> 30));
echo $this->formSelect('categoria_id', null,
  null, array('Dicas', 'Tutoriais', 'Artigos') );

echo $this->formSubmit('btnOk', 'Cadastrar'); ?>   44
</fieldset></form>
POPULANDO CAMPOS
// PostController.php
   public function novoAction()
   {
      $req= $this->getRequest();

     $categorias= $this->_Post->findList();
     $this->view->categorias= $categorias;

     if( $req->isPosted() )
     {
       $data= $req->getParameters();

       $filters= array('*'=> 'StringTrim');
       $validators= array('title'=>'Alpha');
       $input= new Zend_Input_Filter($filters,
        $validators, $data);                     45
POPULANDO CAMPOS

// GenericModel.php
  public function fetchList($first= 'Selecione...',
  $id= 'id', $description= 'descricao', $where=
  null, $order= null, $count= null, $offset= null)
  {
      $fetchedOptions= $this->fetchAll($where,
       $order, $count, $offset);
      if( $first != null ):
        $listOptions[' ']= $first;
      endif;
      foreach( $fetchedOptions as $option ):
        $listOptions[$option[$id]]=
          $option[$description];
      endforeach;
      return $listOptions;
   }                                               46
POPULANDO CAMPOS
<!-- /appplication/views/post/novo.phtml -->
<?php echo $this->form('novoForm',
  array('method'=> 'post'));
echo $this->formErrors(); ?>

<fieldset><legend>Novo Post</legend>

<?php echo $this->formLabel('titulo', 'Título:');
echo $this->formText('titulo');
echo $this->formLabel('texto', 'Texto:');
echo $this->formTextarea('texto', null,
  array('rows'=> 3, 'cols'=> 30));
echo $this->formSelect('categoria_id', null,
  null, $this->categorias );

echo $this->formSubmit('btnOk', 'Cadastrar'); ?>   47
</fieldset></form>
ASSOCIANDO MODELS




                    48
ASSOCIANDO MODELS

<?php
requice_once APPLICATION_PATH .
  '/models/GenericModel.php';

class Post extends GenericModel
{
   protected $_referenceMap= array(
      'Categoria'=> array(
        'columns'        => 'categoria_id'
        , 'refTableClass'=> 'categoria'
        , 'refColumns'   => 'id'));
   protected $_dependentTables=
      array('PostTag');


                                             49
ASSOCIANDO MODELS

<?php
class PostController extends
  Zend_Controller_Action
{
// (...)
   // lista todos os posts e joga para a view
   public function indexAction()
   {
      $posts= $this->Post->fetchAll();
      $this->view->posts= $posts;
   }




                                                50
ASSOCIANDO MODELS

<!-- /application/views/post/index.phtml -->
<?php foreach($this->posts as $post): ?>

  ...

  <h3>Publicado em: <?php
     echo $post->created; ?></h3>

  <?php $categoria= $post
     ->findDependentRowset('Categoria');
     echo $categoria->descricao; ?>

  <p><?php echo nl2br($post->texto); ?></p>

<?php endfor; ?>                              51
ASSOCIANDO MODELS

<!-- /application/views/post/index.phtml -->
<?php foreach($this->posts as $post): ?>

  ...

  <h3>Publicado em: <?php
     echo $post->created; ?></h3>

  <?php $categoria= $post
     ->findCategoriaByPost();
     echo $categoria->descricao; ?>

  <p><?php echo nl2br($post->texto); ?></p>

<?php endfor; ?>                              52
ASSOCIANDO MODELS




                    53
ASSOCIANDO MODELS

<!-- /application/views/post/index.phtml -->
<?php foreach($this->posts as $post): ?>

  ...

  <h3>Publicado em: <?php
     echo $post->created; ?></h3>

  <?php $tags= $post
     ->findManyToManyRowset('Tag', 'PostTag');
     echo implode(', ', $tags->toArray());
      ?>

  <p><?php echo nl2br($post->texto); ?></p>
                                              54

<?php endfor; ?>
AUTENTICAÇÃO E AUTORIZAÇÃO




                             55
AUTENTICAÇÃO E AUTORIZAÇÃO

<?php
requice_once APPLICATION_PATH .
  '/models/GenericController.php';

class AuthController extends GenericController
{
   public function loginAction()
   {
      // como autenticar um usuário...
      $req= $this->getRequest();
      if( $req->isPosted() )
      {
        $parms= $req->getParams();
        // método para validar campos login e senha
        $input= $this->__validate($parms);
                                                56
AUTENTICAÇÃO E AUTORIZAÇÃO

// ...
  $db= Zend_Registry::get('dbAdapter');
  $adap= new Zend_Auth_Adapter_DbTable($db);
  $adap->setTableName('usuario');
  $adap->setIdentityColumn('login');
  $adap->setCredentialColumn('senha');

 $adap->setIdentity($input->usuario);
 $adap->setCredential(md5($input->senha));

 $auth= Zend_Auth::getInstance();
 $result= $auth->authenticate($auth);

 if( $result->isValid() )
    // trata a autenticação...
                                               57
AUTENTICAÇÃO E AUTORIZAÇÃO




                             58
AUTENTICAÇÃO E AUTORIZAÇÃO


AUTORIZAÇÃO
    recursos (resources)
●




    perfis (roles)
●




                             59
AUTENTICAÇÃO E AUTORIZAÇÃO

<?php
require_once . APPLICATION_PATH .
  '/controllers/GenericController.php';

class PostController extends GenericController
  implements Zend_Acl_Resource_Interface
{
   // definir referência ao model
   protected $_Post;

  public function getResourceId()
  {
     return 'POST';
  }
                                                 60
  // ...
AUTENTICAÇÃO E AUTORIZAÇÃO




                             61
AUTENTICAÇÃO E AUTORIZAÇÃO

// GenericController.php

  private function __configPerms()
  { // define perfis
     $chefe= new Zend_Acl_Role('chefe');
     $escritor= new Zend_Acl_Role('escritor', $chefe);

     $this->_acl= new Zend_Acl();
     $this->_acl->addRole($chefe);
     $this->_acl->addRole($escritor);
     // define recursos
     $this->_acl->add(new Zend_Acl_Resource('POST'));

     // define as permissões
     $this->_acl->allow('chefe', 'POST', null);
     $this->_acl->deny('escritor', 'POST', 'novo');62
AUTENTICAÇÃO E AUTORIZAÇÃO

// GenericController

  public function preDispatch()
  {
     // recuperar o usuário autenticado...
     $usuario= $this->__obterUsuarioAutenticado();
     $req= $this->getRequest();

     if($this->_acl->isAllowed($usuario->perfil,
      strtoupper($req->getControllerName()), $req
       ->getActionName()))

         // trata a autorização...


                                                     63
64
PERGUNTAS?




             65
 




           MUITO OBRIGADO!



       MARCELO DE FREITAS ANDRADE
Especialista em Desenv. de Aplicações para Internet
                           mfandrade@gmail.com        66

More Related Content

What's hot

Estandarizacion de macros
Estandarizacion de macrosEstandarizacion de macros
Estandarizacion de macros
gerariel
 
Quiz Component For Joomla
Quiz Component For JoomlaQuiz Component For Joomla
Quiz Component For Joomla
guestebb21a
 
Pertemuan 8 - Report Tabel
Pertemuan 8 - Report TabelPertemuan 8 - Report Tabel
Pertemuan 8 - Report Tabel
Adi Triyatmoko
 
jQuery - Javascript para quem não sabe Javascript
jQuery - Javascript para quem não sabe JavascriptjQuery - Javascript para quem não sabe Javascript
jQuery - Javascript para quem não sabe Javascript
Nando Vieira
 
Un juego creado en php
Un juego creado en phpUn juego creado en php
Un juego creado en php
Erwin Lobo
 
Php codigos interfaces fredy guzman cusihunca
Php codigos interfaces   fredy guzman cusihuncaPhp codigos interfaces   fredy guzman cusihunca
Php codigos interfaces fredy guzman cusihunca
Tigger_Fred
 
Drupal Cms Prezentace
Drupal Cms PrezentaceDrupal Cms Prezentace
Drupal Cms Prezentace
guest3d443e
 
Acções acreditadas fevereiro 2012
Acções acreditadas fevereiro 2012Acções acreditadas fevereiro 2012
Acções acreditadas fevereiro 2012
João Lima
 
亚洲铝业工业城改版展新颜读者细评点
亚洲铝业工业城改版展新颜读者细评点亚洲铝业工业城改版展新颜读者细评点
亚洲铝业工业城改版展新颜读者细评点
sugeladi
 

What's hot (20)

Sumahexavector
SumahexavectorSumahexavector
Sumahexavector
 
2km Workshop: Desenvolvimento ágil com o CakePHP
2km Workshop: Desenvolvimento ágil com o CakePHP2km Workshop: Desenvolvimento ágil com o CakePHP
2km Workshop: Desenvolvimento ágil com o CakePHP
 
Estandarizacion de macros
Estandarizacion de macrosEstandarizacion de macros
Estandarizacion de macros
 
Quiz Component For Joomla
Quiz Component For JoomlaQuiz Component For Joomla
Quiz Component For Joomla
 
Introduction à Marionette
Introduction à MarionetteIntroduction à Marionette
Introduction à Marionette
 
Pertemuan 8 - Report Tabel
Pertemuan 8 - Report TabelPertemuan 8 - Report Tabel
Pertemuan 8 - Report Tabel
 
Palestra PythonBrasil[8]
Palestra PythonBrasil[8]Palestra PythonBrasil[8]
Palestra PythonBrasil[8]
 
jQuery - Javascript para quem não sabe Javascript
jQuery - Javascript para quem não sabe JavascriptjQuery - Javascript para quem não sabe Javascript
jQuery - Javascript para quem não sabe Javascript
 
Jsoon
JsoonJsoon
Jsoon
 
Chief Keef's hologram can't catch a break, and it's a win for Keef
Chief Keef's hologram can't catch a break, and it's a win for KeefChief Keef's hologram can't catch a break, and it's a win for Keef
Chief Keef's hologram can't catch a break, and it's a win for Keef
 
Sumahexavector
SumahexavectorSumahexavector
Sumahexavector
 
Un juego creado en php
Un juego creado en phpUn juego creado en php
Un juego creado en php
 
Php codigos interfaces fredy guzman cusihunca
Php codigos interfaces   fredy guzman cusihuncaPhp codigos interfaces   fredy guzman cusihunca
Php codigos interfaces fredy guzman cusihunca
 
Practical JavaScript Programming - Session 2/8
Practical JavaScript Programming - Session 2/8Practical JavaScript Programming - Session 2/8
Practical JavaScript Programming - Session 2/8
 
Drupal Cms Prezentace
Drupal Cms PrezentaceDrupal Cms Prezentace
Drupal Cms Prezentace
 
14. add in db
14. add in db14. add in db
14. add in db
 
WordPressのテンプレートをカスタマイズするために必要なphpを初歩から解説
WordPressのテンプレートをカスタマイズするために必要なphpを初歩から解説WordPressのテンプレートをカスタマイズするために必要なphpを初歩から解説
WordPressのテンプレートをカスタマイズするために必要なphpを初歩から解説
 
Acções acreditadas fevereiro 2012
Acções acreditadas fevereiro 2012Acções acreditadas fevereiro 2012
Acções acreditadas fevereiro 2012
 
亚洲铝业工业城改版展新颜读者细评点
亚洲铝业工业城改版展新颜读者细评点亚洲铝业工业城改版展新颜读者细评点
亚洲铝业工业城改版展新颜读者细评点
 
Peek inside the fantastical Ukrainian Village home and studio of artists Jare...
Peek inside the fantastical Ukrainian Village home and studio of artists Jare...Peek inside the fantastical Ukrainian Village home and studio of artists Jare...
Peek inside the fantastical Ukrainian Village home and studio of artists Jare...
 

Viewers also liked (6)

Joomla!: uma visão geral
Joomla!: uma visão geralJoomla!: uma visão geral
Joomla!: uma visão geral
 
DevOps: Falando um pouco sobre desenvolvimento orientado a testes com Puppet
DevOps: Falando um pouco sobre desenvolvimento orientado a testes com PuppetDevOps: Falando um pouco sobre desenvolvimento orientado a testes com Puppet
DevOps: Falando um pouco sobre desenvolvimento orientado a testes com Puppet
 
#safaDojo - Coding Dojo Go lang
#safaDojo - Coding Dojo Go lang#safaDojo - Coding Dojo Go lang
#safaDojo - Coding Dojo Go lang
 
Compartilhando experiências sobre ir de bike ao trabalho
Compartilhando experiências sobre ir de bike ao trabalhoCompartilhando experiências sobre ir de bike ao trabalho
Compartilhando experiências sobre ir de bike ao trabalho
 
Slackware Linux
Slackware LinuxSlackware Linux
Slackware Linux
 
Apresentando o CakePHP
Apresentando o CakePHPApresentando o CakePHP
Apresentando o CakePHP
 

More from Marcelo Andrade

More from Marcelo Andrade (10)

Desenvolvimento para a Web com CakePHP
Desenvolvimento para a Web com CakePHPDesenvolvimento para a Web com CakePHP
Desenvolvimento para a Web com CakePHP
 
Plataforma IMMI
Plataforma IMMIPlataforma IMMI
Plataforma IMMI
 
Reflexões aleatórias para calouros em
Reflexões aleatórias para calouros emReflexões aleatórias para calouros em
Reflexões aleatórias para calouros em
 
Ciclovia belem final
Ciclovia belem finalCiclovia belem final
Ciclovia belem final
 
Testes de software automatizados
Testes de software automatizadosTestes de software automatizados
Testes de software automatizados
 
Selenium: visão geral
Selenium: visão geralSelenium: visão geral
Selenium: visão geral
 
Introdução ao Desenvolvimento com Padrões Web: XHTML Essencial
Introdução ao Desenvolvimento com Padrões Web: XHTML EssencialIntrodução ao Desenvolvimento com Padrões Web: XHTML Essencial
Introdução ao Desenvolvimento com Padrões Web: XHTML Essencial
 
Visão Ágil Academic Meeting / TaSAFO em fatos e fotos
Visão Ágil Academic Meeting / TaSAFO em fatos e fotosVisão Ágil Academic Meeting / TaSAFO em fatos e fotos
Visão Ágil Academic Meeting / TaSAFO em fatos e fotos
 
Compartilhando experiências em software livre
Compartilhando experiências em software livreCompartilhando experiências em software livre
Compartilhando experiências em software livre
 
BrOffice nas Universidades
BrOffice nas UniversidadesBrOffice nas Universidades
BrOffice nas Universidades
 

Zend Framework: abordagem prática

  • 3. ROTEIRO O padrão MVC ● Configurando o ZF ● Conhecendo o ZF ● Análise de situações comuns ● 3
  • 4. O PADRÃO MVC Adaptado de 4 betterexplained.com
  • 10. CONFIGURANDO O ZF http://framework.zend.com/download 10
  • 11. CONFIGURANDO O ZF Configurar esta pasta para a raiz do servidor web (DocumentRoot). 11
  • 12. CONFIGURANDO O ZF OBS: Necessário habilitar o  mod_rewrite para reescrita de URLs e  o suporte a arquivos .htaccess no  Apache, configurando­os de acordo  com o tutorial. 12
  • 13. /public/index.php <?php // Passo 1 define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application/')); set_include_path( APPLICATION_PATH . '/../library' . PATH_SEPARATOR . get_include_path() ); // Passo 2 require_once quot;Zend/Loader.phpquot;; Zend_Loader::registerAutoload(); (continua...) 13
  • 14. /public/index.php // Passo 3 try { require '../application/bootstrap.php'; } catch (Exception $exception) { echo '<html><body><center>' . 'Uma exceção ocorreu!.'; if (defined('APPLICATION_ENVIRONMENT') && APPLICATION_ENVIRONMENT != 'production' ){ echo '<br /><br />' . $exception->getMessage() . '<br />' . '<div align=quot;leftquot;>Stack Trace:' . '<pre>' . $exception->getTraceAsString() . '</pre></div>'; } echo '</center></body></html>'; exit(1); } // Passo 4 Zend_Controller_Front::getInstance()->dispatch(); 14
  • 15. /application/bootstrap.php <?php // Constante defined('APPLICATION_PATH') or define('APPLICATION_PATH', dirname(__FILE__)); // Tipo de ambiente defined('APPLICATION_ENVIRONMENT') or define('APPLICATION_ENVIRONMENT', 'development'); // Inicia os controllers $frontController = Zend_Controller_Front::getInstance(); // Onde estão nosso controllers $frontController->setControllerDirectory(APPLICATION_PATH . '/controllers'); // Repassa a constante aos controllers $frontController->setParam('env', APPLICATION_ENVIRONMENT); 15
  • 16. /application/bootstrap.php (continuação...) // Teremos layouts de site? Zend_Layout::startMvc(APPLICATION_PATH . '/layouts'); // Arquivo de configuração $configuration = new Zend_Config_Ini( APPLICATION_PATH . '/config.ini', APPLICATION_ENVIRONMENT ); // Registro $registry = Zend_Registry::getInstance(); $registry->configuration = $configuration; $registry->dbAdapter = $dbAdapter; // Limpa para encerrar unset($frontController); 16
  • 17. /application/controllers/IndexController.php <?php // application/controllers/IndexController.php class IndexController extends Zend_Controller_Action { public function indexAction() { } } /application/views/index/index.phtml <? // application/views/index/index.phtml ?> <h1 align=quot;centerquot;> Hello, Zend Framework MVC! </h1> 17
  • 18. /application/controllers/ErrorController.php <?php class ErrorController extends Zend_Controller_Action { public function errorAction() { $this->_helper->viewRenderer->setViewSuffix('phtml'); $errors = $this->_getParam('error_handler'); switch ($errors->type) { case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER: case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION: $this->getResponse()->setHttpResponseCode(404); $this->view->message = 'Página não encontrada.'; break; default: $this->getResponse()->setHttpResponseCode(500); $this->view->message = 'Application error'; break; 18 }
  • 19. /application/controllers/ErrorController.php (continuação...) $this->view->env = $this->getInvokeArg('env'); $this->view->exception = $errors->exception; $this->view->request = $errors->request; } } 19
  • 20. /application/views/error/error.phtml <h1>Ocorreu um erro!</h1> <h2><?= $this->message ?></h2> <? if ('development' == $this->env): ?> <h3>Exceção ocorrida:</h3> <p> <b>Menssagem:</b> <?= $this->exception->getMessage() ?> </p> <h3>Stack trace:</h3> <pre><?= $this->exception->getTraceAsString() ?></pre> <h3>Parâmetros da requisição:</h3> <pre><? var_dump($this->request->getParams()) ?></pre> <? endif ?> 20
  • 21. /application/layouts/layout.phtml <?= $this->doctype() ?> <html xmlns=quot;http://www.w3.org/1999/xhtmlquot;> <head> <meta http-equiv=quot;Content-Typequot; content=quot;text/html; charset=utf- 8quot; /> <title>ProjetoZF</title> <?= $this->headScript() ?> <?= $this->headLink()->appendStylesheet('/css/global.css') ?> </head> <body> <div id=”header”> <h1>Bem-vindo ao ProjetoZF!</h1> <a href=”<?= $this->url(array('controller'=> 'index', 'action'=> 'index')) ?>“>Página inicial</a> </div> <div id=”content”> <?= $this->layout()->content ?> </div> </body> </html> 21
  • 23. CONHECENDO O ZF MVC Zend_Db_Table ● Zend_Controller_Action ● Zend_View_Helper ● 23
  • 24. CONFIGURANDO O BANCO ;; /application/config.ini [producao] database.adapter = PDO_MYSQL database.params.host = dbserver.example.com database.params.username = username database.params.password = password database.params.dbname = dbname [teste : producao] database.params.dbname = dbname_test [desenv : producao] database.params.dbname = dbname_desenv database.params.host = dbtest.example.com 24
  • 26. PROGRAMANDO MODELS <?php class GenericModel extends Zend_Db_Table { // insere dados do array em campos homônimos public function insert(array $data) { $fields = $this ->info(Zend_Db_Table_Abstract::COLS); foreach ($data as $field => $value) if (!in_array($field, $fields)) unset($data[$field]); return parent::insert($data); } } 26
  • 28. PROGRAMANDO MODELS <?php requice_once APPLICATION_PATH . '/models/GenericModel.php'; class Post extends GenericModel { // lógica de negócio “blug do futuro” public function publicar($data) { $data['created']= date('Y-m-d', strtotime('now +7 days'); return parent::insert($data); } } 28
  • 30. ESCREVENDO CONTROLLERS <?php class PostController extends Zend_Controller_Action { // definir referência ao model protected $_Post; public function init() { // instanciar os models e outras operações require_once APPLICATION_PATH . '/models/Post.php'; $this->_Post= new Post(); } 30
  • 31. ESCREVENDO CONTROLLERS // (continuação...) // lista todos os posts e joga para a view public function indexAction() { $posts= $this->_Post->fetchAll(); $this->view->posts= $posts->toArray(); } // action para visualizar um dado post public function verAction() { $parms= $this->getRequest()->getParams(); $postid= $parms['id']; $post= $this->_Post->find($postid); $this->view->post= $post; } 31
  • 32. DEFININDO VIEWS <!-- /application/views/post/index.phtml --> <?php foreach($this->posts as $post): ?> <h2><a href=”<?php echo $this->url( array('controller'=> 'post' , 'action'=> 'ver' , 'id'=> $post['id'])); ?>”> <?php echo $post['titulo']; ?></a></h2> <h3>Publicado em: <?php echo $post['created']; ?></h3> <p><?php echo nl2br($post['texto']); ?></p> <?php endfor; ?> 32
  • 33. ANÁLISE DE SITUAÇÕES COMUNS EXIBIÇÃO DE MENSAGENS ● FILTROS E VALIDAÇÕES ● POPULANDO CAMPOS ● ASSOCIANDO MODELS ● AUTENTICAÇÃO E AUTORIZAÇÃO ● 33
  • 34. ANÁLISE DE SITUAÇÕES COMUNS EXIBIÇÃO DE MENSAGENS ● FILTROS E VALIDAÇÕES ● POPULANDO CAMPOS ● ASSOCIANDO MODELS ● AUTENTICAÇÃO E AUTORIZAÇÃO ● http://framework.zend.com/manual/en/ 34
  • 36. EXIBIÇÃO DE MENSAGENS <?php class GenericController extends Zend_Controller_Action { protected $_mess; protected $_redir; public function init() { $this->_mens= $this->_helper ->getHelper('FlashMessenger'); $this->_redir= $this->_helper ->getHelper('Redirector'); } 36
  • 37. EXIBIÇÃO DE MENSAGENS // (continuação...) protected function flash($msg, $to) { $this->_mess->addMessage($msg); $this->_redir->gotoUrl($to); exit; } public function postDispatch() { $this->view->messages= join(' ', $this ->_mess->getMessages()); parent::postDispatch(); } } 37
  • 38. EXIBIÇÃO DE MENSAGENS <?= $this->doctype() ?> <html xmlns=quot;http://www.w3.org/1999/xhtmlquot;> <head> <meta http-equiv=quot;Content-Typequot; content=quot;text/html; charset=utf- 8quot; /> <title>ProjetoZF</title> <?= $this->headScript() ?> <?= $this->headLink()->appendStylesheet('/css/global.css') ?> </head> <body> <div id=”header”> <h1>Bem-vindo ao ProjetoZF!</h1> <a href=”<?= $this->url(array('controller'=> 'index', 'action'=> 'index')) ?>“>Página inicial</a> </div> <div id=”messages”><?= $this->messages ?></div> <div id=”content”> <?= $this->layout()->content ?> </div> 38 </body> </html>
  • 40. FILTROS E VALIDAÇÕES // PostController.php public function novoAction() { $req= $this->getRequest(); if( $req->isPosted() ) { $data= $req->getParameters(); $this->_Post->insert($data); } } 40
  • 41. FILTROS E VALIDAÇÕES // PostController.php public function novoAction() { $req= $this->getRequest(); if( $req->isPosted() ) { $data= $req->getParameters(); $filters= array('*'=> 'StringTrim'); $validators= array('titulo'=>'Alpha'); $input= new Zend_Input_Filter($filters, $validators, $data); if( $input->isValid() ): $this->_Post->insert($input); $this->flash('Sucesso!', '/index'); 41 endif;
  • 43. POPULANDO CAMPOS <!-- /appplication/views/post/novo.phtml --> <?php echo $this->form('novoForm', array('method'=> 'post')); echo $this->formErrors(); ?> <fieldset><legend>Novo Post</legend> <?php echo $this->formLabel('titulo', 'Título:'); echo $this->formText('titulo'); echo $this->formLabel('texto', 'Texto:'); echo $this->formTextarea('texto', null, array('rows'=> 3, 'cols'=> 30)); echo $this->formSubmit('btnOk', 'Cadastrar'); ?> </fieldset></form> 43
  • 44. POPULANDO CAMPOS <!-- /appplication/views/post/novo.phtml --> <?php echo $this->form('novoForm', array('method'=> 'post')); echo $this->formErrors(); ?> <fieldset><legend>Novo Post</legend> <?php echo $this->formLabel('titulo', 'Título:'); echo $this->formText('titulo'); echo $this->formLabel('texto', 'Texto:'); echo $this->formTextarea('texto', null, array('rows'=> 3, 'cols'=> 30)); echo $this->formSelect('categoria_id', null, null, array('Dicas', 'Tutoriais', 'Artigos') ); echo $this->formSubmit('btnOk', 'Cadastrar'); ?> 44 </fieldset></form>
  • 45. POPULANDO CAMPOS // PostController.php public function novoAction() { $req= $this->getRequest(); $categorias= $this->_Post->findList(); $this->view->categorias= $categorias; if( $req->isPosted() ) { $data= $req->getParameters(); $filters= array('*'=> 'StringTrim'); $validators= array('title'=>'Alpha'); $input= new Zend_Input_Filter($filters, $validators, $data); 45
  • 46. POPULANDO CAMPOS // GenericModel.php public function fetchList($first= 'Selecione...', $id= 'id', $description= 'descricao', $where= null, $order= null, $count= null, $offset= null) { $fetchedOptions= $this->fetchAll($where, $order, $count, $offset); if( $first != null ): $listOptions[' ']= $first; endif; foreach( $fetchedOptions as $option ): $listOptions[$option[$id]]= $option[$description]; endforeach; return $listOptions; } 46
  • 47. POPULANDO CAMPOS <!-- /appplication/views/post/novo.phtml --> <?php echo $this->form('novoForm', array('method'=> 'post')); echo $this->formErrors(); ?> <fieldset><legend>Novo Post</legend> <?php echo $this->formLabel('titulo', 'Título:'); echo $this->formText('titulo'); echo $this->formLabel('texto', 'Texto:'); echo $this->formTextarea('texto', null, array('rows'=> 3, 'cols'=> 30)); echo $this->formSelect('categoria_id', null, null, $this->categorias ); echo $this->formSubmit('btnOk', 'Cadastrar'); ?> 47 </fieldset></form>
  • 49. ASSOCIANDO MODELS <?php requice_once APPLICATION_PATH . '/models/GenericModel.php'; class Post extends GenericModel { protected $_referenceMap= array( 'Categoria'=> array( 'columns' => 'categoria_id' , 'refTableClass'=> 'categoria' , 'refColumns' => 'id')); protected $_dependentTables= array('PostTag'); 49
  • 50. ASSOCIANDO MODELS <?php class PostController extends Zend_Controller_Action { // (...) // lista todos os posts e joga para a view public function indexAction() { $posts= $this->Post->fetchAll(); $this->view->posts= $posts; } 50
  • 51. ASSOCIANDO MODELS <!-- /application/views/post/index.phtml --> <?php foreach($this->posts as $post): ?> ... <h3>Publicado em: <?php echo $post->created; ?></h3> <?php $categoria= $post ->findDependentRowset('Categoria'); echo $categoria->descricao; ?> <p><?php echo nl2br($post->texto); ?></p> <?php endfor; ?> 51
  • 52. ASSOCIANDO MODELS <!-- /application/views/post/index.phtml --> <?php foreach($this->posts as $post): ?> ... <h3>Publicado em: <?php echo $post->created; ?></h3> <?php $categoria= $post ->findCategoriaByPost(); echo $categoria->descricao; ?> <p><?php echo nl2br($post->texto); ?></p> <?php endfor; ?> 52
  • 54. ASSOCIANDO MODELS <!-- /application/views/post/index.phtml --> <?php foreach($this->posts as $post): ?> ... <h3>Publicado em: <?php echo $post->created; ?></h3> <?php $tags= $post ->findManyToManyRowset('Tag', 'PostTag'); echo implode(', ', $tags->toArray()); ?> <p><?php echo nl2br($post->texto); ?></p> 54 <?php endfor; ?>
  • 56. AUTENTICAÇÃO E AUTORIZAÇÃO <?php requice_once APPLICATION_PATH . '/models/GenericController.php'; class AuthController extends GenericController { public function loginAction() { // como autenticar um usuário... $req= $this->getRequest(); if( $req->isPosted() ) { $parms= $req->getParams(); // método para validar campos login e senha $input= $this->__validate($parms); 56
  • 57. AUTENTICAÇÃO E AUTORIZAÇÃO // ... $db= Zend_Registry::get('dbAdapter'); $adap= new Zend_Auth_Adapter_DbTable($db); $adap->setTableName('usuario'); $adap->setIdentityColumn('login'); $adap->setCredentialColumn('senha'); $adap->setIdentity($input->usuario); $adap->setCredential(md5($input->senha)); $auth= Zend_Auth::getInstance(); $result= $auth->authenticate($auth); if( $result->isValid() ) // trata a autenticação... 57
  • 59. AUTENTICAÇÃO E AUTORIZAÇÃO AUTORIZAÇÃO recursos (resources) ● perfis (roles) ● 59
  • 60. AUTENTICAÇÃO E AUTORIZAÇÃO <?php require_once . APPLICATION_PATH . '/controllers/GenericController.php'; class PostController extends GenericController implements Zend_Acl_Resource_Interface { // definir referência ao model protected $_Post; public function getResourceId() { return 'POST'; } 60 // ...
  • 62. AUTENTICAÇÃO E AUTORIZAÇÃO // GenericController.php private function __configPerms() { // define perfis $chefe= new Zend_Acl_Role('chefe'); $escritor= new Zend_Acl_Role('escritor', $chefe); $this->_acl= new Zend_Acl(); $this->_acl->addRole($chefe); $this->_acl->addRole($escritor); // define recursos $this->_acl->add(new Zend_Acl_Resource('POST')); // define as permissões $this->_acl->allow('chefe', 'POST', null); $this->_acl->deny('escritor', 'POST', 'novo');62
  • 63. AUTENTICAÇÃO E AUTORIZAÇÃO // GenericController public function preDispatch() { // recuperar o usuário autenticado... $usuario= $this->__obterUsuarioAutenticado(); $req= $this->getRequest(); if($this->_acl->isAllowed($usuario->perfil, strtoupper($req->getControllerName()), $req ->getActionName())) // trata a autorização... 63
  • 64. 64
  • 66.   MUITO OBRIGADO! MARCELO DE FREITAS ANDRADE Especialista em Desenv. de Aplicações para Internet mfandrade@gmail.com  66