Slide 1

Slide 1 text

Criando APIs usando o micro-framework Respect

Slide 2

Slide 2 text

Ivan Rosolen Graduado em Sistemas de Informação Pós-graduado em Gerência de Projetos Desenvolvedor a 14+ anos Autor de vários PHPT (testes para o PHP) Entusiasta de novas tecnologias Head of Innovation @ Arizona CTO @ Mokation

Slide 3

Slide 3 text

@ivanrosolen

Slide 4

Slide 4 text

API

Slide 5

Slide 5 text

Vantagens - Troca de informações entre sistemas - Múltiplas interfaces (web, mobile, CLI) - Módulos/Componentes - HTTP Status Codes - Controle de Acesso https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

Slide 6

Slide 6 text

REST BEER

Slide 7

Slide 7 text

API com informações de Ceveja! GET - http://hostname/cerveja/ POST - http://hostname/cerveja/ cerveja[nome] cerveja[estilo] PUT - http://hostname/cerveja/NOME cerveja[nome] cerveja[estilo] DELETE - http://hostname/cerveja/NOME

Slide 8

Slide 8 text

RESPECT

Slide 9

Slide 9 text

Micro-framework para PHP 5.3+ construido por Alexandre Gaigalas (alganet) e comunidade.

Slide 10

Slide 10 text

Como?

Slide 11

Slide 11 text

Composer - Controle de dependências curl -s http://getcomposer.org/installer | php php composer.phar install https://getcomposer.org

Slide 12

Slide 12 text

{ "name": "RestBeer Jelastic Demo", "authors": [ { "name": "Ivan Rosolen", "email": "[email protected]" } ], "require": { "respect/rest": "0.5.x", "respect/relational": "0.5.x", "respect/config": "0.3.x", "respect/validation": "0.4.x" } }

Slide 13

Slide 13 text

Respect/Config - Apenas arquivos .INI - Usa o mesmo parser nativo e rápido do php.ini - Extende o arquivo .INI com seu próprio “dialeto” - Implementa lazy loading para instâncias de objeto https://github.com/Respect/Config

Slide 14

Slide 14 text

db_server = "127.0.0.1" db_name = "restbeer" db_user = "user" db_pwd = "pwd" dsn_mysql = "mysql:host=[db_server];dbname=[db_name]" dsn_mysql; // mysql:host=127.0.0.1;dbname=restbeer

Slide 15

Slide 15 text

Respect/Relational - Quase zero de configuracão (convenção) - Fluent interface: $mapper->author[7]->fetch(); - Diferentes tipos de banco de dados - Registros são tratados como Plain Data Object https://github.com/Respect/Relational

Slide 16

Slide 16 text

author->fetchAll(); // criar objeto de um registro $obj = new stdClass; $obj->name = 'Ivan Rosolen'; // "gravar" informação no banco $mapper->author->persist($obj); $mapper->flush();

Slide 17

Slide 17 text

Respect/Validation - Fluent/Chained interface: v::numeric()->positive()->between(1, 256)->validate($num) - 100+ validadores testados - Fácil extender ou criar novas regras (Concrete API) - Php 7 ( Quase pronto ) https://github.com/Respect/Validation

Slide 18

Slide 18 text

use Respect\Validation\Validator as v; // validar número simples v::numeric()->validate(42); //true // validar em cadeia $v = v::arr() // validar se é array ->key('nome', $rule = v::alnum()->notEmpty()->noWhitespace()) // validar a key 'nome' ->key('estilo', $rule) // utilizando a mesma regra da key de cima ->validate($_POST['cerveja']); // negação de qualquer regra $v = v::not(v::int())->validate(10); // false // operadores lógicos v::allOf(v::numeric(), v::hexa(), v::min(1)); // numeric, hexadecimal e pelo menos 1 v::oneOf(v::nullValue(), v::numeric()); // null ou numeric

Slide 19

Slide 19 text

Respect/Router - Thin and lightweight controller para aplicações RESTful e APIs - “Don't try to change PHP, small learning curve.” - If/Before/After/Accept/Auth/Any/By … https://github.com/Respect/Rest

Slide 20

Slide 20 text

get('/', function() { return 'Hello World'; }); // Separando regras das rotas :D $router->get('/api/uri/*/*', 'Namespace\Cool\Class'); $router->post('/api/uri/', 'Namespace\Cool\Class'); $router->put('/api/uri/', 'Namespace\Cool\Class'); $router->delete('/api/uri/*', 'Namespace\Cool\Class');

Slide 21

Slide 21 text

Projeto

Slide 22

Slide 22 text

dsn_sqlite)); // Criar instância do router $router = new Router(); //Rota para qualquer tipo de request (any) $router->any('/', function () { return 'RestBeer!'; });

Slide 23

Slide 23 text

GET Cerveja

Slide 24

Slide 24 text

$router->get('/cerveja/*', function ($data = null) use ($mapper) { if ( !isset($data) ) { $cervejas = $mapper->cervejas->fetchAll(); header('HTTP/1.1 200 Ok'); return $cervejas; } $data = filter_var( $data, FILTER_SANITIZE_FULL_SPECIAL_CHARS ); if ( v::not(v::alnum()->notEmpty())->validate($data) ) { header('HTTP/1.1 400 Bad Request'); return 'Faltam parâmetros'; } $cerveja = $mapper->cervejas(array( 'nome' => $data ))->fetch(); if ( !$cerveja ) { header('HTTP/1.1 204 No Content'); return; } header('HTTP/1.1 200 Ok'); return $cerveja; });

Slide 25

Slide 25 text

POST Cerveja

Slide 26

Slide 26 text

$router->post('/cerveja', function () use ($mapper) { if ( !isset($_POST) || !isset($_POST['cerveja']) || v::not(v::arr())->validate($_POST['cerveja']) ) { header('HTTP/1.1 400 Bad Request'); return 'Faltam parâmetros'; } $valid = v::arr()->key('nome', $rule = v::alnum()->noWhitespace())->key('estilo', $rule)->validate($_POST['cerveja']); if ( !$valid ) { header('HTTP/1.1 400 Bad Request'); return 'Faltam parâmetros'; } $cerveja = new stdClass(); $cerveja->nome = filter_var($_POST['cerveja']['nome'], FILTER_SANITIZE_FULL_SPECIAL_CHARS); $cerveja->estilo = filter_var($_POST['cerveja']['estilo'], FILTER_SANITIZE_FULL_SPECIAL_CHARS); $check = $mapper->cervejas(array( 'nome' => $cerveja->nome ))->fetch(); if ( $check ) { header('HTTP/1.1 409 Conflict'); return 'Cerveja já existe no sistema'; } $mapper->cervejas->persist($cerveja); $mapper->flush(); if ( !isset($cerveja->id) || empty($cerveja->id) ) { header('HTTP/1.1 422 Unprocessable Entity'); return 'Erro ao inserir cerveja'; } header('HTTP/1.1 201 Created'); return 'Cerveja criada'; });

Slide 27

Slide 27 text

PUT Cerveja

Slide 28

Slide 28 text

$router->put('/cerveja/*', function ($nome) use ($mapper) { parse_str(file_get_contents('php://input'), $data); if ( !isset($data) || !isset($data['cerveja']) || v::not(v::arr())->validate($data['cerveja']) ) { header('HTTP/1.1 400 Bad Request'); return 'Faltam parâmetros'; } $nome = filter_var( $nome, FILTER_SANITIZE_FULL_SPECIAL_CHARS ); if ( v::not(v::alnum()->notEmpty())->validate($nome) ) { header('HTTP/1.1 400 Bad Request'); return 'Faltam parâmetros'; } $cerveja = $mapper->cervejas(array( 'nome' => $nome ))->fetch(); if ( !$cerveja ) { header('HTTP/1.1 204 No Content'); return; } $newNome = filter_var( $data['cerveja']['nome'], FILTER_SANITIZE_FULL_SPECIAL_CHARS ); $newEstilo = filter_var( $data['cerveja']['estilo'], FILTER_SANITIZE_FULL_SPECIAL_CHARS ); $cerveja->nome = $newNome; $cerveja->estilo = $newEstilo; $mapper->cervejas->persist($cerveja); $mapper->flush(); header('HTTP/1.1 200 Ok'); return 'Cerveja atualizada'; }); * removido parte do código para ficar melhor no slide

Slide 29

Slide 29 text

DELETE Cerveja

Slide 30

Slide 30 text

$router->delete('/cerveja/*', function ($nome) use ($mapper) { $nome = filter_var( $nome, FILTER_SANITIZE_FULL_SPECIAL_CHARS ); if ( !isset($nome) || v::not(v::alnum()->notEmpty())->validate($nome) ) { header('HTTP/1.1 400 Bad Request'); return 'Faltam parâmetros'; } $cerveja = $mapper->cervejas(array( 'nome' => $nome ))->fetch(); if ( !$cerveja ) { header('HTTP/1.1 422 Unprocessable Entity'); return 'Erro ao validar cerveja'; } $mapper->cervejas->remove($cerveja); $mapper->flush(); header('HTTP/1.1 200 Ok'); return 'Cerveja removida'; });

Slide 31

Slide 31 text

Formatar Resultado

Slide 32

Slide 32 text

validate($data) ) { $data = array($data); } return json_encode($data,true); }; $router->always('Accept', array('application/json' => $jsonRender));

Slide 33

Slide 33 text

Basic Auth

Slide 34

Slide 34 text

get('/admin', function () { return 'RestBeer Admin Protected!'; })->authBasic('Secret Area', function ($user, $pass) { return checkLogin($user, $pass); });

Slide 35

Slide 35 text

Deploy

Slide 36

Slide 36 text

Jelastic - Locaweb? - Git - Barato - 14 Dias Grátis Aplicações PHP no Jelastic https://t.co/aHi3ZixLon

Slide 37

Slide 37 text

Referências / Links

Slide 38

Slide 38 text

Github https://github.com/ivanrosolen/RestBeer-Jelastic Respect http://respect.github.io Jelastic http://www.locaweb.com.br/cloud/jelastic https://twitter.com/kemelzaidan http://pt.slideshare.net/ivanrosolen/jelastic-53375753 PHPSP http://phpsp.org.br Elton Minetto https://github.com/eminetto/restbeer

Slide 39

Slide 39 text

Dúvidas?

Slide 40

Slide 40 text

OBRIGADO! Avalie esta palestra joind.in/15207 Visite phpsp.org.br