Aplicações PHP 5.4 com
componentes Aura
Flávio Gomes da Silva Lisboa
@fgsl
Quem sou eu?
Quem sou eu?
Quem sou eu?
Quem sou eu?
Quem sou eu?

2008

Zend Framework 1

Zend Framework 2
Quem sou eu?
http://romocavaleirodoespaco.blogspot.com.br
VAMOS COMEÇAR?
O projeto Aura

Código limpo;
●Bibliotecas fracamente acopladas;
●Pacotes independentes;
●Em conformidade com os padrões
PHP-FIG.
●
Código limpo
“Eu gosto que meu código seja elegante e eficiente. A
lógica deve ser simples para que fique mais difícil para
os bugs se esconder, as dependências devem ser
mínimas para que haja facilidade de manutenção, o
tratamento de erros deve estar completamente de
acordo com uma estratégia articulada, e o
desempenho deve estar próximo ao ideal de modo a
não tentar as pessoas a tornar o código confuso com
otimizações sem fundamento. Código limpo faz algo bem
feito.”
Quem disse isso?
Código limpo

Bjarne Stroustrup, criador do C++
Fraco acoplamento
Padrões
“Eu penso em padrões como algo que pode ajudar
pessoas a pensarem de modo orientado a objetos”
Erich Gamma
O caso de uso
●

Um cadastro de alunos.

●

Matrícula e nome.

●

Inclusão, alteração, exclusão e recuperação.

●

Apache + PHP + MySQL
Sugestão: XAMPP

http://www.apachefriends.org/pt_br/xampp.html
Ambiente de desenvolvimento

http://www.zend.com/en/company/community/pdt/downloads
Ambiente de desenvolvimento
Ambiente de desenvolvimento
Instalando o Composer
php -r
"eval('?>'.file_get_contents('https://getcomposer.org/installer'));"

No webroot...
Criando um projeto Aura com Composer
Criando um projeto Aura com Composer
Criando um projeto Aura com Composer
Abrindo o projeto
Abrindo o projeto
Estrutura do projeto
Estrutura do projeto
Estrutura do projeto
Estrutura do projeto
Redirecionando

escola-aura.htaccess
RewriteEngine on
RewriteRule .* web/index.php
Criando o controlador
Criando o controlador
Criando o controlador

<?php
namespace EscolaPackageWebHome;
use AuraFrameworkWebControllerAbstractPage;
class HomePage extends AbstractPage {
public function actionIndex()
{
$this->view = 'index';
}
}
Criando a visão
Criando a visão

<h1>Cadastro de Alunos</h1>
Configurando a rota
<?php
/**
*
* Overrides for 'default' config mode.
*
* @var AuraFrameworkSystem $system Aura system directories; when cast to
* a string, the Aura system root directory.
*
* @var AuraAutoloadLoader $loader The autoloader for the system.
*
* @var AuraDiContainer $di The DI container for the system.
*
*/
// attach the path for a route named 'home' to the controller and action
$di->params ['AuraRouterMap'] ['attach'] [''] = [
// all routes with the '' path prefix (i.e., no prefix)
'routes' => [
// a route named 'home'
'home' => [
'path' => '/escola-aura/',
'values' => [
'controller' => 'home',
'action' => 'index'
]
]
]
];
// map the 'home' controller value to the controller class
$di->params ['AuraFrameworkWebControllerFactory'] ['map'] ['home'] =
'EscolaPackageWebHomeHomePage';
?>
Nosso alô mundo
http://localhost/escola-aura/

Cadastro de Alunos
Criando um layout único
/escola-aura/include/Escola/Package/Web/Home/views/layout.php

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Escola Aura</title>
</head>
<body>
<h1>Cadastro de Alunos</h1>
<?php include $this->find($this->content)?>
</body>
</html>
Criando um layout único
/escola-aura/include/Escola/Package/Web/Home/views/index.php

<a href="<?php echo $this->url?>">Incluir aluno</a>
Gerando rotas

public function actionIndex()
{
$this->view = 'layout';
$this->data = [
'content' => 'index',
'url' => $this->router->generate('edit')
];
}
Definindo rotas
/escola-aura/config/default.php

// a route named 'edit'
'edit' => [
'path' => '/escola-aura/edit/{:matricula}',
'values' => [
'controller' => 'home',
'action' => 'edit',
'matricula' => 0
],
'params' => [
'matricula' => '(d+)'
]
],
Controle de edição

public function actionEdit()
{
$this->view = 'layout';
$this->data = [
'content' => 'edit',
'action' => $this->router->generate('save')
];
}
Visão de edição
/escola-aura/include/Escola/Package/Web/Home/views/edit.php

<form action="<?php echo $this->action?>" method="post">
Nome: <input type="text" name="nome"
autofocus="autofocus">
<input type="hidden" name="matricula">
<input type="submit" value="gravar">
</form>
Nossa tabela

Banco de dados "escola-aura"

CREATE TABLE IF NOT EXISTS `alunos` (
`matricula` int(11) NOT NULL AUTO_INCREMENT,
`nome` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`matricula`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
Definição de rota de inclusão
/escola-aura/config/default.php

// a route named 'save'
'save' => [
'path' => '/escola-aura/save',
'values' => [
'controller' => 'home',
'action' => 'save'
]
],
Ação de inclusão

public function actionSave()
{
$connection = $GLOBALS['di']->get('database');
$connection->connect();
$insert = $connection->newInsert();
$insert->into('alunos')
->cols(['nome']);
$bind = ['nome'=> $this->getContext()->getPost('nome')];
$stmt =
}

$connection->query($insert, $bind);

$this->response->setRedirect($this->router->generate('home'));
Conexão com banco de dados
/escola-aura/config/default.php
$di->set('database',function(){
$connection_factory = include realpath(__DIR__ . '/../package/Aura.Sql/scripts')
. DIRECTORY_SEPARATOR . 'instance.php';;
$connection = $connection_factory->newInstance(
// adapter name
'mysql',
// DSN elements for PDO; this can also be
// an array of key-value pairs
'host=localhost;dbname=escola-aura',
// username for the connection
'root',
// password for the connection
'xampp'
);
return $connection;
});
$GLOBALS['di'] = $di;
Listagem de registros
/escola-aura/include/Escola/Package/Web/Home/HomePage.php
public function actionIndex()
{
$connection = $GLOBALS['di']->get('database');
$connection->connect();
$select = $connection->newSelect();
$select->cols(['*'])
->from('alunos');

}

$this->view = 'layout';
$this->data = [
'content' => 'index',
'url' => $this->router->generate('edit'),
'list' => $connection->fetchAll($select)
];
Listagem de registros
/escola-aura/include/Escola/Package/Web/Home/views/index.php

<a href="<?php echo $this->url?>">Incluir aluno</a>
<table>
<thead>
<tr>
<th>Matrícula</th>
<th>Nome</th>
</tr>
</thead>
<?php
foreach ($this->list as $item):
?>
<tr>
<td><?=$item['matricula']?></td>
<td><?=$item['nome']?></td>
</tr>
<?php
endforeach;
?>
</table>
Listagem de registros
Geração de rota de alteração
/escola-aura/include/Escola/Package/Web/Home/views/index.php
<a href="<?php echo $this->url?>">Incluir aluno</a>
<table>
<thead>
<tr>
<th>Matrícula</th>
<th>Nome</th>
<th colspan="2">&nbsp;</th>
</tr>
</thead>
<?php
foreach ($this->list as $item):
?>
<tr>
<td><?=$item['matricula']?></td>
<td><?=$item['nome']?></td>
<td><a href="<?=$this->route('edit', ['matricula' => $item['matricula']])?
>">alterar</a></td>
</tr>
<?php
endforeach;
?>
</table>
Ação de alteração
/escola-aura/include/Escola/Package/Web/Home/HomePage.php
public function actionEdit()
{
$aluno = [
'matricula' => 0,
'nome' => ''
];
if ($matricula = $this->getParams()['matricula'])
{
$connection = $GLOBALS['di']->get('database');
$connection->connect();
$select = $connection->newSelect();
$select->cols(['*'])
->from('alunos')
->where('matricula = :matricula');
$aluno = $connection->fetchOne($select,['matricula' => $matricula]);
}
$this->view = 'layout';
$this->data = [
'aluno' => $aluno,
'content' => 'edit',
'action' => $this->router->generate('save')
];
}
Ação de gravação
/escola-aura/include/Escola/Package/Web/Home/HomePage.php
public function actionSave()
{
$connection = $GLOBALS['di']->get('database');
$connection->connect();
$matricula = $this->getContext()->getPost('matricula',0);
if ($matricula == 0)
{
$verb = $connection->newInsert();
$verb->into('alunos')
->cols(['nome']);
$bind = ['nome'=> $this->getContext()->getPost('nome')];
}
else
{

$verb = $connection->newUpdate();
$verb->table('alunos')
->set('nome',':nome')
->where('matricula = :matricula');
$nome = $this->getContext()->getPost('nome');
$bind = ['matricula' => $matricula, 'nome' => $nome];

}
$stmt =
}

$connection->query($verb, $bind);

$this->response->setRedirect($this->router->generate('home'));
Definição de rota de exclusão
/escola-aura/config/default.php

// a route named 'delete'
'delete' => [
'path' => '/escola-aura/delete/{:matricula}',
'values' => [
'controller' => 'home',
'action' => 'delete',
'matricula' => 0
],
'params' => [
'matricula' => '(d+)'
]
]
Geração de rota de exclusão
/escola-aura/include/Escola/Package/Web/Home/views/index.php
<a href="<?php echo $this->url?>">Incluir aluno</a>
<table>
<thead>
<tr>
<th>Matrícula</th>
<th>Nome</th>
<th colspan="2">&nbsp;</th>
</tr>
</thead>
<?php
foreach ($this->list as $item):
?>
<tr>
<td><?=$item['matricula']?></td>
<td><?=$item['nome']?></td>
<td><a href="<?=$this->route('edit', ['matricula' => $item['matricula']])?
>">alterar</a></td>
<td><a href="<?=$this->route('delete', ['matricula' => $item['matricula']])?
>">excluir</a></td>
</tr>
<?php
endforeach;
?>
</table>
Ação de exclusão
/escola-aura/include/Escola/Package/Web/Home/HomePage.php
public function actionDelete()
{
$matricula = $this->getParams()['matricula'];
if ($matricula > 0)
{
$connection = $GLOBALS['di']->get('database');
$connection->connect();
$delete = $connection->newDelete();
$delete->from('alunos')
->where('matricula = :matricula');
$bind = ['matricula' => $matricula];
}
}

$connection->query($delete,$bind);

$this->response->setRedirect($this->router->generate('home'));
Você pode ainda...
●

Definir regras para entrada de dados

●

Criar formulários programaticamente

●

Gerenciar a sessão com objetos
Perguntas?
Obrigado!
Aplicações PHP 5.4 com
componentes Aura
Flávio Gomes da Silva Lisboa
@fgsl
Quem sou eu?
Quem sou eu?
Quem sou eu?
Quem sou eu?
Quem sou eu?

2008

Zend Framework 1

Zend Framework 2
Quem sou eu?
http://romocavaleirodoespaco.blogspot.com.br
VAMOS COMEÇAR?
O projeto Aura

Código limpo;
●Bibliotecas fracamente acopladas;
●Pacotes independentes;
●Em conformidade com os padrões
PHP-FIG.
●
Código limpo
“Eu gosto que meu código seja elegante e eficiente. A
lógica deve ser simples para que fique mais difícil para
os bugs se esconder, as dependências devem ser
mínimas para que haja facilidade de manutenção, o
tratamento de erros deve estar completamente de
acordo com uma estratégia articulada, e o
desempenho deve estar próximo ao ideal de modo a
não tentar as pessoas a tornar o código confuso com
otimizações sem fundamento. Código limpo faz algo bem
feito.”
Quem disse isso?
Código limpo

Bjarne Stroustrup, criador do C++
Fraco acoplamento
Padrões
“Eu penso em padrões como algo que pode ajudar
pessoas a pensarem de modo orientado a objetos”
Erich Gamma
O caso de uso
●

Um cadastro de alunos.

●

Matrícula e nome.

●

Inclusão, alteração, exclusão e recuperação.

●

Apache + PHP + MySQL
Sugestão: XAMPP

http://www.apachefriends.org/pt_br/xampp.html
Ambiente de desenvolvimento

http://www.zend.com/en/company/community/pdt/downloads
Ambiente de desenvolvimento
Ambiente de desenvolvimento
Instalando o Composer
php -r
"eval('?>'.file_get_contents('https://getcomposer.org/installer'));"

No webroot...
Criando um projeto Aura com Composer
Criando um projeto Aura com Composer
Criando um projeto Aura com Composer
Abrindo o projeto
Abrindo o projeto
Estrutura do projeto
Estrutura do projeto
Estrutura do projeto
Estrutura do projeto
Redirecionando

escola-aura.htaccess
RewriteEngine on
RewriteRule .* web/index.php
Criando o controlador
Criando o controlador
Criando o controlador

<?php
namespace EscolaPackageWebHome;
use AuraFrameworkWebControllerAbstractPage;
class HomePage extends AbstractPage {
public function actionIndex()
{
$this->view = 'index';
}
}
Criando a visão
Criando a visão

<h1>Cadastro de Alunos</h1>
Configurando a rota
<?php
/**
*
* Overrides for 'default' config mode.
*
* @var AuraFrameworkSystem $system Aura system directories; when cast to
* a string, the Aura system root directory.
*
* @var AuraAutoloadLoader $loader The autoloader for the system.
*
* @var AuraDiContainer $di The DI container for the system.
*
*/
// attach the path for a route named 'home' to the controller and action
$di->params ['AuraRouterMap'] ['attach'] [''] = [
// all routes with the '' path prefix (i.e., no prefix)
'routes' => [
// a route named 'home'
'home' => [
'path' => '/escola-aura/',
'values' => [
'controller' => 'home',
'action' => 'index'
]
]
]
];
// map the 'home' controller value to the controller class
$di->params ['AuraFrameworkWebControllerFactory'] ['map'] ['home'] =
'EscolaPackageWebHomeHomePage';
?>
Nosso alô mundo
http://localhost/escola-aura/

Cadastro de Alunos
Criando um layout único
/escola-aura/include/Escola/Package/Web/Home/views/layout.php

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Escola Aura</title>
</head>
<body>
<h1>Cadastro de Alunos</h1>
<?php include $this->find($this->content)?>
</body>
</html>
Criando um layout único
/escola-aura/include/Escola/Package/Web/Home/views/index.php

<a href="<?php echo $this->url?>">Incluir aluno</a>
Gerando rotas

public function actionIndex()
{
$this->view = 'layout';
$this->data = [
'content' => 'index',
'url' => $this->router->generate('edit')
];
}
Definindo rotas
/escola-aura/config/default.php

// a route named 'edit'
'edit' => [
'path' => '/escola-aura/edit/{:matricula}',
'values' => [
'controller' => 'home',
'action' => 'edit',
'matricula' => 0
],
'params' => [
'matricula' => '(d+)'
]
],
Controle de edição

public function actionEdit()
{
$this->view = 'layout';
$this->data = [
'content' => 'edit',
'action' => $this->router->generate('save')
];
}
Visão de edição
/escola-aura/include/Escola/Package/Web/Home/views/edit.php

<form action="<?php echo $this->action?>" method="post">
Nome: <input type="text" name="nome"
autofocus="autofocus">
<input type="hidden" name="matricula">
<input type="submit" value="gravar">
</form>
Nossa tabela

Banco de dados "escola-aura"

CREATE TABLE IF NOT EXISTS `alunos` (
`matricula` int(11) NOT NULL AUTO_INCREMENT,
`nome` varchar(30) COLLATE utf8_unicode_ci NOT NULL,
PRIMARY KEY (`matricula`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
Definição de rota de inclusão
/escola-aura/config/default.php

// a route named 'save'
'save' => [
'path' => '/escola-aura/save',
'values' => [
'controller' => 'home',
'action' => 'save'
]
],
Ação de inclusão

public function actionSave()
{
$connection = $GLOBALS['di']->get('database');
$connection->connect();
$insert = $connection->newInsert();
$insert->into('alunos')
->cols(['nome']);
$bind = ['nome'=> $this->getContext()->getPost('nome')];
$stmt =
}

$connection->query($insert, $bind);

$this->response->setRedirect($this->router->generate('home'));
Conexão com banco de dados
/escola-aura/config/default.php
$di->set('database',function(){
$connection_factory = include realpath(__DIR__ . '/../package/Aura.Sql/scripts')
. DIRECTORY_SEPARATOR . 'instance.php';;
$connection = $connection_factory->newInstance(
// adapter name
'mysql',
// DSN elements for PDO; this can also be
// an array of key-value pairs
'host=localhost;dbname=escola-aura',
// username for the connection
'root',
// password for the connection
'xampp'
);
return $connection;
});
$GLOBALS['di'] = $di;
Listagem de registros
/escola-aura/include/Escola/Package/Web/Home/HomePage.php
public function actionIndex()
{
$connection = $GLOBALS['di']->get('database');
$connection->connect();
$select = $connection->newSelect();
$select->cols(['*'])
->from('alunos');

}

$this->view = 'layout';
$this->data = [
'content' => 'index',
'url' => $this->router->generate('edit'),
'list' => $connection->fetchAll($select)
];
Listagem de registros
/escola-aura/include/Escola/Package/Web/Home/views/index.php

<a href="<?php echo $this->url?>">Incluir aluno</a>
<table>
<thead>
<tr>
<th>Matrícula</th>
<th>Nome</th>
</tr>
</thead>
<?php
foreach ($this->list as $item):
?>
<tr>
<td><?=$item['matricula']?></td>
<td><?=$item['nome']?></td>
</tr>
<?php
endforeach;
?>
</table>
Listagem de registros
Geração de rota de alteração
/escola-aura/include/Escola/Package/Web/Home/views/index.php
<a href="<?php echo $this->url?>">Incluir aluno</a>
<table>
<thead>
<tr>
<th>Matrícula</th>
<th>Nome</th>
<th colspan="2">&nbsp;</th>
</tr>
</thead>
<?php
foreach ($this->list as $item):
?>
<tr>
<td><?=$item['matricula']?></td>
<td><?=$item['nome']?></td>
<td><a href="<?=$this->route('edit', ['matricula' => $item['matricula']])?
>">alterar</a></td>
</tr>
<?php
endforeach;
?>
</table>
Ação de alteração
/escola-aura/include/Escola/Package/Web/Home/HomePage.php
public function actionEdit()
{
$aluno = [
'matricula' => 0,
'nome' => ''
];
if ($matricula = $this->getParams()['matricula'])
{
$connection = $GLOBALS['di']->get('database');
$connection->connect();
$select = $connection->newSelect();
$select->cols(['*'])
->from('alunos')
->where('matricula = :matricula');
$aluno = $connection->fetchOne($select,['matricula' => $matricula]);
}
$this->view = 'layout';
$this->data = [
'aluno' => $aluno,
'content' => 'edit',
'action' => $this->router->generate('save')
];
}
Ação de gravação
/escola-aura/include/Escola/Package/Web/Home/HomePage.php
public function actionSave()
{
$connection = $GLOBALS['di']->get('database');
$connection->connect();
$matricula = $this->getContext()->getPost('matricula',0);
if ($matricula == 0)
{
$verb = $connection->newInsert();
$verb->into('alunos')
->cols(['nome']);
$bind = ['nome'=> $this->getContext()->getPost('nome')];
}
else
{

$verb = $connection->newUpdate();
$verb->table('alunos')
->set('nome',':nome')
->where('matricula = :matricula');
$nome = $this->getContext()->getPost('nome');
$bind = ['matricula' => $matricula, 'nome' => $nome];

}
$stmt =

$connection->query($verb, $bind);

$this->response->setRedirect($this->router->generate('home'));
}
Definição de rota de exclusão
/escola-aura/config/default.php

// a route named 'delete'
'delete' => [
'path' => '/escola-aura/delete/{:matricula}',
'values' => [
'controller' => 'home',
'action' => 'delete',
'matricula' => 0
],
'params' => [
'matricula' => '(d+)'
]
]
Geração de rota de exclusão
/escola-aura/include/Escola/Package/Web/Home/views/index.php
<a href="<?php echo $this->url?>">Incluir aluno</a>
<table>
<thead>
<tr>
<th>Matrícula</th>
<th>Nome</th>
<th colspan="2">&nbsp;</th>
</tr>
</thead>
<?php
foreach ($this->list as $item):
?>
<tr>
<td><?=$item['matricula']?></td>
<td><?=$item['nome']?></td>
<td><a href="<?=$this->route('edit', ['matricula' => $item['matricula']])?
>">alterar</a></td>
<td><a href="<?=$this->route('delete', ['matricula' => $item['matricula']])?
>">excluir</a></td>
</tr>
<?php
endforeach;
?>
</table>
Ação de exclusão
/escola-aura/include/Escola/Package/Web/Home/HomePage.php
public function actionDelete()
{
$matricula = $this->getParams()['matricula'];
if ($matricula > 0)
{
$connection = $GLOBALS['di']->get('database');
$connection->connect();
$delete = $connection->newDelete();
$delete->from('alunos')
->where('matricula = :matricula');
$bind = ['matricula' => $matricula];
}
}

$connection->query($delete,$bind);

$this->response->setRedirect($this->router->generate('home'));
Você pode ainda...
●

Definir regras para entrada de dados

●

Criar formulários programaticamente

●

Gerenciar a sessão com objetos
Perguntas?
Obrigado!

PHP Conference Brasil 2013 - Aplicações PHP 5.4 com componentes Aura

  • 1.
    Aplicações PHP 5.4com componentes Aura Flávio Gomes da Silva Lisboa @fgsl
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
    Quem sou eu? 2008 ZendFramework 1 Zend Framework 2
  • 7.
  • 8.
  • 9.
    O projeto Aura Códigolimpo; ●Bibliotecas fracamente acopladas; ●Pacotes independentes; ●Em conformidade com os padrões PHP-FIG. ●
  • 10.
    Código limpo “Eu gostoque meu código seja elegante e eficiente. A lógica deve ser simples para que fique mais difícil para os bugs se esconder, as dependências devem ser mínimas para que haja facilidade de manutenção, o tratamento de erros deve estar completamente de acordo com uma estratégia articulada, e o desempenho deve estar próximo ao ideal de modo a não tentar as pessoas a tornar o código confuso com otimizações sem fundamento. Código limpo faz algo bem feito.” Quem disse isso?
  • 11.
  • 12.
  • 13.
    Padrões “Eu penso empadrões como algo que pode ajudar pessoas a pensarem de modo orientado a objetos” Erich Gamma
  • 14.
    O caso deuso ● Um cadastro de alunos. ● Matrícula e nome. ● Inclusão, alteração, exclusão e recuperação. ● Apache + PHP + MySQL
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
    Instalando o Composer php-r "eval('?>'.file_get_contents('https://getcomposer.org/installer'));" No webroot...
  • 20.
    Criando um projetoAura com Composer
  • 21.
    Criando um projetoAura com Composer
  • 22.
    Criando um projetoAura com Composer
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
    Criando o controlador <?php namespaceEscolaPackageWebHome; use AuraFrameworkWebControllerAbstractPage; class HomePage extends AbstractPage { public function actionIndex() { $this->view = 'index'; } }
  • 33.
  • 34.
  • 35.
    Configurando a rota <?php /** * *Overrides for 'default' config mode. * * @var AuraFrameworkSystem $system Aura system directories; when cast to * a string, the Aura system root directory. * * @var AuraAutoloadLoader $loader The autoloader for the system. * * @var AuraDiContainer $di The DI container for the system. * */ // attach the path for a route named 'home' to the controller and action $di->params ['AuraRouterMap'] ['attach'] [''] = [ // all routes with the '' path prefix (i.e., no prefix) 'routes' => [ // a route named 'home' 'home' => [ 'path' => '/escola-aura/', 'values' => [ 'controller' => 'home', 'action' => 'index' ] ] ] ]; // map the 'home' controller value to the controller class $di->params ['AuraFrameworkWebControllerFactory'] ['map'] ['home'] = 'EscolaPackageWebHomeHomePage'; ?>
  • 36.
  • 37.
    Criando um layoutúnico /escola-aura/include/Escola/Package/Web/Home/views/layout.php <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Escola Aura</title> </head> <body> <h1>Cadastro de Alunos</h1> <?php include $this->find($this->content)?> </body> </html>
  • 38.
    Criando um layoutúnico /escola-aura/include/Escola/Package/Web/Home/views/index.php <a href="<?php echo $this->url?>">Incluir aluno</a>
  • 39.
    Gerando rotas public functionactionIndex() { $this->view = 'layout'; $this->data = [ 'content' => 'index', 'url' => $this->router->generate('edit') ]; }
  • 40.
    Definindo rotas /escola-aura/config/default.php // aroute named 'edit' 'edit' => [ 'path' => '/escola-aura/edit/{:matricula}', 'values' => [ 'controller' => 'home', 'action' => 'edit', 'matricula' => 0 ], 'params' => [ 'matricula' => '(d+)' ] ],
  • 41.
    Controle de edição publicfunction actionEdit() { $this->view = 'layout'; $this->data = [ 'content' => 'edit', 'action' => $this->router->generate('save') ]; }
  • 42.
    Visão de edição /escola-aura/include/Escola/Package/Web/Home/views/edit.php <formaction="<?php echo $this->action?>" method="post"> Nome: <input type="text" name="nome" autofocus="autofocus"> <input type="hidden" name="matricula"> <input type="submit" value="gravar"> </form>
  • 43.
    Nossa tabela Banco dedados "escola-aura" CREATE TABLE IF NOT EXISTS `alunos` ( `matricula` int(11) NOT NULL AUTO_INCREMENT, `nome` varchar(30) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`matricula`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
  • 44.
    Definição de rotade inclusão /escola-aura/config/default.php // a route named 'save' 'save' => [ 'path' => '/escola-aura/save', 'values' => [ 'controller' => 'home', 'action' => 'save' ] ],
  • 45.
    Ação de inclusão publicfunction actionSave() { $connection = $GLOBALS['di']->get('database'); $connection->connect(); $insert = $connection->newInsert(); $insert->into('alunos') ->cols(['nome']); $bind = ['nome'=> $this->getContext()->getPost('nome')]; $stmt = } $connection->query($insert, $bind); $this->response->setRedirect($this->router->generate('home'));
  • 46.
    Conexão com bancode dados /escola-aura/config/default.php $di->set('database',function(){ $connection_factory = include realpath(__DIR__ . '/../package/Aura.Sql/scripts') . DIRECTORY_SEPARATOR . 'instance.php';; $connection = $connection_factory->newInstance( // adapter name 'mysql', // DSN elements for PDO; this can also be // an array of key-value pairs 'host=localhost;dbname=escola-aura', // username for the connection 'root', // password for the connection 'xampp' ); return $connection; }); $GLOBALS['di'] = $di;
  • 47.
    Listagem de registros /escola-aura/include/Escola/Package/Web/Home/HomePage.php publicfunction actionIndex() { $connection = $GLOBALS['di']->get('database'); $connection->connect(); $select = $connection->newSelect(); $select->cols(['*']) ->from('alunos'); } $this->view = 'layout'; $this->data = [ 'content' => 'index', 'url' => $this->router->generate('edit'), 'list' => $connection->fetchAll($select) ];
  • 48.
    Listagem de registros /escola-aura/include/Escola/Package/Web/Home/views/index.php <ahref="<?php echo $this->url?>">Incluir aluno</a> <table> <thead> <tr> <th>Matrícula</th> <th>Nome</th> </tr> </thead> <?php foreach ($this->list as $item): ?> <tr> <td><?=$item['matricula']?></td> <td><?=$item['nome']?></td> </tr> <?php endforeach; ?> </table>
  • 49.
  • 50.
    Geração de rotade alteração /escola-aura/include/Escola/Package/Web/Home/views/index.php <a href="<?php echo $this->url?>">Incluir aluno</a> <table> <thead> <tr> <th>Matrícula</th> <th>Nome</th> <th colspan="2">&nbsp;</th> </tr> </thead> <?php foreach ($this->list as $item): ?> <tr> <td><?=$item['matricula']?></td> <td><?=$item['nome']?></td> <td><a href="<?=$this->route('edit', ['matricula' => $item['matricula']])? >">alterar</a></td> </tr> <?php endforeach; ?> </table>
  • 51.
    Ação de alteração /escola-aura/include/Escola/Package/Web/Home/HomePage.php publicfunction actionEdit() { $aluno = [ 'matricula' => 0, 'nome' => '' ]; if ($matricula = $this->getParams()['matricula']) { $connection = $GLOBALS['di']->get('database'); $connection->connect(); $select = $connection->newSelect(); $select->cols(['*']) ->from('alunos') ->where('matricula = :matricula'); $aluno = $connection->fetchOne($select,['matricula' => $matricula]); } $this->view = 'layout'; $this->data = [ 'aluno' => $aluno, 'content' => 'edit', 'action' => $this->router->generate('save') ]; }
  • 52.
    Ação de gravação /escola-aura/include/Escola/Package/Web/Home/HomePage.php publicfunction actionSave() { $connection = $GLOBALS['di']->get('database'); $connection->connect(); $matricula = $this->getContext()->getPost('matricula',0); if ($matricula == 0) { $verb = $connection->newInsert(); $verb->into('alunos') ->cols(['nome']); $bind = ['nome'=> $this->getContext()->getPost('nome')]; } else { $verb = $connection->newUpdate(); $verb->table('alunos') ->set('nome',':nome') ->where('matricula = :matricula'); $nome = $this->getContext()->getPost('nome'); $bind = ['matricula' => $matricula, 'nome' => $nome]; } $stmt = } $connection->query($verb, $bind); $this->response->setRedirect($this->router->generate('home'));
  • 53.
    Definição de rotade exclusão /escola-aura/config/default.php // a route named 'delete' 'delete' => [ 'path' => '/escola-aura/delete/{:matricula}', 'values' => [ 'controller' => 'home', 'action' => 'delete', 'matricula' => 0 ], 'params' => [ 'matricula' => '(d+)' ] ]
  • 54.
    Geração de rotade exclusão /escola-aura/include/Escola/Package/Web/Home/views/index.php <a href="<?php echo $this->url?>">Incluir aluno</a> <table> <thead> <tr> <th>Matrícula</th> <th>Nome</th> <th colspan="2">&nbsp;</th> </tr> </thead> <?php foreach ($this->list as $item): ?> <tr> <td><?=$item['matricula']?></td> <td><?=$item['nome']?></td> <td><a href="<?=$this->route('edit', ['matricula' => $item['matricula']])? >">alterar</a></td> <td><a href="<?=$this->route('delete', ['matricula' => $item['matricula']])? >">excluir</a></td> </tr> <?php endforeach; ?> </table>
  • 55.
    Ação de exclusão /escola-aura/include/Escola/Package/Web/Home/HomePage.php publicfunction actionDelete() { $matricula = $this->getParams()['matricula']; if ($matricula > 0) { $connection = $GLOBALS['di']->get('database'); $connection->connect(); $delete = $connection->newDelete(); $delete->from('alunos') ->where('matricula = :matricula'); $bind = ['matricula' => $matricula]; } } $connection->query($delete,$bind); $this->response->setRedirect($this->router->generate('home'));
  • 56.
    Você pode ainda... ● Definirregras para entrada de dados ● Criar formulários programaticamente ● Gerenciar a sessão com objetos
  • 57.
  • 58.
  • 59.
    Aplicações PHP 5.4com componentes Aura Flávio Gomes da Silva Lisboa @fgsl
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
    Quem sou eu? 2008 ZendFramework 1 Zend Framework 2
  • 65.
  • 66.
  • 67.
    O projeto Aura Códigolimpo; ●Bibliotecas fracamente acopladas; ●Pacotes independentes; ●Em conformidade com os padrões PHP-FIG. ●
  • 68.
    Código limpo “Eu gostoque meu código seja elegante e eficiente. A lógica deve ser simples para que fique mais difícil para os bugs se esconder, as dependências devem ser mínimas para que haja facilidade de manutenção, o tratamento de erros deve estar completamente de acordo com uma estratégia articulada, e o desempenho deve estar próximo ao ideal de modo a não tentar as pessoas a tornar o código confuso com otimizações sem fundamento. Código limpo faz algo bem feito.” Quem disse isso?
  • 69.
  • 70.
  • 71.
    Padrões “Eu penso empadrões como algo que pode ajudar pessoas a pensarem de modo orientado a objetos” Erich Gamma
  • 72.
    O caso deuso ● Um cadastro de alunos. ● Matrícula e nome. ● Inclusão, alteração, exclusão e recuperação. ● Apache + PHP + MySQL
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
    Instalando o Composer php-r "eval('?>'.file_get_contents('https://getcomposer.org/installer'));" No webroot...
  • 78.
    Criando um projetoAura com Composer
  • 79.
    Criando um projetoAura com Composer
  • 80.
    Criando um projetoAura com Composer
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
    Criando o controlador <?php namespaceEscolaPackageWebHome; use AuraFrameworkWebControllerAbstractPage; class HomePage extends AbstractPage { public function actionIndex() { $this->view = 'index'; } }
  • 91.
  • 92.
  • 93.
    Configurando a rota <?php /** * *Overrides for 'default' config mode. * * @var AuraFrameworkSystem $system Aura system directories; when cast to * a string, the Aura system root directory. * * @var AuraAutoloadLoader $loader The autoloader for the system. * * @var AuraDiContainer $di The DI container for the system. * */ // attach the path for a route named 'home' to the controller and action $di->params ['AuraRouterMap'] ['attach'] [''] = [ // all routes with the '' path prefix (i.e., no prefix) 'routes' => [ // a route named 'home' 'home' => [ 'path' => '/escola-aura/', 'values' => [ 'controller' => 'home', 'action' => 'index' ] ] ] ]; // map the 'home' controller value to the controller class $di->params ['AuraFrameworkWebControllerFactory'] ['map'] ['home'] = 'EscolaPackageWebHomeHomePage'; ?>
  • 94.
  • 95.
    Criando um layoutúnico /escola-aura/include/Escola/Package/Web/Home/views/layout.php <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Escola Aura</title> </head> <body> <h1>Cadastro de Alunos</h1> <?php include $this->find($this->content)?> </body> </html>
  • 96.
    Criando um layoutúnico /escola-aura/include/Escola/Package/Web/Home/views/index.php <a href="<?php echo $this->url?>">Incluir aluno</a>
  • 97.
    Gerando rotas public functionactionIndex() { $this->view = 'layout'; $this->data = [ 'content' => 'index', 'url' => $this->router->generate('edit') ]; }
  • 98.
    Definindo rotas /escola-aura/config/default.php // aroute named 'edit' 'edit' => [ 'path' => '/escola-aura/edit/{:matricula}', 'values' => [ 'controller' => 'home', 'action' => 'edit', 'matricula' => 0 ], 'params' => [ 'matricula' => '(d+)' ] ],
  • 99.
    Controle de edição publicfunction actionEdit() { $this->view = 'layout'; $this->data = [ 'content' => 'edit', 'action' => $this->router->generate('save') ]; }
  • 100.
    Visão de edição /escola-aura/include/Escola/Package/Web/Home/views/edit.php <formaction="<?php echo $this->action?>" method="post"> Nome: <input type="text" name="nome" autofocus="autofocus"> <input type="hidden" name="matricula"> <input type="submit" value="gravar"> </form>
  • 101.
    Nossa tabela Banco dedados "escola-aura" CREATE TABLE IF NOT EXISTS `alunos` ( `matricula` int(11) NOT NULL AUTO_INCREMENT, `nome` varchar(30) COLLATE utf8_unicode_ci NOT NULL, PRIMARY KEY (`matricula`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci AUTO_INCREMENT=1 ;
  • 102.
    Definição de rotade inclusão /escola-aura/config/default.php // a route named 'save' 'save' => [ 'path' => '/escola-aura/save', 'values' => [ 'controller' => 'home', 'action' => 'save' ] ],
  • 103.
    Ação de inclusão publicfunction actionSave() { $connection = $GLOBALS['di']->get('database'); $connection->connect(); $insert = $connection->newInsert(); $insert->into('alunos') ->cols(['nome']); $bind = ['nome'=> $this->getContext()->getPost('nome')]; $stmt = } $connection->query($insert, $bind); $this->response->setRedirect($this->router->generate('home'));
  • 104.
    Conexão com bancode dados /escola-aura/config/default.php $di->set('database',function(){ $connection_factory = include realpath(__DIR__ . '/../package/Aura.Sql/scripts') . DIRECTORY_SEPARATOR . 'instance.php';; $connection = $connection_factory->newInstance( // adapter name 'mysql', // DSN elements for PDO; this can also be // an array of key-value pairs 'host=localhost;dbname=escola-aura', // username for the connection 'root', // password for the connection 'xampp' ); return $connection; }); $GLOBALS['di'] = $di;
  • 105.
    Listagem de registros /escola-aura/include/Escola/Package/Web/Home/HomePage.php publicfunction actionIndex() { $connection = $GLOBALS['di']->get('database'); $connection->connect(); $select = $connection->newSelect(); $select->cols(['*']) ->from('alunos'); } $this->view = 'layout'; $this->data = [ 'content' => 'index', 'url' => $this->router->generate('edit'), 'list' => $connection->fetchAll($select) ];
  • 106.
    Listagem de registros /escola-aura/include/Escola/Package/Web/Home/views/index.php <ahref="<?php echo $this->url?>">Incluir aluno</a> <table> <thead> <tr> <th>Matrícula</th> <th>Nome</th> </tr> </thead> <?php foreach ($this->list as $item): ?> <tr> <td><?=$item['matricula']?></td> <td><?=$item['nome']?></td> </tr> <?php endforeach; ?> </table>
  • 107.
  • 108.
    Geração de rotade alteração /escola-aura/include/Escola/Package/Web/Home/views/index.php <a href="<?php echo $this->url?>">Incluir aluno</a> <table> <thead> <tr> <th>Matrícula</th> <th>Nome</th> <th colspan="2">&nbsp;</th> </tr> </thead> <?php foreach ($this->list as $item): ?> <tr> <td><?=$item['matricula']?></td> <td><?=$item['nome']?></td> <td><a href="<?=$this->route('edit', ['matricula' => $item['matricula']])? >">alterar</a></td> </tr> <?php endforeach; ?> </table>
  • 109.
    Ação de alteração /escola-aura/include/Escola/Package/Web/Home/HomePage.php publicfunction actionEdit() { $aluno = [ 'matricula' => 0, 'nome' => '' ]; if ($matricula = $this->getParams()['matricula']) { $connection = $GLOBALS['di']->get('database'); $connection->connect(); $select = $connection->newSelect(); $select->cols(['*']) ->from('alunos') ->where('matricula = :matricula'); $aluno = $connection->fetchOne($select,['matricula' => $matricula]); } $this->view = 'layout'; $this->data = [ 'aluno' => $aluno, 'content' => 'edit', 'action' => $this->router->generate('save') ]; }
  • 110.
    Ação de gravação /escola-aura/include/Escola/Package/Web/Home/HomePage.php publicfunction actionSave() { $connection = $GLOBALS['di']->get('database'); $connection->connect(); $matricula = $this->getContext()->getPost('matricula',0); if ($matricula == 0) { $verb = $connection->newInsert(); $verb->into('alunos') ->cols(['nome']); $bind = ['nome'=> $this->getContext()->getPost('nome')]; } else { $verb = $connection->newUpdate(); $verb->table('alunos') ->set('nome',':nome') ->where('matricula = :matricula'); $nome = $this->getContext()->getPost('nome'); $bind = ['matricula' => $matricula, 'nome' => $nome]; } $stmt = $connection->query($verb, $bind); $this->response->setRedirect($this->router->generate('home')); }
  • 111.
    Definição de rotade exclusão /escola-aura/config/default.php // a route named 'delete' 'delete' => [ 'path' => '/escola-aura/delete/{:matricula}', 'values' => [ 'controller' => 'home', 'action' => 'delete', 'matricula' => 0 ], 'params' => [ 'matricula' => '(d+)' ] ]
  • 112.
    Geração de rotade exclusão /escola-aura/include/Escola/Package/Web/Home/views/index.php <a href="<?php echo $this->url?>">Incluir aluno</a> <table> <thead> <tr> <th>Matrícula</th> <th>Nome</th> <th colspan="2">&nbsp;</th> </tr> </thead> <?php foreach ($this->list as $item): ?> <tr> <td><?=$item['matricula']?></td> <td><?=$item['nome']?></td> <td><a href="<?=$this->route('edit', ['matricula' => $item['matricula']])? >">alterar</a></td> <td><a href="<?=$this->route('delete', ['matricula' => $item['matricula']])? >">excluir</a></td> </tr> <?php endforeach; ?> </table>
  • 113.
    Ação de exclusão /escola-aura/include/Escola/Package/Web/Home/HomePage.php publicfunction actionDelete() { $matricula = $this->getParams()['matricula']; if ($matricula > 0) { $connection = $GLOBALS['di']->get('database'); $connection->connect(); $delete = $connection->newDelete(); $delete->from('alunos') ->where('matricula = :matricula'); $bind = ['matricula' => $matricula]; } } $connection->query($delete,$bind); $this->response->setRedirect($this->router->generate('home'));
  • 114.
    Você pode ainda... ● Definirregras para entrada de dados ● Criar formulários programaticamente ● Gerenciar a sessão com objetos
  • 115.
  • 116.