Mão na massa Restful e Zend Framework 2

I hurried into the local department store Cisco 300-115 pdf to grab1 some last minute Chirsmas gifts. I looked at all the people and grumbled2 AWS-SYSOPS PDF to myself. I would be in here 300-101 pdf Cisco CCNA 100-105 Exam forever Cisco 300-115 pdf and I just Cisco 400-101 pdf had so much to do. Chirsmas was beginning to 100-105 dumps pdfs become such Cisco 300-115 pdf a drag. I kinda wished Cisco 400-101 pdf that I could just sleep through Chirsmas. Cisco CCNA 100-105 Exam But I hurried the best I could through all the people to the toy department. Once again Itcertpasses Cisco 400-101 pdf I kind of mumbled3 to myself at the prices of all these toys, and wondered if the 300-101 pdf grandkids would even play whit4 Itcertpasses Cisco CCNA 100-105 Exam them. I found myself in 100-105 dumps pdfs the doll aisle5. Out of the corner of my eye 100-105 dumps pdfs I saw a little boy about AWS-SYSOPS PDF 5 holding 100-105 dumps pdfs a Itcertpasses lovely doll.He Itcertpasses Cisco CCNA 100-105 Exam kept touching6 her Cisco 300-115 pdf hair and Cisco 300-115 pdf he held her so gently. I could not seem AWS-SYSOPS PDF to help myself. I 300-101 pdf just kept loking over at Cisco 400-101 pdf the little boy and wondered who the doll Cisco 300-115 pdf was for. Cisco CCNA 100-105 Exam I watched him Cisco 300-115 pdf AWS-SYSOPS PDF turn to a woman and he 100-105 dumps pdfs called his aunt by name and said, “Are you sure I don’t have enough money?” She replied a bit impatiently, “You know that you don’t have enough money 300-101 pdf for it.” 300-101 pdf The aunt told the little 300-101 pdf boy AWS-SYSOPS PDF 100-105 dumps pdfs not to go anywhere that she had to go and get some other things and would be back in a few minutes. And then she AWS-SYSOPS PDF left the aisle. The boy AWS-SYSOPS PDF continued to hold the doll. After a bit I asked the Cisco 400-101 pdf boy who the doll was for. He said, “It is the doll my sister wanted so badly for Cisco 300-115 pdf Chirsmas. She just knew that Cisco 300-115 pdf Santa would Cisco 400-101 pdf bring it. “I told 300-101 pdf him that maybe Santa was going to bring it . 300-101 pdf He 300-101 pdf said, “No, Cisco 300-115 pdf Itcertpasses Santa can’t go 300-101 pdf where my sister is…. I have to give the doll to my Mama to take to her. “I asked him where his siter 100-105 dumps pdfs was. He looked at Cisco 400-101 pdf me with the saddest eyes and said, “She was gone to be with Jesus.

My Daddy says that Mamma Cisco 300-115 pdf Itcertpasses is Itcertpasses going Itcertpasses to have to go be with her.” Itcertpasses My heart nearly stopped beating. Then the Cisco CCNA 100-105 Exam boy looked at me again and Cisco CCNA 100-105 Exam said, “I told my 100-105 dumps pdfs Daddy to tell 100-105 dumps pdfs my Mama not Cisco CCNA 100-105 Exam to go yet. I told him to Cisco 400-101 pdf tell her Cisco CCNA 100-105 Exam to wait till I got back from the store.” 100-105 dumps pdfs Then Cisco 400-101 pdf he asked me 300-101 pdf if i wanted to see his picture. I told him I’d love Cisco 300-115 pdf to. AWS-SYSOPS PDF He AWS-SYSOPS PDF pulled out 100-105 dumps pdfs some picture he’d had taken at the front of the store. He said, “I want my Mama to take this Itcertpasses with her so the dosen’t ever forget me. I love my Mama so very much and 300-101 pdf I wish she dind not have 300-101 pdf to leave me.But Daddy says AWS-SYSOPS PDF she will need to be with my sister.” I saw that the little boy had lowered his head and had grown so qiuet. Cisco CCNA 100-105 Exam While he was not looking I reached Cisco 400-101 pdf into my purse and 100-105 dumps pdfs pilled out a handful of bills. I asked the little boy, “Shall we count that miney Cisco 400-101 pdf one more time?” He grew excited and Cisco CCNA 100-105 Exam said, “Yes,I just Cisco 400-101 pdf know it has to be enough.” So Itcertpasses I slipped my money in with his and we began to count it Cisco 300-115 pdf . Of course it was plenty AWS-SYSOPS PDF AWS-SYSOPS PDF for the doll. He softly said, “Thank you 300-101 pdf Jesus for giving me enough Cisco CCNA 100-105 Exam money.” Then the boy Itcertpasses Cisco 300-115 pdf said, “I just asked Jesus to give me enough money to buy this doll so Mama can take Cisco 300-115 pdf it with her Itcertpasses to give my sister. And he heard my prayer. I wanted to ask him give for enough 300-101 pdf to buy my Mama a white rose, Cisco 400-101 pdf but Cisco 400-101 pdf I didn’t ask him, but he gave me enough to buy the doll AWS-SYSOPS PDF and a rose for my Mama. She loves white rose so much. “In Cisco 400-101 pdf a few minutes the aunt came back and I wheeled my cart away. I could not Cisco CCNA 100-105 Exam keep from thinking about the little boy as AWS-SYSOPS PDF 100-105 dumps pdfs I finished my shoppong in a ttally different 100-105 dumps pdfs spirit 100-105 dumps pdfs than when I had started. And I kept remembering a AWS-SYSOPS PDF story Cisco 400-101 pdf I had seen in the newspaper several days earlier about a drunk driver hitting Cisco CCNA 100-105 Exam a car and killing7 a AWS-SYSOPS PDF little girl and the Mother was in serious condition. The family was deciding on whether to remove the life support. Now surely this Itcertpasses little boy did Cisco CCNA 100-105 Exam not belong with that 100-105 dumps pdfs story.Two days later Cisco 300-115 pdf I read in the Cisco CCNA 100-105 Exam paper where the family had disconnected the life support and the young woman had died. I could not forget the little Itcertpasses boy and just kept wondering if the two Itcertpasses were somehow connected. Later that day, I could not help myself and I went out and bought aome white roses and took them to the funeral home where the yough woman was .And there she was holding a lovely white rose, the beautiful doll, and the picture of the 300-101 pdf little boy in the store. I left there in tears, thier life changed forever. The love that little boy had for his little sisiter and his mother was overwhel. And in a split8 second a drunk driver had ripped9 the life of that little boy to pieces.

Mais uma postagem da séria Mão na massa. Aqui vamos ter uma aplicação Restful usando Zend Framework 2, esse tipo de aplicação é largamente utilizada para criação de APIs e arquitetura SOA.

Particularmente eu gosto do Rest por ele ser simples, acredito que essa seja a maior vantagem dele. Muitas pessoas dizem que ele é pior do que o SOAP por questões de segurança e bla bla bla. Para você ter uma ideia, podemos usar o OAuth no Rest, acredito que isso seja o suficiente para mostrar que é seguro. Outro motivo é o fato de usar Json, eu simplesmente acho mais legal que XML, nada mais a declarar. 🙂

Depois de falar esse monte de besteiras para você, vamos ao escopo dessa mão na massa.
Fazer um sistema que leia um CEP informado e retorne o endereço completo, o retorno deve ser em JSon e XML.
Para isso vamos fazer algo bem tranquilo, vamos apenas retornar o método get($id), com os dados fixos em um array.

Se você não tiver um ambiente pronto, eu recomendo usar o Vagrant, aqui uma postagem sobre ele e uma de como configrar um servidor LAMP. Ou, você pode usar o servidor embutido:

php -S 0.0.0.0:8080 -t public/ public/index.php

Primeiramente vamos montar o ambiente de desenvolvimento usando o Skeleton que a Zend disponibiliza, eu tenho um fork dele na minha conta do github e é ele que vamos usar. Download Skeleton.

Depois de descompactar e deixar pronto para uso, vamos as modificações.

Sempre tenho problemas na versão do PHP, por isso vamos usar o Zend Framework 2.2, precisamos alterar o composer.

Agora vamos executar o composer

php composer.phar install

Assim que ele terminar de executar já podemos consultar o site, no meu caso http://localhost:8080.

restfullsample

Vamos definir que a nossa URL para fazer a consulta de CEP será “/api/cep[.:format]/[:CEP]”. Como exemplos:

http://localhost:8080/api/cep.json/06460000

ou

http://localhost:8080/api/cep.xml/06460000

Para fazer isso, precisamos criar uma rota na nossa aplicação para ela responder por esse endereço.

cepsample/module/Application/config/module.config.php (link GitHub)

return array(
    'router' => array(
        'routes' => array(
        ...
          'cep' => array(
              'type' => 'Segment',
              'options' => array(
                  'route' => '/api/cep[.:format]/[:id]',
                  'constraints' => array(
                      'format' => '(json)',
                  ),
                  'defaults' => array(
                      'controller' => 'Application\Controller\Cep',
                      'format' => 'json',
                  ),
              ),
          ),

No mesmo arquivo, procure o indíce “controllers”, ele deve se parecer com isso

'controllers' => array(
    'invokables' => array(
        'Application\Controller\Index' => 'Application\Controller\IndexController'
    ),
),

E deve ficar assim

'controllers' => array(
    'invokables' => array(
        'Application\Controller\Index' => 'Application\Controller\IndexController',
        'Application\Controller\Cep' => 'Application\Controller\CepController'
    ),
),

Com o redirect pronto, podemos iniciar a construção do método em Rest

No caminho “modules/Application/src/Application/Controller” crie um arquivo chamado “CepController.php”, ele deve ser assim:

Agora quando acessarmos a URL ele vai nos mostrar o array que foi definido no método get($id). Se não passarmos nada depois no CEP na URL, o retorno será em JSon, podemos passar XML também.

restfull_final_sample

Esse código por ser baixado pelo meu GitHub aqui.