More Related Content More from Marcelo Andrade (10) Zend Framework: abordagem prática3. ROTEIRO
O padrão MVC
●
Configurando o ZF
●
Conhecendo o ZF
●
Análise de situações comuns
●
3
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, configurandoos 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
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
}
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
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>
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
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
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
66.
MUITO OBRIGADO!
MARCELO DE FREITAS ANDRADE
Especialista em Desenv. de Aplicações para Internet
mfandrade@gmail.com 66