<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>hlegius &#187; Desenvolvimento</title>
	<atom:link href="http://programe.me/tag/desenvolvimento/feed/" rel="self" type="application/rss+xml" />
	<link>http://programe.me</link>
	<description>programação, desenvolvimento, tecnologia e muito o que contar.</description>
	<lastBuildDate>Wed, 23 Nov 2011 17:26:38 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Meu ambiente de trabalho em 7 itens</title>
		<link>http://programe.me/meu-ambiente-de-trabalho-em-7-itens/</link>
		<comments>http://programe.me/meu-ambiente-de-trabalho-em-7-itens/#comments</comments>
		<pubDate>Mon, 27 Dec 2010 09:54:14 +0000</pubDate>
		<dc:creator>hlegius</dc:creator>
				<category><![CDATA[Dia-a-dia]]></category>
		<category><![CDATA[ambiente]]></category>
		<category><![CDATA[Desenvolvimento]]></category>
		<category><![CDATA[Organização]]></category>

		<guid isPermaLink="false">http://www.hlegius.pro.br/?p=661</guid>
		<description><![CDATA[Neste meme iniciado por @duodraco, fui pelo @brgomes indicado a postar sobre os 7 itens mais relevantes em meu ambiente de trabalho. Dentre os vários itens que utilizo / dependo, destaco aqui os de maior importância: 1. Sistema Operacional: Linux. Utilizo tal plataforma pela simplicidade no gerenciamento e performance. Dentre as distribuições, opto sempre por [...]]]></description>
			<content:encoded><![CDATA[<p>Neste meme iniciado por <a href="http://twitter.com/duodraco" target="_blank">@duodraco</a>, fui pelo <a href="http://twitter.com/brgomes" target="_blank">@brgomes</a> indicado a postar sobre os 7 itens mais relevantes em meu ambiente de trabalho. Dentre os vários itens que utilizo / dependo, destaco aqui os de maior importância:</p>
<p><strong>1. Sistema Operacional:</strong> Linux. Utilizo tal plataforma pela simplicidade no gerenciamento e performance. Dentre as distribuições, opto sempre por Arch, Slackware ou Gentoo, nesta ordem.</p>
<p><strong>2. Controle de versão:</strong> Git. Já tem uns meses que uso em novos projetos, recentemente porém, adotei também nos projetos SVN <a href="http://vexcorp.com" target="_blank">lá na empresa</a> com o git-svn enquanto a migração pra Git por lá não acontece.</p>
<p><strong>3. IDE: </strong>Há quem fale que uma IDE não agrega em nada, pois eu vejo o contrário. Ter praticidade ao programar é muito bom. Eu costumo utilizar muitos atalhos de teclado para evitar utilizar o mouse ao codificar, elevando o desempenho. Já utilizei várias IDEs para um <em>trial </em>até que há mais de um ano venho utilizando Zend Studio (Eclipse based) para PHP e Eclipse JEE/Ruby para Java e Ruby. Assim os atalhos de uma funcionam na outra <img src='http://programe.me/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<div class="wp-caption aligncenter" style="width: 510px"><a href="http://www.flickr.com/photos/hlegius/4732094176/"><img title="Home Office v1" src="http://farm2.static.flickr.com/1437/4732094176_28b2f2486e.jpg" alt="Home Office v1" width="500" height="375" /></a><p class="wp-caption-text">Home Office v1</p></div>
<p style="text-align: center;">
<p><strong>4. Ambiente:</strong> o ambiente em volta é deveras importante para mim ! Recinto calmo, com iluminação adequada e recursos a mão fazem toda diferença ao trabalhar. Até a cor do ambiente influência. Neste caso, porque não <a href="http://www.google.com.br/search?hl=pt-BR&amp;client=opera&amp;hs=wTp&amp;rls=pt-BR&amp;channel=suggest&amp;&amp;sa=X&amp;ei=7FsYTf-TBIyr8AbI5M33DQ&amp;ved=0CCwQBSgA&amp;q=Feng+shui&amp;spell=1" target="_blank">seguir as dicas</a>, não é ?</p>
<p><strong>5. Remoto:</strong> servidores e apps remotas auxiliam o compartilhamento, armazenamento e controle dos softwares/programas/<span style="text-decoration: line-through;">malwares</span> desenvolvidos. Utilizo um server shared na Dreamhost com dois domínios apontando nele e estou cogitando a ideia de utilizar uma VPS. Lá ficam salvos além das versões comitadas dos softwares, um ambiente de deploy e meu servidor Git remoto para onde comito meus projetos particulares. No Github ficam somente os open <img src='http://programe.me/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<p><strong>6.  Controle de atividades:</strong> Utilizava até um tempinho atrás o renomado <a href="http://basecamphq.com" target="_blank">Basecamp</a>. Porém, na Rubyconf deste ano, fui apresentado ao seu concorrente mais em conta, <a href="http://goplanapp.com" target="_blank">Go Plan</a>. Fiz um teste e gostei da ferramenta. Atualmente estou migrando os dados do Basecamp para lá. Issue tracker <span style="text-decoration: line-through;">eu não uso, afinal, não produzo bugs <img src='http://programe.me/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </span> eu também coloco no Basecamp/Go Plan.</p>
<p><strong>7.  Monitores:</strong> sou viciado em monitor. Comecei comprando um de 19&#8242; que virou um de 22&#8242; e depois um de 24&#8242;. Espaço na área de trabalho virtual agrega muito quando trabalha-se com desenvolvimento. Não é ter visão de uma linha com trocentas colunas, mas sim, utilizar as abas da IDE com suas funções &#8211; unit test, shell, filesystem, outline, type&#8230; &#8211; o que ocupa um bom espaço na tela.</p>
<p>Para continuar, convido:</p>
<p>@tmadeira<br />
@lfamorim<br />
@gchapiewski<br />
@loiane<br />
@chesterbr</p>
]]></content:encoded>
			<wfw:commentRss>http://programe.me/meu-ambiente-de-trabalho-em-7-itens/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Procura-se o Programador Sênior</title>
		<link>http://programe.me/procura-se-o-programador-senior/</link>
		<comments>http://programe.me/procura-se-o-programador-senior/#comments</comments>
		<pubDate>Tue, 22 Jun 2010 15:19:29 +0000</pubDate>
		<dc:creator>hlegius</dc:creator>
				<category><![CDATA[Carreira]]></category>
		<category><![CDATA[Featured Articles]]></category>
		<category><![CDATA[Desenvolvimento]]></category>
		<category><![CDATA[developer]]></category>

		<guid isPermaLink="false">http://www.hlegius.pro.br/?p=455</guid>
		<description><![CDATA[O que muito é visto nas ofertas de &#8220;vagas&#8221; para programadores são os rótulos Júnior, Pleno e Sênior. Mas, como saber em qual destes níveis você está ? E, é possível tachar pessoas com estes níveis ? Já conversei com pessoas que batem o martelo facilmente dizendo: - É por tempo.  Eu programo em brainfuck [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">O que muito é visto nas ofertas de &#8220;vagas&#8221; para programadores são os rótulos Júnior, Pleno e Sênior. Mas, como saber em qual destes níveis você está ? E, é possível tachar pessoas com estes níveis ?</p>
<p style="text-align: center;">
<div class="wp-caption aligncenter" style="width: 510px"><a href="http://www.moma.org/collection/browse_results.php?object_id=79018"><img class=" " title="The Persistence of Memory" src="http://farm4.static.flickr.com/3023/3097529664_ffc705e57e.jpg" alt="The Persistence of Memory" width="500" height="333" /></a><p class="wp-caption-text">Salvador Dali, 1931 - The Persistence of Memory</p></div>
<p>Já conversei com pessoas que batem o martelo facilmente dizendo:</p>
<p style="padding-left: 30px;"><em>- É por tempo.  Eu programo em <a href="http://en.wikipedia.org/wiki/Brainfuck" target="_blank">brainfuck</a> há seis anos, logo sou sênior. </em></p>
<p>Será mesmo ?</p>
<p style="text-align: justify;">Em tempos modernos, fica ainda mais complexo fazer uma avaliação deste tipo para programadores, arquitetos ou engenheiros de software, pois, não é somente uma linguagem de programação que está em análise. É todo um contexto que abrange desde a escolha do ambiente de desenvolvimento até relacionamento com stakeholders e domínio em metodologias e paradigmas de desenvolvimento.</p>
<p style="text-align: justify;">Se temos a análise temporal como inválida, então o que espera-se de um dito sênior ?</p>
<p style="text-align: justify;">Para tal, conversei com três pessoas que estão diretamente envolvidas com estes aspectos.</p>
<p style="text-align: left;">&nbsp;</p>
<p style="padding-left: 30px; text-align: justify;">Creio que sim. Existem os profissionais seniores, porém muitas pessoas, e empresas, acabam confundindo o nível do profissional com o seu tempo de experiência.</p>
<p style="padding-left: 30px; text-align: justify;">Em minha visão, o tempo de experiência é importante, porém, não determinante para rotular um profissional, ou seja, é perfeitamente possível existirem seniores com 3 anos de experiência e juniores com 15 anos.</p>
<p style="padding-left: 30px; text-align: justify;">O profissional Júnior, é aquele que já desempenha as tarefas com certa autonômia, porém, necessita de um maior tempo de pesquisa e em alguns casos de orientação.</p>
<p style="padding-left: 30px; text-align: justify;">Por sua vez, o pleno já demora um tempo menor para realizar as mesmas tarefas além de não necessitar de orientações referente aquela tarefa. O que difere o pleno de um sênior é a visão holistica, ou seja, para ser um profissional sênior é preciso possuir habilidades complementares as necessárias para o desenvolvimento daquela tarefa, isso ajuda acima de tudo no desenho de uma melhor solução além de maior facilidade no tratamento de problemas.</p>
<p style="padding-left: 30px; text-align: justify;">Outro ponto que vale ser observado, é que muitas vezes o sênior é destacado para tarefas simples, que não exige um conhecimento avançado, como seguir um procedimento de criação de usuário. Esse fato, além de desmotivar o profissional, gasta recursos de forma imprudente, já que são os seniores que deveriam criar os procedimentos a serem seguidos, além de desenhar soluções para problemas e corrigir falhas críticas ou em serviços críticos.</p>
<p style="text-align: right;"><a href="http://twitter.com/bufoni" target="_blank">Vinícius Bufoni</a>, coordenador de engenharia web na <a href="http://www.vexcorp.com" target="_blank">Vex</a></p>
<p style="text-align: left;">&nbsp;</p>
<p style="text-align: left;">&nbsp;</p>
<p style="padding-left: 30px; text-align: justify;">Este é um assunto interessante. Na maioria dos lugares as pessoas usam &#8220;anos de experiência&#8221; como medida para classificar. Esta é, na minha experiência, uma das piores maneiras de se fazer este tipo de classificação. Uma pessoa que desenvolve em, digamos, JSP e Servlets Java por 10 anos não necessariamente tem 10 anos de experiência desenvolvendo software, ele tem experiência desenvolvendo JSP e Servlets! E mesmo assim, tempo gasto em uma tecnologia não está diretamente relacionado com proficiência nesta. Enfim, utilizar tempo para medir experiência é, normalmente, uma besteira.</p>
<p style="text-align: justify; padding-left: 30px;">A forma com que eu tenho lidado com esta relação entre níveis de desenvolvedores, atualmente, é usando algo chamado modelo Dreyfus de aquisição de conhecimento: <a href="http://en.wikipedia.org/wiki/Dreyfus_model_of_skill_acquisition" target="_self">http://en.wikipedia.org/wiki/Dreyfus_model_of_skill_acquisition</a> .</p>
<p style="text-align: justify; padding-left: 30px;">Normalmente eu tenho as áreas em que eu considero que meu time deve ser competente (este post: <a href="http://fragmental.tw/2009/11/24/i-wish-i-knew-that-before-getting-this-job-–-slides-and-long-notes/" target="_blank">http://fragmental.tw/2009/11/24/i-wish-i-knew-that-before-getting-this-job-–-slides-and-long-notes</a> da uma idéia sobre quais seriam estas áreas) e uso o Dreyfus para tentar entender onde cada um está nestas competências. Tem funcionado relativamente bem para mim mas ainda é, como sempre será, problemático e, por muitas vezes, injusto.</p>
<p style="padding-left: 30px; text-align: right;"><a href="http://fragmental.tw/" target="_blank">Phillip Calçado</a>, consultor na <a href="http://www.thoughtworks.com" target="_blank">ThoughtWorks</a></p>
<p style="text-align: left;">&nbsp;</p>
<p style="text-align: left;">&nbsp;</p>
<p style="padding-left: 30px; text-align: justify;">Do meu ponto de vista um profissional sênior é acima de tudo auto suficiente, é o tipo de profissional em que você não precisa passar o que deve ser feito, ele geralmente entende seu papel em uma equipe e como pode contribuir.</p>
<p style="padding-left: 30px; text-align: justify;">Um profissional Sênior consegue tomar decisões e assumir responsabilidades, ele não depende de alocações e precisa de muito pouca supervisão gerencial e técnica.</p>
<p style="text-align: justify; padding-left: 30px;">Geralmente um profissional Sênior também, está sempre atualizado e esta sempre ligado em tendências do mercado e em como adaptar estas novidades a sua realidade nos projetos em que esta envolvido.</p>
<p style="text-align: justify; padding-left: 30px;">&#8220;Tempo&#8221; de experiência na verdade não é tão importante, mas a diversidade e intensidade da experiência da pessoa é extremamente importante, se ele esteve envolvido uma grande diversidade de projetos e atuou em papeis dos mais diversos, um profissional sênior geralmente consegue se adaptar pois já trabalhou em diversos papéis e com diversos times.</p>
<p style="text-align: justify; padding-left: 30px;">No caso de grandes empresas de Internet, como o Yahoo!, é vital que o profissional sênior entenda de e tenha tido vivência com projetos de grande escala, e que entenda de Sistemas, arquiteturas e plataformas que funcionem com grandes volumes de acesso e demandam muita performance.</p>
<p style="text-align: justify; padding-left: 30px;">Não gosto muito destes rótulos, mas um profissional Pleno depende de um nível de supervisão/apoio maior. Um Pleno também tende a ser mais inseguro na tomada de decisões e definições mais complexas.</p>
<p style="text-align: justify; padding-left: 30px;">Mas a principal diferença é a experiência, bagagem de conhecimento. Em entrevistas sempre pergunto qual foi o maior desastre da carreira da pessoa, espero que ele me diga quais foram os erros e o que ele aprendeu com isso. Isso mostra maturidade em relação a tentativa/erro, onde não se deve temer cometer erros e que sempre devemos aprender com eles e continuar tentando. Isso é chave para ser inovador.</p>
<p style="text-align: right;"><a href="http://me.me/acarlos1000" target="_blank">Antônio Carlos Silveira</a>, diretor de Produto e Engenharia, <a href="http://yahoo.com.br" target="_blank">Yahoo! América Latina</a></p>
<p style="text-align: right;">
<p style="text-align: left;">Cada um tem seus métodos de análise, mas ficou evidente que contar os dias no calendário já não é mais tão convincente como parecia <img src='http://programe.me/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://programe.me/procura-se-o-programador-senior/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>Programador apaixonado</title>
		<link>http://programe.me/programador-apaixonado/</link>
		<comments>http://programe.me/programador-apaixonado/#comments</comments>
		<pubDate>Sun, 06 Jun 2010 22:10:24 +0000</pubDate>
		<dc:creator>hlegius</dc:creator>
				<category><![CDATA[Carreira]]></category>
		<category><![CDATA[Desenvolvimento]]></category>
		<category><![CDATA[Dia-a-dia]]></category>
		<category><![CDATA[PHP]]></category>

		<guid isPermaLink="false">http://www.hlegius.pro.br/?p=599</guid>
		<description><![CDATA[Ser programador é uma coisa engraçada ! Tenho visto recentemente várias movimentações por parte de programadores, buscando juntar-se para: programar ! É possível reparar que a quantidade de grupinhos que buscam aprender coisas novas &#8211; sejam elas linguagens da hype &#8211; metodologias ou ainda algum projeto pessoal integrando algumas linguagens, dados públicos e uma interface [...]]]></description>
			<content:encoded><![CDATA[<p><a title="Ser Programador" href="http://hlegius.pro.br/ser-programador" target="_blank">Ser programador</a> é uma coisa engraçada ! Tenho visto recentemente várias movimentações por parte de programadores, buscando juntar-se para: <strong>programar</strong> !<br />
É possível reparar que a quantidade de grupinhos que buscam aprender coisas novas &#8211; sejam elas linguagens da <em>hype</em> &#8211; metodologias ou ainda algum projeto pessoal integrando algumas linguagens, dados públicos e uma interface dita Web 2.0.</p>
<div class="wp-caption aligncenter" style="width: 510px"><a href="http://www.flickr.com/photos/danicuki/4671867058/in/set-72157624208353028/"><img title="Random Hack of Kindness São Paulo 2010 por danicuki" src="http://farm2.static.flickr.com/1275/4671867058_104bf2b4eb.jpg" alt="" width="500" height="333" /></a><p class="wp-caption-text">Random Hack of Kindness São Paulo 2010 por danicuki</p></div>
<p>Eventos como Yahoo! Open Hack day; Google Developer Day; o recente Random Hack of Kindness; <a href="http://www.codingdojo.org" target="_blank">Coding Dojo</a> (o de Sampa no IME da USP está meio inativo ao que consta); e vários outros movimentos iniciados até por empresas, como a própria <a href="http://www.caelum.com.br" target="_blank">Caelum</a> que já abriu as portas para criar um ambiente onde programdores pudessem se juntar e desenvolver suas coisas, ou mesmo que fechado ao grupo de programadores da mesma como já ouvi relatos de programadores.</p>
<p>O que leva esse bando de programador <em>malhucos</em> das cavernas a participarem com empolgação destes eventos &#8211; muitas das vezes apenas com <em>free lunch</em> e Internet 0800 ? São desocupados ? Loucos ?</p>
<div class="wp-caption aligncenter" style="width: 510px"><a href="http://www.flickr.com/photos/acarlos1000/4448541107/"><img title="Yahoo! Open Hack Day Brazil 2010" src="http://farm5.static.flickr.com/4020/4448541107_bf35ab2bea.jpg" alt="Yahoo! Open Hack Day Brazil 2010" width="500" height="281" /></a><p class="wp-caption-text">Yahoo! Open Hack Day Brazil 2010 por Antônio Carlos</p></div>
<p>Simples: adoram o que fazem ! São essas pessoas que geralmente criam tendências, aplicam ideias e tomam iniciativas nas corporações em que trabalham; São os mesmos developers que passam horas a fio programando com vários livros de nomes <em>nonsense</em> à tira-colo; ou que criam projetos pessoais para suprir uma necessidade própria e acabam chamando a atenção de muita gente &#8211; vide tantas <em>startups</em> bem sucessidas criadas e mantidas por programadores.</p>
<p>Geralmente esses mesmos programadores conhecem pelo menos duas linguagens. O motivo ? Curiosidade ! Pouco importa se Ruby on Rails fará sucesso no mercado coorporativo ou se Python não agrada o chefe. É legal para eles, então, investem tempo nisto.</p>
<p>Sempre em busca de novos conhecimentos, fanáticos pela arte em programar e fazer coisas novas; de novas formas e com novas ferramentas. Criam coisas, compartilham o feito e ainda passam a diante o novo conhecimento com artigos, blogs ou seminários. São programadores sempre motivados que buscam fazer uma análise crítica sobre suas próprias formas de programação buscando a evolução das ideias.</p>
<p>Vida social ? Muito bem, obrigado ! Nestas idas e vindas acabam conhecendo pessoas, lugares e oportunidades diferentes. Trocam ideias, conversam, trocam contactos das redes sociais; <acronym title="PHPinga, oi ?">juntam-se em botecos</acronym> ou equivalentes tornando o simples ato de programar em grupo em praticamente uma festa completa ! <img src='http://programe.me/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://programe.me/programador-apaixonado/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Alternativa ao Cron Jobs em PHP</title>
		<link>http://programe.me/alternativa-ao-cron-jobs-em-php/</link>
		<comments>http://programe.me/alternativa-ao-cron-jobs-em-php/#comments</comments>
		<pubDate>Sat, 28 Mar 2009 01:25:25 +0000</pubDate>
		<dc:creator>hlegius</dc:creator>
				<category><![CDATA[Featured Articles]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Desenvolvimento]]></category>

		<guid isPermaLink="false">http://www.hlegius.pro.br/?p=326</guid>
		<description><![CDATA[Salve ! Sabe aquelas vezes em que você precisa realizar tarefas demoradas no browser do cliente e então você lembra do maravilhoso Cron Jobs ? Pois é, uma excelente ferramenta a nossa disposição. Entretanto, às vezes, certas empresas de hosting (Locaweb é uma) define um horário para funcionamento destas "tarefas agendadas". No caso da Locaweb [...]]]></description>
			<content:encoded><![CDATA[<p>Salve !</p>
<p>Sabe aquelas vezes em que você precisa realizar tarefas demoradas no browser do cliente e então você lembra do maravilhoso Cron Jobs ? Pois é, uma excelente ferramenta a nossa disposição. Entretanto, às vezes, certas empresas de hosting (Locaweb é uma) define um horário para funcionamento destas "tarefas agendadas". No caso da Locaweb é das 2 às 3 da matina apenas.</p>
<p>Mas, mas e agora ? Como executar a tal sonhada tarefa "em background" quando não há o Cron Jobs como opção ?</p>
<h3>Um pouco de história</h3>
<p>Sabemos muito bem que o PHP é <em>server-side</em> e isso significa que o PHP roda no servidor e não no cliente como o Javascript, por exemplo. Entretanto, logo quando eu comecei a programar com PHP eu me perguntava o motivo pelo qual o script era interrompido ao clicar no botão Stop do browser ou então quando eu o fechava já que a ação era no cliente e não no servidor. Tempos depois descobri que nestes eventos, era enviada uma informação ao servidor PHP (via TCP, claro) que de o usuário "abortou" a conexão com ele e o PHP bem esperto que é, parava aquela tarefa.</p>
<h3>Entretanto...</h3>
<p>O PHP nos permite manipular esse comportamento, ou seja, posso dizer ao PHP que eu quero continuar executando o script mesmo se o cliente nos <em>deixar na voz</em> ! Como uma imagem vale mais do que mil palavras, deixo aos senhores um pequeno vídeo que fiz demonstrando o funcionamento:</p>
<p><object width="590" height="422"><param name="movie" value="http://www.youtube.com/v/kJT2rEK7mvo&#038;hl=pt-br&#038;fs=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/kJT2rEK7mvo&#038;hl=pt-br&#038;fs=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="590" height="422"></embed></object></p>
<p>Perceba que caso queira redirecionar o usuário para outra página e continuar trabalhando naquela tarefa, você precisa manipular o buffer e os headers da página da forma como coloquei no script, caso contrário, ele irá processar todo o conteúdo e depois sim, redirecionar. Isto por quê, como não estamos enviando nada diretamente ao browser, o Apache espera uma quantidade de dados enviados antes de processar quaisquer headers. Com as <a href="http://br.php.net/manual/en/ref.outcontrol.php" target="_blank">funções de buffer do PHP</a> nós podemos mudar também esse comportamento, forçando-lhe a obedecer o header (Location).</p>
<p>Deixo abaixo o código dos dois arquivos usados no vídeo:</p>
<div class="igBar"><span id="lcode-3"><a href="#" onclick="javascript:showPlainTxt('code-3'); return false;">PLAIN TEXT</a></span></div>
<div class="syntax_hilite"><span class="langName">CODE:</span>
<div id="code-3">
<div class="code">
<ol>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&lt;?php</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color:#008000;">/**</span></div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color:#008000;"> * Connection Handler</span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color:#008000;"> * @author Hélio Costa e Silva &lt;helio@hlegius.pro.br&gt;</span></div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color:#008000;"> * @version 27/03/2009</span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color:#008000;"> *</span></div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color:#008000;"> * @internal teste</span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color:#008000;"> */</span></div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">ob_start<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">&#41;</span>;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">ignore_user_abort<span style="color:#006600; font-weight:bold;">&#40;</span>true<span style="color:#006600; font-weight:bold;">&#41;</span>;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">$n = <span style="color:#800000;color:#800000;">1</span>;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">do <span style="color:#006600; font-weight:bold;">&#123;</span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; error_log<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0000;">'Sequência '</span> . $n . <span style="color:#CC0000;">"<span style="color:#000099; font-weight:bold;">\n</span>"</span>, <span style="color:#800000;color:#800000;">3</span>, <span style="color:#CC0000;">'foobar.txt'</span><span style="color:#006600; font-weight:bold;">&#41;</span>;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; $n++;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; sleep<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#800000;color:#800000;">1</span><span style="color:#006600; font-weight:bold;">&#41;</span>;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; flush<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">&#41;</span>;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; if <span style="color:#006600; font-weight:bold;">&#40;</span>$n&gt; <span style="color:#800000;color:#800000;">35</span><span style="color:#006600; font-weight:bold;">&#41;</span> break;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color:#006600; font-weight:bold;">&#125;</span> while <span style="color:#006600; font-weight:bold;">&#40;</span>true<span style="color:#006600; font-weight:bold;">&#41;</span>;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">?&gt; </div>
</li>
</ol>
</div>
</div>
</div>
<p></p>
<div class="igBar"><span id="lcode-4"><a href="#" onclick="javascript:showPlainTxt('code-4'); return false;">PLAIN TEXT</a></span></div>
<div class="syntax_hilite"><span class="langName">CODE:</span>
<div id="code-4">
<div class="code">
<ol>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&lt;?php</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color:#008000;">/**</span></div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color:#008000;"> * Connection Handler</span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color:#008000;"> * @author Hélio Costa e Silva &lt;helio@hlegius.pro.br&gt;</span></div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color:#008000;"> * @version 27/03/2009</span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color:#008000;"> *</span></div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color:#008000;"> * @internal teste</span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color:#008000;"> */</span></div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">$n = <span style="color:#800000;color:#800000;">30</span>;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">do <span style="color:#006600; font-weight:bold;">&#123;</span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; if <span style="color:#006600; font-weight:bold;">&#40;</span>$n == <span style="color:#800000;color:#800000;">36</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">&#123;</span></div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp; &nbsp; header <span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0000;">"Location: http://localhost/estudos/"</span><span style="color:#006600; font-weight:bold;">&#41;</span>;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp; &nbsp; ob_end_clean<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">&#41;</span>;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp; &nbsp; header <span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0000;">"Connection: close"</span><span style="color:#006600; font-weight:bold;">&#41;</span>;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp; &nbsp; ignore_user_abort<span style="color:#006600; font-weight:bold;">&#40;</span>true<span style="color:#006600; font-weight:bold;">&#41;</span>;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp; &nbsp; ob_start<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">&#41;</span>;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp; &nbsp; header<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0000;">"Content-Length: 0"</span><span style="color:#006600; font-weight:bold;">&#41;</span>;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp; &nbsp; ob_end_flush<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">&#41;</span>;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp; &nbsp; flush<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">&#41;</span>;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp; &nbsp; <span style="color:#FF9933; font-style:italic;">// Se houver sessões em aberto, usar também:</span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp; &nbsp; <span style="color:#FF9933; font-style:italic;">//session_write_close();</span></div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color:#FF9933; font-style:italic;">// Sugestão feita pelo usuário em:</span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color:#FF9933; font-style:italic;">// http://br.php.net/manual/en/features.connection-handling.php</span></div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; <span style="color:#006600; font-weight:bold;">&#125;</span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; error_log<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0000;">'Redirecionado '</span> . $n . <span style="color:#CC0000;">"<span style="color:#000099; font-weight:bold;">\n</span>"</span>, <span style="color:#800000;color:#800000;">3</span>, <span style="color:#CC0000;">'foobar.txt'</span><span style="color:#006600; font-weight:bold;">&#41;</span>;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; $n++;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; sleep<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#800000;color:#800000;">1</span><span style="color:#006600; font-weight:bold;">&#41;</span>;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; if <span style="color:#006600; font-weight:bold;">&#40;</span>$n&gt; <span style="color:#800000;color:#800000;">65</span><span style="color:#006600; font-weight:bold;">&#41;</span> break;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color:#006600; font-weight:bold;">&#125;</span> while <span style="color:#006600; font-weight:bold;">&#40;</span>true<span style="color:#006600; font-weight:bold;">&#41;</span>;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">?&gt; </div>
</li>
</ol>
</div>
</div>
</div>
<p></p>
<p>E também, o <a href="http://helio.hlegius.pro.br/hlegius-ignore_user_abort_php.ogv">vídeo original no formato OGV</a>.</p>
<p><strong>Mais informações:</strong></p>
<ul>
<li><a href="http://br.php.net/ignore_user_abort" target="_blank">http://br.php.net/ignore_user_abort</a></li>
<li><a href="http://br.php.net/manual/en/features.connection-handling.php" target="_blank">http://br.php.net/manual/en/features.connection-handling.php</a></li>
</ul>
<p><em>Nota</em>: o programa usado para gravar foi o <strong>qt-RecordMyDesktop</strong> para Linux.</p>
]]></content:encoded>
			<wfw:commentRss>http://programe.me/alternativa-ao-cron-jobs-em-php/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Exceptions. Pois nem tudo é perfeito</title>
		<link>http://programe.me/exceptions-pois-nem-tudo-e-perfeito/</link>
		<comments>http://programe.me/exceptions-pois-nem-tudo-e-perfeito/#comments</comments>
		<pubDate>Sun, 15 Mar 2009 14:44:10 +0000</pubDate>
		<dc:creator>hlegius</dc:creator>
				<category><![CDATA[Desenvolvimento]]></category>
		<category><![CDATA[Featured Articles]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Segurança]]></category>

		<guid isPermaLink="false">http://www.hlegius.pro.br/?p=313</guid>
		<description><![CDATA[Salve ! Pense numa rotina que desenvolveu. Qualquer uma ! Agora tente se recordar de quantas formas ela poderia ser quebrada pelo usuário, gerando assim algo inexperado na sua aplicação fazendo com que você retornasse um erro para o cliente. E qual é a forma que você utiliza para retornar estes erros ? Veja, eu [...]]]></description>
			<content:encoded><![CDATA[<p>Salve !</p>
<p>Pense numa rotina que desenvolveu. Qualquer uma ! Agora tente se recordar de quantas formas ela poderia ser quebrada pelo usuário, gerando assim algo inexperado na sua aplicação fazendo com que você retornasse um erro para o cliente.</p>
<p>E qual é a forma que você utiliza para retornar estes erros ? Veja, eu posso ajudar a recordar você:</p>
<div class="igBar"><span id="lcode-9"><a href="#" onclick="javascript:showPlainTxt('code-9'); return false;">PLAIN TEXT</a></span></div>
<div class="syntax_hilite"><span class="langName">CODE:</span>
<div id="code-9">
<div class="code">
<ol>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&lt;?php</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">function foobar<span style="color:#006600; font-weight:bold;">&#40;</span>$nome<span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">&#123;</span></div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp;if <span style="color:#006600; font-weight:bold;">&#40;</span>strlen<span style="color:#006600; font-weight:bold;">&#40;</span>$nome<span style="color:#006600; font-weight:bold;">&#41;</span> &lt;<span style="color:#800000;color:#800000;">3</span><span style="color:#006600; font-weight:bold;">&#41;</span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return -<span style="color:#800000;color:#800000;">1</span>;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp;if <span style="color:#006600; font-weight:bold;">&#40;</span>strpos<span style="color:#006600; font-weight:bold;">&#40;</span>$nome,<span style="color:#CC0000;">"foo"</span><span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#41;</span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return -<span style="color:#800000;color:#800000;">2</span>;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp;echo $nome;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp;return <span style="color:#800000;color:#800000;">0</span>;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color:#006600; font-weight:bold;">&#125;</span></div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">?&gt; </div>
</li>
</ol>
</div>
</div>
</div>
<p></p>
<p>Com isso lá na sua Action você fica fazendo malabarismo para encontrar o erro retornado e gerar a mensagem para o usuário. Não demorará muito para você criar sua tabela de erro:</p>
<ul>
<li>-1 para erros de entrada</li>
<li>-2 para erros de máscara</li>
<li>-3 para calcúlos errados</li>
<li>-4 para usuário não logado</li>
<li>-5 ....</li>
<li>-7634 ....</li>
</ul>
<p>Realmente, bem simples assim né ? Só consultar a tabela e mandar bala.</p>
<p>Eu realmente não entendo o motivo de muitos não utilizarem a<a href="http://br.php.net/exception" target="_blank"> classe nativa de exceções do PHP</a>. É simples, é funcional e<em> de grátis</em> você não precisa montar sua tabelinha de códigos de erro.</p>
<p>Veja o mesmo código reescrito utilizando a tal classe:</p>
<div class="igBar"><span id="lcode-10"><a href="#" onclick="javascript:showPlainTxt('code-10'); return false;">PLAIN TEXT</a></span></div>
<div class="syntax_hilite"><span class="langName">CODE:</span>
<div id="code-10">
<div class="code">
<ol>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&lt;?php</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">function foobar<span style="color:#006600; font-weight:bold;">&#40;</span>$nome<span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">&#123;</span></div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp;if <span style="color:#006600; font-weight:bold;">&#40;</span>strlen<span style="color:#006600; font-weight:bold;">&#40;</span>$nome<span style="color:#006600; font-weight:bold;">&#41;</span> &lt;<span style="color:#800000;color:#800000;">3</span><span style="color:#006600; font-weight:bold;">&#41;</span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;throw new Exception <span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0000;">"O nome não é válido !"</span><span style="color:#006600; font-weight:bold;">&#41;</span>;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp;if <span style="color:#006600; font-weight:bold;">&#40;</span>strpos<span style="color:#006600; font-weight:bold;">&#40;</span>$nome,<span style="color:#CC0000;">"foo"</span><span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#41;</span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp; &nbsp; throw new Exception<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0000;">"O nome precisa conter foo, cara !"</span><span style="color:#006600; font-weight:bold;">&#41;</span>;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp;echo $nome;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color:#006600; font-weight:bold;">&#125;</span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">?&gt; </div>
</li>
</ol>
</div>
</div>
</div>
<p></p>
<p>Com isso na sua Action, simplesmente:</p>
<div class="igBar"><span id="lcode-11"><a href="#" onclick="javascript:showPlainTxt('code-11'); return false;">PLAIN TEXT</a></span></div>
<div class="syntax_hilite"><span class="langName">CODE:</span>
<div id="code-11">
<div class="code">
<ol>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&lt;?php</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">include <span style="color:#CC0000;">"function_foobar.php"</span>;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">try <span style="color:#006600; font-weight:bold;">&#123;</span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; foobar<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0000;">"ab"</span><span style="color:#006600; font-weight:bold;">&#41;</span>;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color:#006600; font-weight:bold;">&#125;</span> catch <span style="color:#006600; font-weight:bold;">&#40;</span>Exception $e<span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">&#123;</span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; $var_template_sem_merchan_pro_smarty-&gt;<span style="">assign</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0000;">'retorno_de_erro'</span>,$e-&gt;<span style="">getMessage</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#41;</span>;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color:#006600; font-weight:bold;">&#125;</span> </div>
</li>
</ol>
</div>
</div>
</div>
<p></p>
<p>Assim, você pode ter 1, 2, 3, <em>n</em> mensagens de erro em <em>n</em> camadas da aplicação sem a necessidade de se preocupar em tratar uma a uma também na Action. Fica ultra-transparente na Action além de economizar seus dedos refazendo coisas que já estavam prontas camadas a dentro.</p>
<p><strong>Nota</strong>: Não esqueça disso <strong>nunca</strong> : <span style="color: #ff0000;">jamais</span> lance como exception uma mensagem de erro do PHP. Isso é feio - porque vem em inglês -, você será xingado por 3 gerações futuras de programadores além de permitir que os usuários vejam detalhes sobre sua aplicação.</p>
<h5>Como detectar os erros sem lança-los ao usuário ?</h5>
<p>Bem simples. Persista-os - eita mania - em arquivos de log. Mas calma, antes de sair criando algo com fopen(), leia isto: o PHP também traz o cara que salva - persiste - erros ! Ah sim, o PHP é excelente eu sei. Voltando ao exemplo...</p>
<p>
<div class="igBar"><span id="lcode-12"><a href="#" onclick="javascript:showPlainTxt('code-12'); return false;">PLAIN TEXT</a></span></div>
<div class="syntax_hilite"><span class="langName">CODE:</span>
<div id="code-12">
<div class="code">
<ol>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&lt;?php</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">function foobar<span style="color:#006600; font-weight:bold;">&#40;</span>$nome<span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">&#123;</span></div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp;if <span style="color:#006600; font-weight:bold;">&#40;</span>strlen<span style="color:#006600; font-weight:bold;">&#40;</span>$nome<span style="color:#006600; font-weight:bold;">&#41;</span> &lt;<span style="color:#800000;color:#800000;">3</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">&#123;</span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;error_log<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0000;">"O cara forneceu "</span>. $nome . <span style="color:#CC0000;">" e isto é inválido <span style="color:#000099; font-weight:bold;">\n</span>"</span>, <span style="color:#800000;color:#800000;">3</span>, <span style="color:#CC0000;">"seu_arquivo_de_log.txt"</span><span style="color:#006600; font-weight:bold;">&#41;</span>;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;throw new Exception <span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0000;">"O nome não é válido !"</span><span style="color:#006600; font-weight:bold;">&#41;</span>;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp;<span style="color:#006600; font-weight:bold;">&#125;</span></div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp;if <span style="color:#006600; font-weight:bold;">&#40;</span>strpos<span style="color:#006600; font-weight:bold;">&#40;</span>$nome,<span style="color:#CC0000;">"foo"</span><span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">&#123;</span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp; &nbsp; error_log<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0000;">"O cara forneceu "</span>. $nome . <span style="color:#CC0000;">" porém sem o foo !<span style="color:#000099; font-weight:bold;">\n</span>"</span>, <span style="color:#800000;color:#800000;">3</span>, <span style="color:#CC0000;">"seu_arquivo_de_log.txt"</span><span style="color:#006600; font-weight:bold;">&#41;</span>;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp; &nbsp; <span style="color:#FF9933; font-style:italic;">// #notamental não há motivos para logar &quot;erros&quot; deste tipo. Estou apenas ilustrando seu funcionamento <img src='http://programe.me/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp; &nbsp;throw new Exception<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0000;">"O nome precisa conter foo, cara !"</span><span style="color:#006600; font-weight:bold;">&#41;</span>;</div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; <span style="color:#006600; font-weight:bold;">&#125;</span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; </div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; echo $nome;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color:#006600; font-weight:bold;">&#125;</span></div>
</li>
<li style="font-family: 'Courier New', Courier, monospace; color: black; font-weight: normal; font-style: normal;color:#3A6A8B;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">?&gt; </div>
</li>
</ol>
</div>
</div>
</div>
<p></p>
<p>Sim, ele, o <a href="http://br.php.net/error_log" target="_blank">error_log()</a> salva o log para ti. E pior, digo, melhor: caso queira ele pode enviar a notificação no seu e-mail. Certo, em boa parte dos casos isto definitivamente não é uma boa ideia. Mas pode ser útil algum dia, penso.</p>
<p>Resumo do dia: use ao máximo as <a href="http://br.php.net/exception" target="_blank">Exceptions</a> e as <a href="http://br.php.net/manual/pt_BR/ref.errorfunc.php" target="_blank">funções para tratamento de erros do php</a> .</p>
]]></content:encoded>
			<wfw:commentRss>http://programe.me/exceptions-pois-nem-tudo-e-perfeito/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

