<?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; OOP e Patterns</title>
	<atom:link href="http://www.hlegius.pro.br/category/oop/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.hlegius.pro.br</link>
	<description>programação, desenvolvimento, tecnologia e muito o que contar.</description>
	<lastBuildDate>Tue, 22 Jun 2010 15:19:29 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.9.1</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Eu uso estático porque é mais rápido.</title>
		<link>http://www.hlegius.pro.br/eu-uso-estatico-porque-e-mais-rapido/</link>
		<comments>http://www.hlegius.pro.br/eu-uso-estatico-porque-e-mais-rapido/#comments</comments>
		<pubDate>Sun, 14 Feb 2010 14:04:04 +0000</pubDate>
		<dc:creator>hlegius</dc:creator>
				<category><![CDATA[Arquitetura]]></category>
		<category><![CDATA[Featured Articles]]></category>
		<category><![CDATA[OOP e Patterns]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[developer]]></category>
		<category><![CDATA[teoria]]></category>

		<guid isPermaLink="false">http://www.hlegius.pro.br/?p=488</guid>
		<description><![CDATA[Ouvi e já pude ler isto não uma, nem duas, mas sim diversas vezes. Argumentação padrão de quem defende uma &#8220;Orientação à Objetos mais estática&#8221; &#8211; se é que podemos chamar isso de OO.
Vejamos um exemplo nada científico que fiz:
Criei os seguintes exemplos:

&#60;?php
class Estatico {

    public static function fazAlgumaCoisa() {
   [...]]]></description>
			<content:encoded><![CDATA[<p>Ouvi e já pude ler isto não uma, nem duas, mas sim diversas vezes. Argumentação padrão de quem defende uma &#8220;Orientação à Objetos mais estática&#8221; &#8211; se é que podemos chamar isso de OO.</p>
<p>Vejamos um exemplo nada científico que fiz:</p>
<p>Criei os seguintes exemplos:</p>
<p><code></p>
<pre>&lt;?php
class Estatico {

    public static function fazAlgumaCoisa() {
        $i = 0;
        while ($i &lt; 10000) {
           echo Estatico::outraCoisa();
           $i++;
        }
    }

    public static function outraCoisa() {
        return "Conteúdo";
    }
}

Estatico::fazAlgumaCoisa();</pre>
<p></code></p>
<p><code></p>
<pre>&lt;?php
class Instancia {

    public function fazAlgumaCoisa() {
        $i = 0;
        while ($i &lt; 10000) {
            echo $this-&gt;outraCoisa();
            $i++;
        }
    }

    public function outraCoisa() {
        return "Conteúdo";
    }
}
$objInstancia = new Instancia();
$objInstancia-&gt;fazAlgumaCoisa();</pre>
<p></code></p>
<p>Os resultados após rodar quatro vezes cada foram:</p>
<p><a href="http://www.hlegius.pro.br/wp-content/uploads/2010/02/estatico.png"><img class="aligncenter size-medium wp-image-491" title="Chamadas estáticas em PHP" src="http://www.hlegius.pro.br/wp-content/uploads/2010/02/estatico-300x68.png" alt="" width="300" height="68" /></a></p>
<p style="text-align: center;"><a href="http://www.hlegius.pro.br/wp-content/uploads/2010/02/instancia.png"><img class="aligncenter" title="Chamada em instância em PHP" src="http://www.hlegius.pro.br/wp-content/uploads/2010/02/instancia-300x66.png" alt="" width="300" height="66" /></a></p>
<p>Ou seja: <strong>91.09 ms para o estático</strong> contra <strong>90.07 para a versão non-static</strong>. Obviamente foi apenas um teste sem qualquer relevância, pois rodei em minha máquina pessoal com várias outras aplicações rodando em background. É perceptível porém, que a diferença não é absurda que compense o uso de estático por este motivo.</p>
<p>Deixando a questão de &#8220;performance&#8221; de lado, partimos para questões arquitetônicas:</p>
<ul>
<li>Identidade</li>
<li>SoC &#8211; Separation of Concerns (Principio de Separação das Responsabilidades)</li>
<li>Encapsulamento</li>
<li>Estado</li>
<li>DRY &#8211; Don&#8217;t Repeat Yourself</li>
<li>Associações &#8211; sejam elas composições ou agregações</li>
</ul>
<p>Ao perder Identidade e Estado as possibilidades daquele método &#8211; ou da classe inteira, caso use estático em tudo &#8211; tem o leque de utilidade reduzido para:</p>
<ul>
<li>Service</li>
<li>Facade</li>
<li>Factory</li>
<li>Helpers &#8211; no âmbito de serem apenas funções que realizam determinada tarefa na aplicação sem qualquer valor ao Domínio</li>
</ul>
<p>Com isso, perdemos também o Princípio de Separação das Responsabilidades, ou seja, a classe perde o controle sobre a integridade dos dados que ela deveria controlar e proteger contra acesso ou alteração indevidos.</p>
<p>Listei o DRY também por um motivo simples: com métodos estáticos, perdemos a grande chance de usar as variáveis de instância da classe à favor da mesma. Exemplo:</p>
<p><code></p>
<pre>class UsuarioEstatico {

    public static function login($usuario, $senha) {
        // valida o usuário e zaz
        $autenticador = new Autenticador();
        $autenticador-&gt;autentica($usuario, $senha);
    }

    public static function logout($usuario) {
        // verifica se a sessao está aberta
        $autenticador = new Autenticador();
        $autenticador-&gt;fechaSessaoPara($usuario);
    }
}</pre>
<p></code></p>
<p><code></p>
<pre>class Usuario implements Autenticavel {
    private $autenticador;

    public function __construct($usuario, $senha) {
        // manipula os dados de entrada
        $this-&gt;autenticador = new Autenticador($this);
    }

    public function login() {
        return $this-&gt;autenticador-&gt;autentica();
    }

    public function logout() {
        return $this-&gt;autenticador-&gt;fechaSessao();
    }
}</pre>
<p></code></p>
<p>Repare no modelo estático: foi necessário instanciar o antenticador por duas vezes em pontos diferentes. Opa, repetiu ! Mesmo que o autenticador fosse estático, teriamos duplicação, pois teriamos que certificar que o usuário existe e tudo mais. Isso porque não comentei como ficaria o lado cliente dessa implementação estática. O cliente &#8211; seja Controller, WebService ou qualquer classe em outra camada no domínio &#8211; teria que conhecer muita coisa sobre implementação dessa classe para poder manipulá-la.</p>
<p>Como bônus, repare que perdemos neste caso também o Polimorfismo, uma vez que eu poderia ter esse Autenticador() como base de autenticação para qualquer tipo (Usuário, Funcionário, Gerência, Administradores&#8230;)</p>
<p>O uso de métodos ou funções &#8211; sim, há diferença &#8211; estáticas pode ser bem-vindo nos itens já enumerados. Alguns developers porém, ainda que nestes casos são contra o uso por achar a ideia estática demasiadamente anti-oo.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hlegius.pro.br/eu-uso-estatico-porque-e-mais-rapido/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>O manual, por favor !</title>
		<link>http://www.hlegius.pro.br/o-manual-por-favor/</link>
		<comments>http://www.hlegius.pro.br/o-manual-por-favor/#comments</comments>
		<pubDate>Tue, 24 Feb 2009 00:44:14 +0000</pubDate>
		<dc:creator>hlegius</dc:creator>
				<category><![CDATA[Featured Articles]]></category>
		<category><![CDATA[OOP e Patterns]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[developer]]></category>
		<category><![CDATA[Programação]]></category>

		<guid isPermaLink="false">http://www.hlegius.pro.br/o-manual-por-favor/</guid>
		<description><![CDATA[É fato que ninguém nasce sabendo. Fato também que para evoluirmos é bem interessante ler, além de entender, saber separar as coisas e etc., mas a base é a leitura. A todo momento o pessoal fala isso nos fóruns: "leia isto, leia aquilo. Nossa, isso aqui é referência neste assunto".
Vamos centrar mais no "nosso" mundo: [...]]]></description>
			<content:encoded><![CDATA[<p>É fato que ninguém nasce sabendo. Fato também que para evoluirmos é bem interessante ler, além de entender, saber separar as coisas e etc., mas a base é a leitura. A todo momento o pessoal fala isso nos fóruns: "leia isto, leia aquilo. Nossa, isso aqui é referência <em>neste</em> assunto".<br />
Vamos centrar mais no "nosso" mundo: você não sabe PHP, mas está interessado em aprender. O que você vai em busca imediatamente ? Referências, manuais e "apostilas", certo ? Seu objetivo com isto é aprender/conhecer algo que ainda não conhece.<br />
Qual é o pré-requisito para tal ? Saber ler, óbvio ! Por mais expressivo que um <strong>str_replace("foo","bar", $string);</strong> possa parecer, você precisa realmente entender o que acontece ou deixa de acontecer naquela parte.</p>
<p>Você deve estar se perguntando: aonde você quer chegar ?<br />
Simples: se tudo isso que citei é muito óbvio para você, meus parabéns ! Você deve ser um profissional preocupado com a documentação !</p>
<p>Sim, da mesma forma que você precisou ler para entender como funciona a API de reflexão nativa do PHP, o seu colega de projeto precisará ler a documentação daquele Webservice que você fez para o projeto.<br />
Partindo da minha analogia, seu amigo precisa ter como pré-requisito: saber ler e conhecimentos em PHP para poder implementar x)</p>
<p>Pensamento óbvio o meu, claro, claro que sim ! Mas pensa aí rapidinho: quantos códigos nos últimos tempos você pegou totalmente sem documentação, isso sem falar em outros aspectos, como qualidade interna e <em>blablablá</em> [no bom sentido] que profissionais aptos a escrever <em>grandes softwares</em> fazem [Se essa última palavra não faz sentido para você, recomendo ler <a href="http://www.amazon.com/Head-First-Object-Oriented-Analysis-Design/dp/0596008678/ref=pd_bbs_sr_6?ie=UTF8&#038;s=books&#038;qid=1235432837&#038;sr=8-6">este livro</a> para entender o que é um <em>grande software</em>]</p>
<p>Aquela velha <em>estória</em> de que quem manja mesmo lê o código <em>e já era</em> caiu por terra. Para um formmail até que pode ser, mas aplicações modularizadas com um modelo bem definido e aplicado e uma chuva de classes trabalhando neste modelo precisa muito mais do que uma simples leitura de código. O mínimo necessário são os comentários do tipo <a href="http://en.wikipedia.org/wiki/PHPDoc#DocBlock"><strong>DocBlock</strong></a> além dos comentários inline e por fim e não menos importante Classes, atributos, comportamentos, variáveis locais e constantes com nomes reais do que fazem, recebem ou são.</p>
<div class="igBar"><span id="lcode-2"><a href="#" onclick="javascript:showPlainTxt('code-2'); return false;">PLAIN TEXT</a></span></div>
<div class="syntax_hilite"><span class="langName">CODE:</span>
<div id="code-2">
<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;"> * Pretend this is a file</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;"> * Page-level DocBlock is here because it is the first DocBlock</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;"> * in the file, and contains a @package tag</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;"> * @package pagepackage</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;">&nbsp;define<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC0000;">"almost"</span>,<span style="color:#CC0000;">"Now the Page-level DocBlock is for the page, and the&nbsp; Define has no docblock"</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;">?&gt; </div>
</li>
</ol>
</div>
</div>
</div>
<p>
Isto é um <strong>DocBlock</strong> <a href="http://en.wikipedia.org/wiki/PHPDoc#Page_Level_DocBlocks">retirado daqui</a> !</p>
<p>Para fechar, eu recomendo fortemente que você caso não conheça, dê uma boa olhada e claro, <a href="http://phpdoc.org/">passe lá</a> e pegue sua cópia gratuitamente dele, o <strong>PHPDoc</strong> em <a href="http://phpdoc.org/">PHPdoc.org</a>. Não vou me prolongar em explicar o que ele tem ou o que faz. O site está lá completinho.</p>
<p>Veja você mesmo <a href="http://manual.phpdoc.org/HTMLSmartyConverter/HandS/Smarty/Smarty.html">neste exemplo</a> online onde foi gerado o manual do Smarty Template. Ele por si só já diz tudo. Agora é com você <img src='http://www.hlegius.pro.br/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.hlegius.pro.br/o-manual-por-favor/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Sobrecarga em PHP com __get() e __set()</title>
		<link>http://www.hlegius.pro.br/sobrecarga-em-php-com-__get-e-__set/</link>
		<comments>http://www.hlegius.pro.br/sobrecarga-em-php-com-__get-e-__set/#comments</comments>
		<pubDate>Wed, 16 Jul 2008 21:07:35 +0000</pubDate>
		<dc:creator>hlegius</dc:creator>
				<category><![CDATA[OOP e Patterns]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programação]]></category>
		<category><![CDATA[sobrecarga]]></category>

		<guid isPermaLink="false">http://www.hlegius.pro.br/sobrecarga-em-php-com-__get-e-__set/</guid>
		<description><![CDATA[Aloha!
O papo agora é sobre a sobrecarga do PHP, mais precisamente 2 deles que são: __get() e __set().
Eu particularmente já os conhecia, mas somente essa semana resolvi fazer uns testes e ver suas utilidades e limitações.
Bom, chega de papo e vamos ao source:
Controller.php
PLAIN TEXT
PHP:




&#60;?php


&#160;


&#160;


final class Controller &#123;


&#160; &#160; 


&#160; &#160; static public function Adiciona&#40;Array $Produto&#41; [...]]]></description>
			<content:encoded><![CDATA[<p>Aloha!</p>
<p>O papo agora é sobre a <a href="http://br.php.net/manual/pt_BR/language.oop5.overloading.php">sobrecarga do PHP</a>, mais precisamente 2 deles que são: __get() e __set().</p>
<p>Eu particularmente já os conhecia, mas somente essa semana resolvi fazer uns testes e ver suas utilidades e limitações.</p>
<p>Bom, chega de papo e vamos ao source:</p>
<p>Controller.php</p>
<div class="igBar"><span id="lphp-11"><a href="#" onclick="javascript:showPlainTxt('php-11'); return false;">PLAIN TEXT</a></span></div>
<div class="syntax_hilite"><span class="langName">PHP:</span>
<div id="php-11">
<div class="php">
<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;"><span style="color:#000000; font-weight:bold;">&lt;?php</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;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">final <span style="color:#000000; font-weight:bold;">class</span> Controller <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; </div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; <a href="http://www.php.net/static"><span style="color:#000066;">static</span></a> public <span style="color:#000000; font-weight:bold;">function</span> Adiciona<span style="color:#006600; font-weight:bold;">&#40;</span><a href="http://www.php.net/array"><span style="color:#000066;">Array</span></a> <span style="color:#0000FF;">$Produto</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; <span style="color:#616100;">if</span><span style="color:#006600; font-weight:bold;">&#40;</span>!<a href="http://www.php.net/is_numeric"><span style="color:#000066;">is_numeric</span></a><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#0000FF;">$Produto</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#CC66CC;color:#800000;">0</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#616100;">return</span> <span style="color:#000000; font-weight:bold;">false</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; </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:#0000FF;">$ProdutoModelo</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#FF0000;">'Id'</span><span style="color:#006600; font-weight:bold;">&#93;</span> &nbsp; &nbsp;= <span style="color:#0000FF;">$Produto</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#CC66CC;color:#800000;">0</span><span style="color:#006600; font-weight:bold;">&#93;</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:#0000FF;">$ProdutoModelo</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#FF0000;">'Nome'</span><span style="color:#006600; font-weight:bold;">&#93;</span>&nbsp; = <span style="color:#0000FF;">$Produto</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#CC66CC;color:#800000;">1</span><span style="color:#006600; font-weight:bold;">&#93;</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:#0000FF;">$ProdutoModelo</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#FF0000;">'Idade'</span><span style="color:#006600; font-weight:bold;">&#93;</span>&nbsp;= <span style="color:#0000FF;">$Produto</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#CC66CC;color:#800000;">2</span><span style="color:#006600; font-weight:bold;">&#93;</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; </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:#0000FF;">$modelo</span> = <span style="color:#000000; font-weight:bold;">new</span> Modelo<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#0000FF;">$ProdutoModelo</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; &nbsp; <span style="color:#FF9933; font-style:italic;">//$modelo-&gt;Id = 2; // Sobrescreve o $ProdutoModelo['Id']</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; </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:#616100;">return</span> <span style="color:#0000FF;">$modelo</span>-&gt;<span style="color:#006600;">Adiciona</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">&#41;</span>; <span style="color:#FF9933; font-style:italic;">// O novo broda adicionado...</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;"><span style="color:#006600; font-weight:bold;">&#125;</span> </div>
</li>
</ol>
</div>
</div>
</div>
<p></p>
<p>Partindo do princípio que você tenha noções básicas de MVC, acima é nossa Controller.php. Ele recebe os dados vindo do usuário e indica para qual Modelo(Model) será derecionado os dados para aplicarmos a regra de negócio.</p>
<p>Falando em Modelo...</p>
<div class="igBar"><span id="lphp-12"><a href="#" onclick="javascript:showPlainTxt('php-12'); return false;">PLAIN TEXT</a></span></div>
<div class="syntax_hilite"><span class="langName">PHP:</span>
<div id="php-12">
<div class="php">
<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;"><span style="color:#000000; font-weight:bold;">&lt;?php</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;"><span style="color:#000000; font-weight:bold;">class</span> Modelo <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; private <span style="color:#0000FF;">$Id</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; private <span style="color:#0000FF;">$Nome</span>;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; private <span style="color:#0000FF;">$Idade</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; </div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; public <span style="color:#000000; font-weight:bold;">function</span> __construct<span style="color:#006600; font-weight:bold;">&#40;</span><a href="http://www.php.net/array"><span style="color:#000066;">Array</span></a> <span style="color:#0000FF;">$params</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; <span style="color:#616100;">if</span><span style="color:#006600; font-weight:bold;">&#40;</span>!<span style="color:#0000FF;">$params</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#616100;">return</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:#616100;">foreach</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#0000FF;">$params</span> <span style="color:#616100;">as</span> <span style="color:#0000FF;">$pname</span> =&gt; <span style="color:#0000FF;">$pvalue</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; &nbsp; &nbsp; <span style="color:#0000FF;">$this</span>-&gt;<span style="color:#0000FF;">$pname</span> = <span style="color:#0000FF;">$pvalue</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:#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; <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; <span style="color:#008000;">/**</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;">&nbsp; &nbsp;&nbsp; * Adiciona um usuário e tal.</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;">&nbsp; &nbsp;&nbsp; * </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;">&nbsp; &nbsp;&nbsp; * @return string || boolean</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;">&nbsp; &nbsp;&nbsp; */</span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; public <span style="color:#000000; font-weight:bold;">function</span> Adiciona<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;">&#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; <span style="color:#FF9933; font-style:italic;">// Regra de negócio aqui, ó!</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:#616100;">if</span><span style="color:#006600; font-weight:bold;">&#40;</span>!<span style="color:#0000FF;">$this</span>-&gt;<span style="color:#006600;">Id</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#616100;">return</span> <span style="color:#000000; font-weight:bold;">false</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:#0000FF;">$this</span>-&gt;<span style="color:#006600;">Id</span> = <span style="color:#006600; font-weight:bold;">&#40;</span>int<span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#0000FF;">$this</span>-&gt;<span style="color:#006600;">Id</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; </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; 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; &nbsp; &nbsp; &nbsp; &nbsp; Dao::<span style="color:#006600;">Adiciona</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#0000FF;">$this</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; &nbsp; <span style="color:#616100;">return</span> <span style="color:#FF0000;">'Usuário cadastrado com número: '</span> . <span style="color:#0000FF;">$this</span>-&gt;<span style="color:#006600;">Id</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:#006600; font-weight:bold;">&#125;</span>catch<span style="color:#006600; font-weight:bold;">&#40;</span>Exception <span style="color:#0000FF;">$e</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; &nbsp; &nbsp; <span style="color:#FF9933; font-style:italic;">// Salva Exception no log e tal, e exibe uma mensagem ao usuário</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; &nbsp; <span style="color:#616100;">return</span> <span style="color:#FF0000;">"Não foi possível Adicionar! =~"</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:#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; <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; </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; <span style="color:#008000;">/* setters e getters mágicos */</span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; public <span style="color:#000000; font-weight:bold;">function</span> __set<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#0000FF;">$pname</span>, <span style="color:#0000FF;">$pvalue</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">&#123;</span> <span style="color:#0000FF;">$this</span>-&gt;<span style="color:#0000FF;">$pname</span> = <span style="color:#0000FF;">$pvalue</span>; <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; public <span style="color:#000000; font-weight:bold;">function</span> __get<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#0000FF;">$pname</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">&#123;</span> <span style="color:#616100;">return</span> <span style="color:#0000FF;">$this</span>-&gt;<span style="color:#0000FF;">$pname</span>; <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;"><span style="color:#006600; font-weight:bold;">&#125;</span> </div>
</li>
</ol>
</div>
</div>
</div>
<p></p>
<p>O mais importante de tudo é isso aqui, ó:</p>
<div class="igBar"><span id="lphp-13"><a href="#" onclick="javascript:showPlainTxt('php-13'); return false;">PLAIN TEXT</a></span></div>
<div class="syntax_hilite"><span class="langName">PHP:</span>
<div id="php-13">
<div class="php">
<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;">public <span style="color:#000000; font-weight:bold;">function</span> __set<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#0000FF;">$pname</span>, <span style="color:#0000FF;">$pvalue</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">&#123;</span> <span style="color:#0000FF;">$this</span>-&gt;<span style="color:#0000FF;">$pname</span> = <span style="color:#0000FF;">$pvalue</span>; <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; &nbsp; &nbsp; public <span style="color:#000000; font-weight:bold;">function</span> __get<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#0000FF;">$pname</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">&#123;</span> <span style="color:#616100;">return</span> <span style="color:#0000FF;">$this</span>-&gt;<span style="color:#0000FF;">$pname</span>; <span style="color:#006600; font-weight:bold;">&#125;</span> </div>
</li>
</ol>
</div>
</div>
</div>
<p></p>
<p>Setando isto, assim que eu chamar: <strong>$metodo->Id = 2</strong> meu atributo Id do objeto Modelo passará a ter o valor 2. Caso eu simplesmente rode um <strong>$metodo->Id;</strong> eu poderei resgatar o valor passado ao atributo.</p>
<p>Para quem ainda não viu os atributos da class Metodo, aqui estão eles:</p>
<div class="igBar"><span id="lphp-14"><a href="#" onclick="javascript:showPlainTxt('php-14'); return false;">PLAIN TEXT</a></span></div>
<div class="syntax_hilite"><span class="langName">PHP:</span>
<div id="php-14">
<div class="php">
<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;">private <span style="color:#0000FF;">$Id</span>;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; private <span style="color:#0000FF;">$Nome</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; private <span style="color:#0000FF;">$Idade</span>; </div>
</li>
</ol>
</div>
</div>
</div>
<p></p>
<p>Note que eu descrevi no Método construtor da classe uma iteração foreach para correr o $Params em busca de setters para setar. Obviamente se passarmos um Atributo não existente, um erro será lançado, para tanto será necessário um tratamento do dado inserido para garantir que o atributo realmente existe.</p>
<p>Como descrevemos a Dao ali no método <strong>Adiciona()</strong> da classe Modelo, coloco seu conteúdo abaixo:</p>
<div class="igBar"><span id="lphp-15"><a href="#" onclick="javascript:showPlainTxt('php-15'); return false;">PLAIN TEXT</a></span></div>
<div class="syntax_hilite"><span class="langName">PHP:</span>
<div id="php-15">
<div class="php">
<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;"><span style="color:#000000; font-weight:bold;">&lt;?php</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;"><span style="color:#000000; font-weight:bold;">class</span> Dao <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; </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; <a href="http://www.php.net/static"><span style="color:#000066;">static</span></a> public <span style="color:#000000; font-weight:bold;">function</span> Adiciona<span style="color:#006600; font-weight:bold;">&#40;</span>Modelo <span style="color:#0000FF;">$mod</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; <span style="color:#FF9933; font-style:italic;">// faz alguma coisa no banco e tal.</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:#616100;">return</span> <span style="color:#0000FF;">$mod</span>-&gt;<span style="color:#006600;">Id</span>; <span style="color:#FF9933; font-style:italic;">// Retorna o novo id cadastrado, por exemplo</span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<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-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>Então, se eu criasse a seguinte estrutura:</p>
<div class="igBar"><span id="lphp-16"><a href="#" onclick="javascript:showPlainTxt('php-16'); return false;">PLAIN TEXT</a></span></div>
<div class="syntax_hilite"><span class="langName">PHP:</span>
<div id="php-16">
<div class="php">
<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;"><span style="color:#000000; font-weight:bold;">&lt;?php</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;"><span style="color:#616100;">include_once</span> <span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#FF0000;">'Modelo.php'</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;"><span style="color:#616100;">include_once</span> <span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#FF0000;">'Controller.php'</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:#616100;">include_once</span> <span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#FF0000;">'Dao.php'</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;"><span style="color:#0000FF;">$ctrl</span> = <span style="color:#000000; font-weight:bold;">new</span> Controller<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; <a href="http://www.php.net/echo"><span style="color:#000066;">echo</span></a> <span style="color:#0000FF;">$ctrl</span>-&gt;<span style="color:#006600;">Adiciona</span><span style="color:#006600; font-weight:bold;">&#40;</span><a href="http://www.php.net/array"><span style="color:#000066;">array</span></a><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#CC66CC;color:#800000;">1</span>, <span style="color:#FF0000;">"Fulaninha"</span>, <span style="color:#CC66CC;color:#800000;">22</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;">&nbsp;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;"><span style="color:#000000; font-weight:bold;">?&gt;</span> </div>
</li>
</ol>
</div>
</div>
</div>
<p></p>
<p>Os três atributos (1, Fulaninha e 22) seriam passados à seus respectivos Atributos dentro da Classe Modelo, pois a Controller fez o tratamento desse Array passando os valores coerentes de acordo com a exigência da classe Modelo.</p>
<p><strong>Uma alternativa</strong> seria inutilizar esse método construtor __construct(Array $params) e chamar os valores direto, para isto, basta modificarmos nossa Controller que estará tudo resolvido:</p>
<div class="igBar"><span id="lphp-17"><a href="#" onclick="javascript:showPlainTxt('php-17'); return false;">PLAIN TEXT</a></span></div>
<div class="syntax_hilite"><span class="langName">PHP:</span>
<div id="php-17">
<div class="php">
<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;"><span style="color:#000000; font-weight:bold;">&lt;?php</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;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">final <span style="color:#000000; font-weight:bold;">class</span> Controller <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; </div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; <a href="http://www.php.net/static"><span style="color:#000066;">static</span></a> public <span style="color:#000000; font-weight:bold;">function</span> Adiciona<span style="color:#006600; font-weight:bold;">&#40;</span><a href="http://www.php.net/array"><span style="color:#000066;">Array</span></a> <span style="color:#0000FF;">$Produto</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; <span style="color:#616100;">if</span><span style="color:#006600; font-weight:bold;">&#40;</span>!<a href="http://www.php.net/is_numeric"><span style="color:#000066;">is_numeric</span></a><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#0000FF;">$Produto</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#CC66CC;color:#800000;">0</span><span style="color:#006600; font-weight:bold;">&#93;</span><span style="color:#006600; font-weight:bold;">&#41;</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#616100;">return</span> <span style="color:#000000; font-weight:bold;">false</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; </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:#0000FF;">$modelo</span> = <span style="color:#000000; font-weight:bold;">new</span> Modelo<span style="color:#006600; font-weight:bold;">&#40;</span><a href="http://www.php.net/array"><span style="color:#000066;">array</span></a><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-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color:#0000FF;">$modelo</span>-&gt;<span style="color:#006600;">Id</span> &nbsp; &nbsp; = <span style="color:#0000FF;">$Produto</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#CC66CC;color:#800000;">0</span><span style="color:#006600; font-weight:bold;">&#93;</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; &nbsp; <span style="color:#0000FF;">$modelo</span>-&gt;<span style="color:#006600;">Nome</span> &nbsp; = <span style="color:#0000FF;">$Produto</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#CC66CC;color:#800000;">1</span><span style="color:#006600; font-weight:bold;">&#93;</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; &nbsp; <span style="color:#0000FF;">$modelo</span>-&gt;<span style="color:#006600;">Idade</span>&nbsp; = <span style="color:#0000FF;">$Produto</span><span style="color:#006600; font-weight:bold;">&#91;</span><span style="color:#CC66CC;color:#800000;">2</span><span style="color:#006600; font-weight:bold;">&#93;</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:#616100;">return</span> <span style="color:#0000FF;">$modelo</span>-&gt;<span style="color:#006600;">Adiciona</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">&#41;</span>; <span style="color:#FF9933; font-style:italic;">// O novo broda adicionado...</span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<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-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>Pronto, não utilizamos mais o __construct() para popular nossos atributos.</p>
<p><strong>Desvantagens</strong><br />
Apesar de ser muito útil e facilitar muito a criação dos getters e setters das nossas aplicações, vale lembrar que essa forma deixa muito 'limitada' nosso controle ao gets e sets do objeto. Uma das limitações se dá quanto ao nome do método get/set que usando a sobrecarga, nos obriga a usar o mesmo nome do atributo criado na classe.<br />
Outro problema é quanto a atualização de nomes. Se eu precisar mudar o nome do atributo, terei que mudar em toda a extensão do código criado, Controllers, Daos e Views.</p>
<p><strong>Resumindo:</strong> Essa é uma ferramenta que pode lhe ajudar muito da mesma forma que pode te quebrar legal. Cabe você avaliar quando usá-la e quando usar o tradicional:</p>
<div class="igBar"><span id="lphp-18"><a href="#" onclick="javascript:showPlainTxt('php-18'); return false;">PLAIN TEXT</a></span></div>
<div class="syntax_hilite"><span class="langName">PHP:</span>
<div id="php-18">
<div class="php">
<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;"><span style="color:#000000; font-weight:bold;">&lt;?php</span></div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; public <span style="color:#000000; font-weight:bold;">function</span> setId<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#0000FF;">$i</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">&#123;</span> <span style="color:#0000FF;">$this</span>-&gt;<span style="color:#006600;">Id</span> = <span style="color:#0000FF;">$i</span>; <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; public <span style="color:#000000; font-weight:bold;">function</span> getId<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;">&#123;</span> <span style="color:#616100;">return</span> <span style="color:#0000FF;">$this</span>-&gt;<span style="color:#006600;">Id</span>; <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; public <span style="color:#000000; font-weight:bold;">function</span> setNome<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#0000FF;">$n</span><span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#006600; font-weight:bold;">&#123;</span> <span style="color:#0000FF;">$this</span>-&gt;<span style="color:#006600;">NomeCompleto</span> = <span style="color:#0000FF;">$n</span>; <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; public <span style="color:#000000; font-weight:bold;">function</span> getNome<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;">&#123;</span> <span style="color:#616100;">return</span> <span style="color:#0000FF;">$this</span>-&gt;<span style="color:#006600;">NomeCompleto</span>; <span style="color:#006600; font-weight:bold;">&#125;</span> </div>
</li>
</ol>
</div>
</div>
</div>
<p></p>
]]></content:encoded>
			<wfw:commentRss>http://www.hlegius.pro.br/sobrecarga-em-php-com-__get-e-__set/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Design Patterns e o PHP</title>
		<link>http://www.hlegius.pro.br/design-patterns-e-o-php/</link>
		<comments>http://www.hlegius.pro.br/design-patterns-e-o-php/#comments</comments>
		<pubDate>Thu, 08 Nov 2007 10:40:10 +0000</pubDate>
		<dc:creator>hlegius</dc:creator>
				<category><![CDATA[Desenvolvimento]]></category>
		<category><![CDATA[OOP e Patterns]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[artigos]]></category>
		<category><![CDATA[design patterns]]></category>
		<category><![CDATA[Programação]]></category>

		<guid isPermaLink="false">http://www.hlegius.pro.br/design-patterns-e-o-php/</guid>
		<description><![CDATA[Salve!
Quem já ouviu falar de design patterns e que programa em PHP ? Melhor: quem que programa em PHP e está utilizando qualquer uma das patterns mais conhecidas ?
Isso não é nada espantoso! Os programadores PHP em sua grande parcela ainda não acordaram para a nova realidade: código mais extensível e pensado. Nunca falei aqui, [...]]]></description>
			<content:encoded><![CDATA[<p>Salve!</p>
<p>Quem já ouviu falar de design patterns e que programa em PHP ? Melhor: quem que programa em PHP e está utilizando qualquer uma das patterns mais conhecidas ?</p>
<p>Isso não é nada espantoso! Os programadores PHP em sua grande parcela ainda não acordaram para a nova realidade: código mais extensível e pensado. Nunca falei aqui, mas acho que o PHP tem um defeito grave: ser super simples. Isso estragou, em partes a fama da linguagem.</p>
<p>Vamos a um exemplo: duelo. Java Vs PHP.</p>
<p>Java: Hello world no shell</p>
<div class="igBar"><span id="ljava-24"><a href="#" onclick="javascript:showPlainTxt('java-24'); return false;">PLAIN TEXT</a></span></div>
<div class="syntax_hilite"><span class="langName">JAVA:</span>
<div id="java-24">
<div class="java">
<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;"><span style="color: #000000; font-weight: bold;">class</span> HelloWorld <span style="color: #66cc66;">&#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;<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #993333;">static</span> <span style="color: #993333;">void</span> main<span style="color: #66cc66;">&#40;</span><a href="http://www.google.com/search?q=allinurl%3AString+java.sun.com&amp;bntl=1"><span style="color: #aaaadd; font-weight: bold;">String</span></a><span style="color: #66cc66;">&#91;</span><span style="color: #66cc66;">&#93;</span> args<span style="color: #66cc66;">&#41;</span> <span style="color: #66cc66;">&#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; &nbsp; <a href="http://www.google.com/search?q=allinurl%3ASystem+java.sun.com&amp;bntl=1"><span style="color: #aaaadd; font-weight: bold;">System</span></a>.<span style="color: #006600;">out</span>.<span style="color: #006600;">println</span><span style="color: #66cc66;">&#40;</span><span style="color: #ff0000;">"Hello World!"</span><span style="color: #66cc66;">&#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: #66cc66;">&#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;"><span style="color: #66cc66;">&#125;</span> </div>
</li>
</ol>
</div>
</div>
</div>
<p></p>
<p>PHP procedural</p>
<div class="igBar"><span id="lphp-25"><a href="#" onclick="javascript:showPlainTxt('php-25'); return false;">PLAIN TEXT</a></span></div>
<div class="syntax_hilite"><span class="langName">PHP:</span>
<div id="php-25">
<div class="php">
<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;"><a href="http://www.php.net/echo"><span style="color:#000066;">echo</span></a> <span style="color:#FF0000;">'Hello world'</span>; </div>
</li>
</ol>
</div>
</div>
</div>
<p></p>
<p>PHP O.O</p>
<div class="igBar"><span id="lphp-26"><a href="#" onclick="javascript:showPlainTxt('php-26'); return false;">PLAIN TEXT</a></span></div>
<div class="syntax_hilite"><span class="langName">PHP:</span>
<div id="php-26">
<div class="php">
<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;"><span style="color:#000000; font-weight:bold;">class</span> HelloWorld <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;public <span style="color:#000000; font-weight:bold;">function</span> __construct<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;">&#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; &nbsp;<a href="http://www.php.net/echo"><span style="color:#000066;">echo</span></a> <span style="color:#FF0000;">'HelloWorld'</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;"><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;"><span style="color:#0000FF;">$hw</span> = <span style="color:#000000; font-weight:bold;">new</span> HelloWorld<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#006600; font-weight:bold;">&#41;</span>; </div>
</li>
</ol>
</div>
</div>
</div>
<p></p>
<p>O que é mais fácil ? PHP ou Java ? PHP procedural ou PHP O.O ? Essa facilidade fez com que várias aplicações inseguras e mal pensadas infestassem a rede, causando uma rejeição do PHP por parte de vários Clientes e com isso, empresas de desenvolvimento de software. Isso é ruim para a linguagem, ruim para o profissional sério e ruim para o cliente que terá que pagar mais caro por uma tecnologia como o Java.</p>
<p>Hélio, tá, mas onde entra os design patterns nessa sua conversa mole ? Ok, até o momento eu tangenciei o tema, mas veja que para existir Pattern é ideal que haja Programação Orientada a objetos com tudo que temos direito.</p>
<p>Design patterns nada mais é que um conjunto de conceitos que visa auxiliar na resolução de um problema comum entre os programadores de verdade.</p>
<p><strong>E dale exemplos</strong></p>
<p><strong>MVC (Model View Control - Modelo Visualização Controle) ::</strong> essa Pattern foi desenvolvida para resolver o problema da lambança de códigos, ou seja, um arquivo faz tudo: conecta no banco, traz dados, exibe na tela, pega retorno do cliente, aplica regra de negócio e salva no banco.<br />
Imagine uma aplicação como E-commerce feita desta forma! Loucura hein! Falando em lambança, encontrei recentemente em um dos projetos que assumi, um arquivo <em>executa.php</em>. Já ouviu falar dele ? O "faz tudo" ? Não ? Assunto para outro post!</p>
<p>Então, como eu ia dizendo: para resolver o problema de manter tudo nas "costas" de uma mesma aplicação, foi pensado e desenvolvido esse <strong>modelo MVC</strong> onde a aplicação fica separada em camadas. Na camada mais baixa, fica o modelo, que faz a interação com o servidor de banco de dados, sistema de arquivos e etc.; Depois temos a classe que processa os dados recebidos pelo usuário e se passar por checagens simples é entregue a "Model"; e por fim, temos a View que nada mais é do que o HTML que o usuário vê, sem PHP, sem CSS sem Javascript misturado.</p>
<p>Criando um diagrama bobo temos:</p>
<blockquote><p>Banco de dados -> Model -> Controller -> View</p></blockquote>
<p><strong>View:</strong> Usuário clica no botão submit com o campo Nome preenchido.<br />
<strong>Controller </strong> recebe esse formulário. Verifica se o nome tá setado (sem checar seu valor). Setado ? Ok, manda para a model.<br />
<strong>Model</strong> recebe e aplica a regra de negócio: no exemplo, o nome precisa ter pelo menos 3 caracteres. Tem ? Ok, pega o poll de conexão com o banco de dados e salva.<br />
Retorna "true" para a <strong> Controller</strong> que exibe uma mensagem de "Sucesso" na <strong>View</strong></p>
<p><strong>DAO: (Data Access Object) </strong>:: Essa Pattern tem como objetivo separar a <em>Model</em> em dois: regra de negócio do acesso ao banco de dados. No nosso exemplo anterior, a <em>Usuario.php</em> receberia da <em>UsuarioController.php</em> o dado e a mesma aplicaria a regra de negócio. Após estar ok, a <em>Usuario.php</em> enviaria o status de "ok, pode gravar" para o UsuarioDao.php e este gravaria a informação no banco (verificando se o nome não existe por exemplo) e retornaria a informação de "true" para nosso <em>Usuario.php.</em><br />
Veja que ela tem como objetivo deixar a <em>Model</em> mais limpa e legível à manter regra de negócio e acesso ao banco tudo junto.</p>
<p><strong>Factory Pattern (Fábrica)</strong> :: tem por objetivo englobar vários recursos dentro de um mesmo método usando os blocos de condição "if" ou "switch". Exemplo:</p>
<div class="igBar"><span id="lphp-27"><a href="#" onclick="javascript:showPlainTxt('php-27'); return false;">PLAIN TEXT</a></span></div>
<div class="syntax_hilite"><span class="langName">PHP:</span>
<div id="php-27">
<div class="php">
<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;"><span style="color:#000000; font-weight:bold;">class</span> Usuario <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;public <span style="color:#000000; font-weight:bold;">function</span> Pesquisa<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;">&#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; &nbsp; <span style="color:#616100;">switch</span><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#0000FF;">$p</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; &nbsp; &nbsp; &nbsp;<span style="color:#616100;">case</span> <a href="http://www.php.net/is_numeric"><span style="color:#000066;">is_numeric</span></a><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#0000FF;">$p</span>-&gt;<span style="color:#006600;">Id</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; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color:#FF9933; font-style:italic;">// Faz a pesquisa tomando como base o ID do cliente</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; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color:#616100;">break</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; &nbsp; &nbsp; &nbsp;</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; &nbsp; &nbsp; &nbsp;<span style="color:#616100;">case</span> <span style="color:#006600; font-weight:bold;">&#40;</span><a href="http://www.php.net/strlen"><span style="color:#000066;">strlen</span></a><span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#0000FF;">$p</span>-&gt;<span style="color:#006600;">Nome</span><span style="color:#006600; font-weight:bold;">&#41;</span>&gt; <span style="color:#CC66CC;color:#800000;">3</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; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color:#FF9933; font-style:italic;">// Faz a pesquisa tomando como base o Nome do cliente</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; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color:#616100;">break</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; <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; &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;"><span style="color:#006600; font-weight:bold;">&#125;</span> </div>
</li>
</ol>
</div>
</div>
</div>
<p></p>
<p>Veja que no exemplo o método <em>Pesquisa()</em> é um só mas dependendo do tipo de informação que ele recebe, executa uma ação diferente. Isso é a <strong>Pattern Factory</strong>, novamente resolvendo outro problema usando conceitos simples. Uma outra forma de resolver o mesmo problema seria criando vários métodos<em> PesquisaId() PesquisaNome()</em>, porém, estariamos deixando de lado a Pattern Factory.</p>
<p><strong>Singleton ::</strong> essa Pattern tem como objetivo evitar que uma mesma variável, poll de conexão e etc., ocupe mais espaço na memória. Vamos a um exemplo:</p>
<p><a href='http://www.hlegius.pro.br/wp-content/uploads/2007/11/singleton.jpg' title='Singleton - Pattern'><img src='http://www.hlegius.pro.br/wp-content/uploads/2007/11/singleton.jpg' alt='Singleton - Pattern' /></a></p>
<p>No desenho que criei no Gimp, ao conectar com o banco é alocado certo endereço da memória para ele. Caso eu faça outra requisição de conexão, ao invés de alocar outro endereço de memória, ele vai usar o mesmo endereço. Pense em algo fixo. Posso fazer "n" requisições que ele sempre usará o mesmo espaço que foi alocado inicialmente.</p>
<p>A mágina está no <strong>public static $Con</strong>. Estou definindo que o <strong>$Con</strong> será estático.<br />
Abaixo, o script que está na imagem:</p>
<div class="igBar"><span id="lphp-28"><a href="#" onclick="javascript:showPlainTxt('php-28'); return false;">PLAIN TEXT</a></span></div>
<div class="syntax_hilite"><span class="langName">PHP:</span>
<div id="php-28">
<div class="php">
<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;"><span style="color:#000000; font-weight:bold;">&lt;?php</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;"><span style="color:#000000; font-weight:bold;">class</span> BancoDados <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;</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; public <a href="http://www.php.net/static"><span style="color:#000066;">static</span></a> <span style="color:#0000FF;">$Con</span> = <span style="color:#000000; font-weight:bold;">null</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; &nbsp; &nbsp;private <span style="color:#000000; font-weight:bold;">function</span> __construct<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;">&#123;</span> <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;</div>
</li>
<li style="font-weight: bold;color:#26536A;">
<div style="font-family: 'Courier New', Courier, monospace; font-weight: normal;">&nbsp; &nbsp; <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;">&nbsp; &nbsp;&nbsp; * Abre uma conexão com o MySQL</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;">&nbsp; &nbsp;&nbsp; */</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; public <span style="color:#000000; font-weight:bold;">function</span> Conecta<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;">&#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; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;<span style="color:#616100;">if</span> <span style="color:#006600; font-weight:bold;">&#40;</span>self::<span style="color:#0000FF;">$Con</span> instanceof PDO<span style="color:#006600; font-weight:bold;">&#41;</span> <span style="color:#616100;">return</span> self::<span style="color:#0000FF;">$Con</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; &nbsp; self::<span style="color:#0000FF;">$Con</span> = <span style="color:#000000; font-weight:bold;">new</span> PDO<span style="color:#006600; font-weight:bold;">&#40;</span><span style="color:#FF0000;">"mysql:host="</span> . SERV . </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; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; <span style="color:#FF0000;">";dbname="</span> . NAME . <span style="color:#FF0000;">""</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; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; USER,</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; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; PASS</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; &nbsp; &nbsp; &nbsp; <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; &nbsp; <span style="color:#616100;">return</span> self::<span style="color:#0000FF;">$Con</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;"><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;"><span style="color:#000000; font-weight:bold;">?&gt;</span> </div>
</li>
</ol>
</div>
</div>
</div>
<p></p>
<p>Caso tenha interessado o assunto, você poderá pesquisar outras diversas Patterns que propõem solução para vários outros "problemas" que temos diariamente. Esse foi apenas um panorama geral sobre Design Patterns.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.hlegius.pro.br/design-patterns-e-o-php/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Frameworks PHP versus Código na unha</title>
		<link>http://www.hlegius.pro.br/frameworks-php-versus-codigo-na-unha/</link>
		<comments>http://www.hlegius.pro.br/frameworks-php-versus-codigo-na-unha/#comments</comments>
		<pubDate>Sun, 04 Nov 2007 13:11:33 +0000</pubDate>
		<dc:creator>hlegius</dc:creator>
				<category><![CDATA[Desenvolvimento]]></category>
		<category><![CDATA[OOP e Patterns]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programação]]></category>

		<guid isPermaLink="false">http://www.hlegius.pro.br/frameworks-php-versus-codigo-na-unha/</guid>
		<description><![CDATA[Salve!
Com o advento do PHP 5 OO, começaram a surgir o que já era esperado: uma chuva de frameworks. Tem framework para quase tudo hoje: XML, manupilação de dados, automatização de rotinas na view, abstração de database, até modelos mais avançados, complexos e completos como o CodeIngniter e o Symfony. Mas até onde isso é [...]]]></description>
			<content:encoded><![CDATA[<p>Salve!</p>
<p>Com o advento do PHP 5 OO, começaram a surgir o que já era esperado: uma chuva de frameworks. Tem framework para quase tudo hoje: XML, manupilação de dados, automatização de rotinas na view, abstração de database, até modelos mais avançados, complexos e completos como o <a href="http://codeigniter.com">CodeIngniter</a> e o <a href="http://www.symfony-project.com/">Symfony</a>. Mas até onde isso é vantajoso ? Será que nós programadores estamos preparados para nos adaptarmos a essas frameworks ?</p>
<p><strong>1. Conhecendo os participantes<br />
</strong>Quando produzimos um software temos em mente que aquela aplicação é totalmente conhecida por nós, ou pelo menos o máximo possível, e que atrás dela há apenas Classes e funções criadas por nós e linguagem nativa (no caso o PHP).</p>
<p>Com frameworks temos um cenário totalmente diferente: código código e mais código por trás daquela framework que nós não temos a minima noção do que faz, onde há possíveis falhas e se aquela era a melhor forma de se fazer tal funcionabilidade. Entretanto, temos um "modelo" bem genérico ao nosso dispor, evitando que percamos tempo criando algo que tem pronto.</p>
<p>Os defensores de frameworks dizem que se você não sabe o que tem dentro da framework é porque você não quer saber o que há nela e ponto. Por outro lado, os defensores do código "na unha", dizem que se é para usar frameworks, ler a mesma seria uma tremenda perca de tempo e sendo assim, é melhor criar suas próprias classes/funções e usar em suas aplicações todas.</p>
<p><strong>2. Quebrando paradigmas</strong><br />
Com o tempo estive analisando os prós e contras da framework e hoje, consegui chegar a uma linha de pensamento que talvez seja agradável ou não para você: "Frameworks. Consuma com moderação.".<br />
E é exatamente isso que tenho feito de uns tempos para cá: uso algumas poucas frameworks para auxiliar em algumas tarefas e o resto eu vou criando na mão e criando meu "pacote".</p>
<p>Não adianta ser radical. Não usar framework nenhuma é meio que loucura atualmente. Se você é das antigas e já tem seus pacotes até pode ser, mas começar hoje a nadar contra a maré é suicídio.</p>
<p>Eu faço assim atualmente:<br />
<em><strong>Pergunto :</strong> A framework "X" faz o que ?<br />
<strong>Respondo:</strong> ah, de acordo com o site, ele cria um blog em 20 minutos.<br />
<strong>Afirmo: </strong>Então essa framework é a "tal" que faz tudo ? Ótimo, não serve para mim!</em></p>
<p>Você pode estar me xingando a rodo neste momento, mas tenho para mim que ficar preso a uma framework é suicídio! Ficarei dependente de algo assim como um drogado depende da droga! Loucura! Se encontrar um problema na framework, terei que esperar uma nova versão, ou então debugar tudo para encontrar  o erro/solução; Pensa no <a href="http://wordpress.com">WordPress</a>: tem uma falha, todo mundo que tem o <a href="http://wordpress.com">WordPress</a> instalado fica preocupado, pois é por lá que entrarão no seu sistema e danificarão suas informações. afinal o bug é público! E adaptar-se a nova forma de trabalho daquela framework, também não é tarefa fácil.</p>
<p>Estive vendo o <a href="http://www.symfony-project.com/">Symfony PHP</a> e constatei que ele é estilo o <a href="http://www.rubyonrails.org/">Ruby On Rails</a>! Tudo por linha de comando. Tenho que ficar digitando comandos no meu querido <a href="http://www.flickr.com/photos/hlegius/1330961101/">shell</a> para criar coisas dentro do projeto ? Não, isso infelizmente não é minha realidade!</p>
<p>Para mim, framework está como uma "biblioteca" de recursos, e não um novo modo de trabalhar com a linguagem de programação.</p>
<p><strong>3. Frameworks</strong><br />
Atualmente eu estou utilizando a framework <a href="http://jquery.com">Jquery</a> para Javascript e o <a href="http://smarty.php.net">Smarty Template</a> para templates no PHP.</p>
<p>Talvez um dia eu mude de concepção, mas atualmente estou bem feliz assim e creio que muitos estejam como eu <img src='http://www.hlegius.pro.br/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://www.hlegius.pro.br/frameworks-php-versus-codigo-na-unha/feed/</wfw:commentRss>
		<slash:comments>12</slash:comments>
		</item>
	</channel>
</rss>
