<?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>Lucas Stephanou</title>
	<atom:link href="http://blog.lucas-ts.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://blog.lucas-ts.com</link>
	<description>sf php and web</description>
	<lastBuildDate>Fri, 09 Oct 2009 03:37:32 +0000</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.4</generator>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
			<item>
		<title>Playing with Symfony Templating Part 1</title>
		<link>http://blog.lucas-ts.com/programacao/php/symfony/playing-with-symfony-templating-part-1/</link>
		<comments>http://blog.lucas-ts.com/programacao/php/symfony/playing-with-symfony-templating-part-1/#comments</comments>
		<pubDate>Mon, 05 Oct 2009 14:31:04 +0000</pubDate>
		<dc:creator>lucas</dc:creator>
				<category><![CDATA[symfony]]></category>
		<category><![CDATA[haml]]></category>
		<category><![CDATA[smarty]]></category>
		<category><![CDATA[template]]></category>

		<guid isPermaLink="false">http://blog.lucas-ts.com/?p=37</guid>
		<description><![CDATA[This is the first part of two
A few days ago Fabien Potencier, lead developer of Symfony project, published a new component  of the Symfony Components project.
As you may not know yet, Symfony components is a &#8220;lego way&#8221; that Fabien and symfony team found to publish piece by piece the parts that will compose the next [...]]]></description>
			<content:encoded><![CDATA[<p><em>This is the first part of two</em></p>
<p>A few days ago <a href="http://fabien.potencier.org/">Fabien Potencier</a>, lead developer of <a href="http://www.symfony-project.org/" target="_blank">Symfony project</a>, published a new component  of the <a href="http://components.symfony-project.org/">Symfony Components project</a>.</p>
<p>As you may not know yet, Symfony components is a &#8220;lego way&#8221; that Fabien and symfony team found to publish piece by piece the parts that will compose the next big version of symfony framework, the very waited symfony 2 version.</p>
<p>This last component is a templating framework, but what is that?</p>
<h2>A Templating Framework and some history</h2>
<p>A big part of php developers around the world use day-by-day a templating engine, like smarty and phptal.</p>
<p>A group of devs have asked in symfony mailing lists to use symfony together with one of those engines.</p>
<p>But bundle a template engine together with Symfony was never in mind of core team, for some(and good) reasons.</p>
<p>Some time ago, the Symfony components project was released and putting all parts together we can understand everything, the answer is a templating framework(not a template engine) , giving us a flexibe way to implement whatever &#8220;engine&#8221;  we want in a standard way.</p>
<h2>Wich template engine?</h2>
<p>Well, to test Symfony templating framework we need to choice a engine to reproduce.<br />
Wich one?<br />
Smarty? No, thanks.  Too flat to me.<br />
<a href="http://phptal.org/" target="_blank">PHPTal</a>? Maybe<br />
<a href="http://haml-lang.com/" target="_blank"> Haml</a>? Hum, far away from html and php syntax. A good example to see if the framework  is good <img src='http://blog.lucas-ts.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> </p>
<h2>Implementing Haml Templating Engine with Symfony templating framework</h2>
<p>Since <a href="http://haml-lang.com/" target="_blank">Haml</a> isn&#8217;t exactly a tiny language, I&#8217;ll implement just a few features.</p>
<p>The goal is parse this example:</p>
<pre>!!!
%html
  %head
    %title= $title
  %body
    #header
      %h1 Symfony templating Haml example
    #content
      %img {:src =&gt; 'http://haml-lang.com/images/haml.gif'}
      %h2 Haml
      %p Haml is a markup language that’s used to cleanly and simply describe the HTML of any web document without the use of inline code. Haml functions as a replacement for inline page templating systems such as PHP, ASP, and ERB, the templating language used in most Ruby on Rails applications. However, Haml avoids the need for explicitly coding HTML into the template, because it itself is a description of the HTML, with some code to generate dynamic content.
    #footer
      %span.author Lucas Stephanou</pre>
<h2>The simple Symfony Haml Template Engine</h2>
<p>Since <a href="http://phphaml.sourceforge.net/" target="_blank">phphaml</a> is very easy to use, our template renderer class will be simple.</p>
<pre>&lt;?php

/**
 * sfTemplateRendererHaml is a renderer for Haml templates.
 *
 * @package    symfony
 * @subpackage templating
 * @author     Lucas Stephanou &lt;lucas@lucas-ts.com&gt;
 * @version    SVN: $Id$
 */
class sfTemplateRendererHaml extends sfTemplateRenderer
{
  private $hamlParser;

  public function __construct(HamlParser $hamlParser)
  {
    $this-&gt;hamlParser = $hamlParser;
  }    

  /**
   * Evaluates a template.
   *
   * @param mixed $template   The template to render
   * @param array $parameters An array of parameters to pass to the template
   *
   * @return string|false The evaluated template, or false if the renderer is unable to render the template
   */
  public function evaluate(sfTemplateStorage $template, array $parameters = array())
  {  

    // even if $template is a string representation, hamlParser will take care of this
    $this-&gt;hamlParser-&gt;setFile($template);

    foreach($parameters as $key =&gt; $val)
    {
      $this-&gt;hamlParser-&gt;assign($key,$val);
    }   

    return $this-&gt;hamlParser-&gt;render();
  }
}</pre>
<p>The</p>
<pre>&lt;?php
__construct(HamlParser $hamlParser)</pre>
<p>method receive a HamlParser class as argument, this will allow us to implement all this with  DI in the next article.</p>
<pre>&lt;?php
evaluate($template, array $parameters = array())</pre>
<p>this method  is all we need to do for  a renderer class, we receive a $template instance(object or a string) and $parameters.</p>
<p>Them the symfony templating framework will expect to receive a string(in case of success ) or a boolean false if something goes wrong.</p>
<h2>Testing</h2>
<p>To test if we do all right, just create a single file:</p>
<pre>&lt;?php

require_once '../../symfony_templating/lib/sfTemplateAutoloader.php';
sfTemplateAutoloader::register();

$loader = new sfTemplateLoaderFilesystem(dirname(__FILE__).'/%name%.haml');

require_once dirname(__FILE__).'/../lib/phphaml/haml/HamlParser.class.php';
$parser = new HamlParser();

require_once dirname(__FILE__).'/../lib/sfTemplateRendererHaml.php';
$engine = new sfTemplateEngine($loader,array(
 'haml' =&gt; new sfTemplateRendererHaml($parser),
));

echo $engine-&gt;render('haml:example', array('title' =&gt; 'Haml Lucas Test'));</pre>
<p>Al l code is pretty obvious</p>
<ol>
<li>register symfony templating autoload</li>
<li>instantiate a template loader (in this case a filesystem loader)</li>
<li>include the HamlParser and instantiate it</li>
<li>include our haml renderer class</li>
<li>create a template engine indicating that our class will render haml files</li>
<li>render  the template passing a single parameter(title)</li>
</ol>
<p>In the next article we will integrate the symfony dependency injection lib and create a more flexible way to load templates</p>
<p>All code are here for download:</p>
<p><a href="http://dl.getdropbox.com/u/1417411/sfSimpleHaml.tar.bz2" target="_blank">http://dl.getdropbox.com/u/1417411/sfSimpleHaml.tar.bz2</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lucas-ts.com/programacao/php/symfony/playing-with-symfony-templating-part-1/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Symfony Jobeet Screencast &#8211; Day 1</title>
		<link>http://blog.lucas-ts.com/programacao/symfony-jobeet-screencast-day-1/</link>
		<comments>http://blog.lucas-ts.com/programacao/symfony-jobeet-screencast-day-1/#comments</comments>
		<pubDate>Thu, 09 Jul 2009 05:09:10 +0000</pubDate>
		<dc:creator>lucas</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[programação]]></category>
		<category><![CDATA[symfony]]></category>

		<guid isPermaLink="false">http://blog.lucas-ts.com/?p=22</guid>
		<description><![CDATA[Symfony Jobeet Screencast - Day 1]]></description>
			<content:encoded><![CDATA[<p>Just uploaded to vimeo my first screencast.</p>
<p>It&#8217;s a Screencast covering a Symfony Tutorial, the  Jobeet Day 1</p>
<p>I&#8217;m thinking in continue the series of jobeet if people like this one and so start  increasing quality(+audio,+tips) of nexts</p>
<p>About Screencast:<br />
It&#8217;s take a fresh ubuntu  and starting install everything that we need to run php/symfony and all things related to Jobeet Day 1</p>
<p>For this screencast, I can&#8217;t record audio and edit the video, is purely what I got from screencast recorder, sorry for that.</p>
<p>you can see it larger direct in vimeo website:<br />
<a href="http://www.vimeo.com/5518192" target="_blank">http://www.vimeo.com/5518192</a></p>
<p><object width="400" height="300"><param name="allowfullscreen" value="true" /><param name="allowscriptaccess" value="always" /><param name="movie" value="http://vimeo.com/moogaloop.swf?clip_id=5518192&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" /><embed src="http://vimeo.com/moogaloop.swf?clip_id=5518192&amp;server=vimeo.com&amp;show_title=1&amp;show_byline=1&amp;show_portrait=0&amp;color=&amp;fullscreen=1" type="application/x-shockwave-flash" allowfullscreen="true" allowscriptaccess="always" width="400" height="300"></embed></object>
<p><a href="http://vimeo.com/5518192">Symfony Screencast &#8211; Jobeet Day 1</a> from <a href="http://vimeo.com/user2004574">lucas stephanou</a> on <a href="http://vimeo.com">Vimeo</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lucas-ts.com/programacao/symfony-jobeet-screencast-day-1/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Instalando PHP 5,Fastcgi, lighttpd e symfony framework</title>
		<link>http://blog.lucas-ts.com/programacao/php/symfony/instalando-php-5fastcgi-lighttpd-e-symfony-framework/</link>
		<comments>http://blog.lucas-ts.com/programacao/php/symfony/instalando-php-5fastcgi-lighttpd-e-symfony-framework/#comments</comments>
		<pubDate>Fri, 03 Jul 2009 19:21:34 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[symfony]]></category>

		<guid isPermaLink="false">http://blog.lucas-ts.com/?p=17</guid>
		<description><![CDATA[Graças aos archive.org consegui recuperar este artigo escrito em 2006, sobre como instalar o lighttpd e compilando o php 5 com suporte a fastcgi.
Apesar de ter 3 anos, a instalação ainda funciona normalmente.
Mas irei atualiza-lo em breve refletindo alguns avançoes que tivemos.
De uma olhada: Symfony com lighttpd e php5 compilado
]]></description>
			<content:encoded><![CDATA[<p>Graças aos <a title="Web Archive Site" href="http://archive.org " target="_blank">archive.org</a> consegui recuperar este artigo escrito em 2006, sobre como instalar o lighttpd e compilando o php 5 com suporte a fastcgi.</p>
<p>Apesar de ter 3 anos, a instalação ainda funciona normalmente.</p>
<p>Mas irei atualiza-lo em breve refletindo alguns avançoes que tivemos.</p>
<p>De uma olhada: <a title="Symfony com lighttpd e php5 compilado" href="http://blog.lucas-ts.com/instalando-php-5fastcgi-lighttpd-e-symfony-framework/" target="_self">Symfony com lighttpd e php5 compilado</a></p>
]]></content:encoded>
			<wfw:commentRss>http://blog.lucas-ts.com/programacao/php/symfony/instalando-php-5fastcgi-lighttpd-e-symfony-framework/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>[TRADUÇÃO] &#8211; 39 dicas de performance PHP</title>
		<link>http://blog.lucas-ts.com/programacao/traducao-39-dicas-de-perfomance-php/</link>
		<comments>http://blog.lucas-ts.com/programacao/traducao-39-dicas-de-perfomance-php/#comments</comments>
		<pubDate>Wed, 08 Apr 2009 14:49:27 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[programação]]></category>

		<guid isPermaLink="false">http://lucas-ts.com/blog/?p=3</guid>
		<description><![CDATA[
Meu primeiro artigo no blog, uma tradução do otimo post de Reinhold, depois desse espero ter sempre artigos e traduções de qualidade sobre PHP. ( fiz algumas alterações e coloquei links para alguns artigos relacionados)
[UPDATE]
Algumas correções de português, adicionados exemplos.
Obrigado Pablo.
[/UPDATE]
Ai esta: (Thank you Reinhold)

Se um método pode ser estatico, declare ele estatico. O fator [...]]]></description>
			<content:encoded><![CDATA[<div class="entry">
<p>Meu primeiro artigo no blog, uma tradução do <a title="40 Tips for optimizing your php code " href="http://reinholdweber.com/?p=3">otimo post de Reinhold</a>, depois desse espero ter sempre artigos e traduções de qualidade sobre PHP. ( fiz algumas alterações e coloquei links para alguns artigos relacionados)</p>
<p>[UPDATE]<br />
Algumas correções de português, adicionados exemplos.<br />
Obrigado Pablo.<br />
[/UPDATE]</p>
<p>Ai esta: (Thank you Reinhold)</p>
<ol>
<li>Se um método pode ser estatico, declare ele estatico. O fator de otimização é 4x+</li>
<li><em>echo</em> é mais rapido que <em>print</em>. <a title="Veja aqui" href="http://www.faqts.com/knowledge_base/view.phtml/aid/1/fid/40" target="_blank">Veja</a></li>
<li>Prefira usar echo com multiplo parametros ao invés de concatenar string
<div class="geshi no php">
<ol>
<li class="li1">
<div class="de1"><span class="kw3">echo</span> <span class="st0">&#8220;parametro um&#8221;</span><span class="sy0">,</span> <span class="re1">$var</span> <span class="sy0">,</span> <span class="st0">&#8220;outro parametro&#8221;</span></div>
</li>
</ol>
</div>
</li>
<li>Set o valor maximo  do seus loops FOR antes e não no for
<div class="geshi no php">
<div class="head">#onde:</div>
<ol>
<li class="li1">
<div class="de1"><span class="kw1">for</span><span class="br0">(</span><span class="re1">$i</span><span class="sy0">=</span><span class="nu0">0</span><span class="sy0">;</span><span class="re1">$i</span><span class="sy0">&amp;</span>lt<span class="sy0">;</span>count<span class="br0">(</span><span class="re1">$array</span><span class="br0">)</span><span class="sy0">;</span><span class="re1">$i</span><span class="sy0">++</span><span class="br0">)</span></div>
</li>
<li class="li1">
<div class="de1"><span class="co2">#use:</span></div>
</li>
<li class="li1">
<div class="de1"><span class="re1">$max_for</span> <span class="sy0">=</span> <span class="kw3">count</span><span class="br0">(</span><span class="re1">$array</span><span class="br0">)</span><span class="sy0">;</span></div>
</li>
<li class="li1">
<div class="de1"><span class="kw1">for</span><span class="br0">(</span><span class="re1">$i</span><span class="sy0">=</span><span class="nu0">0</span><span class="sy0">;</span><span class="re1">$i</span><span class="sy0">&amp;</span>lt<span class="sy0">;</span><span class="re1">$max_for</span><span class="sy0">;</span><span class="re1">$i</span><span class="sy0">++</span><span class="br0">)</span></div>
</li>
</ol>
</div>
</li>
<li>Sempre de <span style="font-style: italic;">unset </span>em variaveis que nao serão mais usadas, principalemente grandes arrays.</li>
<li>Tente não usar métodos magicos, como:  __get, __set, __autoload</li>
<li>require_once() tem custo elevado, prefira include[_once], como alertado pelo Pablo, o include_once é mais custoso que o include.</li>
<li>Use caminhos completos em includes e requires, o PHP gastara menos tempo resolvendo os caminhos.</li>
<li>Se você deseja descobrir quando o script começou a ser executado, $_SERVER[’REQUEST_TIME’]  é melhor que time()</li>
<li>Se você puder, use strncasecmp, strpbrk e stripos no lugar de funcões regex</li>
<li>str_replace é mais rápida que preg_replace, mas strtr é ainda 4x mais rapida que str_replace.</li>
<li>Se uma função, como troca de string , aceitar tanto arrays quanto caracteres unicos e a sua lista de argumentos não for muito longa, considere escrever algumas vezes o mesmo codigo passando um caracter por vez ao invés de uma linha passando arrays nos argumentos de pesquisa e troca.</li>
<li>É melhor usar switch/case do que multiplos if’s e else.</li>
<li>Usar supressão de erros com @ na frente da função é muito lento.</li>
<li>Ative o mod_deflate do apache( modulo de compressão de resposta).</li>
<li>Feche as conexões ao banco de dados quando você não for mais usa-lo.</li>
<li>$row[’id’] é 7x mais rapido que  $row[id]</li>
<li>Mensagens de erros tem custo elevado, desligue-as em produção.</li>
<li>Não use funcões dentro de loops, como:
<div class="geshi no php">
<ol>
<li class="li1">
<div class="de1"><span class="kw1">for</span> <span class="br0">(</span><span class="re1">$x</span><span class="sy0">=</span><span class="nu0">0</span><span class="sy0">;</span> <span class="re1">$x</span> <span class="sy0">&amp;</span>lt<span class="sy0">;</span> <span class="kw3">count</span><span class="br0">(</span><span class="re1">$array</span><span class="br0">)</span><span class="sy0">;</span> <span class="re1">$x</span><span class="br0">)</span></div>
</li>
</ol>
</div>
<p>A função count() é chamada em cada iteração.</li>
<li>Incrementando uma variavel local é mais rapido.</li>
<li>Incrementando uma variavel global é 2x mais lento que em uma variavel local.</li>
<li>Incrementando uma propriedade ( $this-&gt;prop++) é 3x mais lento que em uma variavel local.</li>
<li>Incrementando uma variavel local não definida é de 9x a 10x mais lento do que uma variavel local pré-inicializada.</li>
<li>Declarando uma variável global sem usá-lo em uma função também atrasa as coisas (com aproximadamente a mesma quantidade incrementando como uma variavel local).O PHP provavelmente faz um checagem para ver se existe a nível global</li>
<li>A invocação de métodos parece ser independente do número de métodos definidos em uma classe, em uma classe de teste onde se adicionou 10 metódos não teve mudança de performance.</li>
<li>Métodos em classes derivadas rodam mais rápido do que aqueles definidos na classe base.</li>
<li>Use ‘ ao invés de ” em strings quando não for preciso usar variaveis ou escapes, assim o PHP não necessita procurar e interpretar esses caracteres especiais.</li>
<li>Prefira usar HTML puro se for possivel, scripts PHP são servidos de 2x a 10x mais lentos que equivalentes.</li>
<li>Em cada requisição seus scripts PHP são recompilados, use uma solução de cache, isso pode te dar um ganho de 25 a 100% . <a title="Artigos sobre PHP  e Cache no delicious." href="http://del.icio.us/search/?fr=del_icio_us&amp;p=php%2Bcache&amp;type=all" target="_blank">Veja</a></li>
<li>Quando lidando com string e você precisar verificar se a string possui certo tamanho, você entendidamente desejara usar a função strlen().<br />
Essa função é bastante rapida, já que ela não faz nenhum calculo, apenas retorna o tamanho ja conhecido da string disponivel na estrutura zval(estrutura interna do C usada para guardar variaveis PHP). No entanto como strlen() é uma função ela ainda assim é lenta, porque o PHP precisa fazer varias operações  como lowercase e buscas na hashtable, e em seguida executar a dita função.<br />
Algumas vezes você podera aumentar a velocidade do seu código usando um truque com isset().<br />
Exemplo: Digamos que voce tem :</p>
<div class="geshi no php">
<div class="head">if (strlen($foo) &lt; 5) { echo “Foo is too short”; }</div>
<ol>
<li class="li1">
<div class="de1"><span class="co2"># versus</span></div>
</li>
<li class="li1">
<div class="de1"><span class="kw1">if</span> <span class="br0">(</span><span class="sy0">!</span><span class="kw3">isset</span><span class="br0">(</span><span class="re1">$foo</span><span class="br0">{</span><span class="nu0">5</span><span class="br0">}</span><span class="br0">)</span><span class="br0">)</span> <span class="br0">{</span> <span class="kw3">echo</span> <span class="st0">&#8220;Foo is too short&#8221;</span><span class="sy0">;</span> <span class="br0">}</span></div>
</li>
</ol>
</div>
<p>Usando isset() sera mais rapido que strlen(), porque diferente de strlen(), isset() é um construtor de linguagem e não uma função, isso quer dizer que a sua execução não necessita busca na hashtable nem uso de lowercase. Virtualmente você não sobrecarga no código atual para determinar o tamanho da string.</li>
<li>Quando incrementando ou decrementando o valor de uma variavel, $i++ normalmente é mais lenta que  ++$i. Isso é especifico para PHP, ou seja, não se aplica a outras linguagens, não sai por ai modificando seu código java ou C. Isso se da porque $i++ usa 4 opcodes enquanto ++$i precisa de somente 3.</li>
<li>Nem tudo precisa ser <acronym title="Programação Orientada a Objetos">OOP</acronym>, gera muita sobrecarga, cada chamada de método e objeto consome um monte de memória.</li>
<li>Não implemente cada estrutura de dados como uma classe, arrays são utéis também.</li>
<li>Não divida muito os métodos, pense bem cada código que sera reusado.</li>
<li>Você sempre podera dividir o código no futuro, caso necessario.</li>
<li>Faça uso das incontaveis funções pré-definidas.</li>
<li>Se você tem muito tempo consumido por funções em seu código, considere escreva-las como extensões C.</li>
<li> Faça Profile do seu código. Um profiler mostra quanto tempo cada parte do seu código consome. A extensão  Xdebug ja contém um profiler.</li>
<li><a href="http://phplens.com/lens/php-book/optimizing-debugging-php.php" target="_blank">Excelente artigo</a> sobre otimização PHP de John Lim (inglês)</li>
</ol>
</div>
]]></content:encoded>
			<wfw:commentRss>http://blog.lucas-ts.com/programacao/traducao-39-dicas-de-perfomance-php/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
