<?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>Rogério Lino &#187; PHP</title>
	<atom:link href="http://rogeriolino.com/categorias/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://rogeriolino.com</link>
	<description>Desenvolvimento Web, tecnologia, jogos e etcetera</description>
	<lastBuildDate>Wed, 16 May 2012 19:51:00 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.2</generator>
<xhtml:meta xmlns:xhtml="http://www.w3.org/1999/xhtml" name="robots" content="noindex" />
		<item>
		<title>HTML5: Websocket</title>
		<link>http://rogeriolino.com/2012/05/16/html5-websocket/</link>
		<comments>http://rogeriolino.com/2012/05/16/html5-websocket/#comments</comments>
		<pubDate>Wed, 16 May 2012 19:48:48 +0000</pubDate>
		<dc:creator>Rogério Alencar Lino Filho</dc:creator>
				<category><![CDATA[HTML5]]></category>
		<category><![CDATA[Javascript]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[demo]]></category>
		<category><![CDATA[example]]></category>
		<category><![CDATA[html5]]></category>
		<category><![CDATA[hybi]]></category>
		<category><![CDATA[rfc6455]]></category>
		<category><![CDATA[socket]]></category>
		<category><![CDATA[websocket]]></category>

		<guid isPermaLink="false">http://rogeriolino.com/?p=563</guid>
		<description><![CDATA[<p> <a href="http://www.rfc-editor.org/rfc/rfc6455.txt" title="RFC 6455">The Websocket Protocol</a><br /> The WebSocket Protocol enables two-way communication between a client running untrusted code in a controlled environment to a remote host that has opted-in to communications from that code. The security model used for this is the origin-based security model commonly used by web browsers. The protocol consists [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><blockquote><p>
<center><a href="http://www.rfc-editor.org/rfc/rfc6455.txt" title="RFC 6455">The Websocket Protocol</a></center><br />
 The WebSocket Protocol enables two-way communication between a client running untrusted code in a controlled environment to a remote host    that has opted-in to communications from that code.  The security model used for this is the origin-based security model commonly used by web browsers.  The protocol consists of an opening handshake followed by basic message framing, layered over TCP.  The goal of this technology is to provide a mechanism for browser-based applications that need two-way communication with servers that does not rely on opening multiple HTTP connections (e.g., using XMLHttpRequest or &lt;iframe&gt;s and long polling).
</p></blockquote>
<p>Aproveitando um post sobre <a href="http://rogeriolino.com/2010/04/22/php-socket-class/" title="PHP Socket class">PHP Sockets</a> que tinha escrito unindo o estudo sobre Websocket, eu criei um <a href="https://github.com/rogeriolino/phpsocket" title="Github: PHP Socket project">projeto no Github</a> para facilitar o uso de sockets com PHP fornecendo suporte ao Websocket também.</p>
<p>E para visualizar o <a href="https://github.com/rogeriolino/phpsocket/tree/master/demo/websocket" title="Websocket chat example">exemplo</a> basta fazer checkout do projeto, executar o arquivo server.php: </p>
<pre name="code" class="php">
> $ php server.php
</pre>
<p>E abrir a página chat.html pelo browser. O funcionamento do exemplo vai depender, além obviamente do suporte à Websocket, do tipo da versão da implementação do browser. Por enquanto a suportada pelo projeto é a HyBi (descrita na <a href="http://www.rfc-editor.org/rfc/rfc6455.txt" title="RFC 6455">RFC 6455</a>).</p>
<div class="shr-publisher-563"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><div class='shareaholic-like-buttonset' style='float:none;height:30px;'><a class='shareaholic-fblike' data-shr_layout='button_count' data-shr_showfaces='false' data-shr_href='http%3A%2F%2Frogeriolino.com%2F2012%2F05%2F16%2Fhtml5-websocket%2F' data-shr_title='HTML5%3A+Websocket'></a><a class='shareaholic-googleplusone' data-shr_size='medium' data-shr_count='true' data-shr_href='http%3A%2F%2Frogeriolino.com%2F2012%2F05%2F16%2Fhtml5-websocket%2F' data-shr_title='HTML5%3A+Websocket'></a><a class='shareaholic-tweetbutton' data-shr_count='horizontal' data-shr_href='http%3A%2F%2Frogeriolino.com%2F2012%2F05%2F16%2Fhtml5-websocket%2F' data-shr_title='HTML5%3A+Websocket'></a></div><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://rogeriolino.com/2012/05/16/html5-websocket/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>PHP: Validate Filters</title>
		<link>http://rogeriolino.com/2012/03/16/php-validate-filters/</link>
		<comments>http://rogeriolino.com/2012/03/16/php-validate-filters/#comments</comments>
		<pubDate>Fri, 16 Mar 2012 17:46:43 +0000</pubDate>
		<dc:creator>Rogério Alencar Lino Filho</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[classe]]></category>
		<category><![CDATA[email]]></category>
		<category><![CDATA[filter]]></category>
		<category><![CDATA[filters]]></category>
		<category><![CDATA[filter_var]]></category>
		<category><![CDATA[ip]]></category>
		<category><![CDATA[oo]]></category>
		<category><![CDATA[regex]]></category>
		<category><![CDATA[url]]></category>
		<category><![CDATA[validate]]></category>
		<category><![CDATA[validation]]></category>
		<category><![CDATA[validator]]></category>

		<guid isPermaLink="false">http://rogeriolino.com/?p=529</guid>
		<description><![CDATA[<p>A partir do PHP 5.2 foi introduzida a função <a href="http://php.net/filter_var" title="PHP: filter_var">filter_var</a>. Que serve justamente para filtrar uma variável a partir de um filtro especificado.</p> mixed filter_var ( mixed $variable [, int $filter = FILTER_DEFAULT [, mixed $options ]] ) // Returns the filtered data, or FALSE if the filter fails. <p>Filtros pré-definidos:</p> // [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>A partir do PHP 5.2 foi introduzida a função <a href="http://php.net/filter_var" title="PHP: filter_var">filter_var</a>. Que serve justamente para filtrar uma variável a partir de um filtro especificado.</p>
<blockquote>
<pre>
mixed filter_var ( mixed $variable [, int $filter = FILTER_DEFAULT [, mixed $options ]] )
// Returns the filtered data, or FALSE if the filter fails.
</pre>
</blockquote>
<p>Filtros pré-definidos:</p>
<pre name="code" class="php">
// email filtering
echo filter_var('email@domain.com', FILTER_VALIDATE_EMAIL); // email@domain.com
echo filter_var('domain.com', FILTER_VALIDATE_EMAIL); // false

// url filtering
echo filter_var('http://rogeriolino.com', FILTER_VALIDATE_URL); // http://rogeriolino.com
echo filter_var('rogeriolino.com', FILTER_VALIDATE_URL); // false

// ip filtering
echo filter_var('127.0.0.1', FILTER_VALIDATE_IP); // 127.0.0.1
echo filter_var('127.0.1', FILTER_VALIDATE_IP); // false
</pre>
<p>Como a função pode retornar <strong>FALSE</strong> (caso o filtro falhe) ou o valor filtrado. Podemos utilizar o <strong>Not identical operator</strong> (!==) para verificar se retorno é realmente FALSE, ou seja, o valor testado não passou pelo filtro.</p>
<p>Colocando em prática a função mais orientação à objetos para criar algumas classes validadoras:</p>
<pre name="code" class="php">

/**
 * Interface Validator
 */
interface Validator {

    public function isValid($value);

}

/**
 * Abstract class Simple Validator
 */
abstract class SimpleValidator implements Validator {

    protected abstract function defaultFilter();

    public function isValid($value) {
        return filter_var($value, $this->defaultFilter()) !== false;
    }

}

/**
 * Simple Email validator
 */
class EmailValidator extends SimpleValidator {

    protected function defaultFilter() {
        return FILTER_VALIDATE_EMAIL;
    }

}

/**
 * Simple URL validator
 */
class UrlValidator extends SimpleValidator {

    protected function defaultFilter() {
        return FILTER_VALIDATE_URL;
    }

}

/**
 * Simple IP Validator
 */
class IpValidator extends SimpleValidator {

    protected function defaultFilter() {
        return FILTER_VALIDATE_IP;
    }

}
</pre>
<p>Testando</p>
<pre name="code" class="php">
// email validating
$validator = new EmailValidator();
echo $validator->isValid('rogeriolino@com'); // false
echo $validator->isValid('contact@rogeriolino.com'); // true
echo $validator->isValid('contact+spam@rogeriolino.com'); // true

// URL validating
$validator = new UrlValidator();
echo $validator->isValid('http://rogeriolino.com'); // true
echo $validator->isValid('http://rogeriolino.com/contact'); // true
echo $validator->isValid('rogeriolino.com/contact'); // false
echo $validator->isValid('https://rogeriolino'); // true
echo $validator->isValid('ftp://rogeriolino.com'); // true

// URL validating
$validator = new IpValidator();
echo $validator->isValid('127.0.0.1'); // true
echo $validator->isValid('127.0.0'); // false
echo $validator->isValid('1050:0000:0000:0000:0005:0600:300c:326b'); // true
echo $validator->isValid('1050:0000:0000:0000:0005:0600'); // false
</pre>
<p>Para ver outros filtros:<br />
<a href="http://php.net/manual/filter.filters.validate.php" target="_blank">http://php.net/manual/filter.filters.validate.php</a></p>
<div class="shr-publisher-529"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><div class='shareaholic-like-buttonset' style='float:none;height:30px;'><a class='shareaholic-fblike' data-shr_layout='button_count' data-shr_showfaces='false' data-shr_href='http%3A%2F%2Frogeriolino.com%2F2012%2F03%2F16%2Fphp-validate-filters%2F' data-shr_title='PHP%3A+Validate+Filters'></a><a class='shareaholic-googleplusone' data-shr_size='medium' data-shr_count='true' data-shr_href='http%3A%2F%2Frogeriolino.com%2F2012%2F03%2F16%2Fphp-validate-filters%2F' data-shr_title='PHP%3A+Validate+Filters'></a><a class='shareaholic-tweetbutton' data-shr_count='horizontal' data-shr_href='http%3A%2F%2Frogeriolino.com%2F2012%2F03%2F16%2Fphp-validate-filters%2F' data-shr_title='PHP%3A+Validate+Filters'></a></div><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://rogeriolino.com/2012/03/16/php-validate-filters/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP: Easy SQL date time formatting</title>
		<link>http://rogeriolino.com/2012/02/01/php-easy-sql-date-time-formatting/</link>
		<comments>http://rogeriolino.com/2012/02/01/php-easy-sql-date-time-formatting/#comments</comments>
		<pubDate>Wed, 01 Feb 2012 18:26:03 +0000</pubDate>
		<dc:creator>Rogério Alencar Lino Filho</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[array]]></category>
		<category><![CDATA[array_reverse]]></category>
		<category><![CDATA[data]]></category>
		<category><![CDATA[date]]></category>
		<category><![CDATA[datetime]]></category>
		<category><![CDATA[easy]]></category>
		<category><![CDATA[explode]]></category>
		<category><![CDATA[format]]></category>
		<category><![CDATA[formatação]]></category>
		<category><![CDATA[hora]]></category>
		<category><![CDATA[implode]]></category>
		<category><![CDATA[join]]></category>
		<category><![CDATA[sql]]></category>
		<category><![CDATA[strtotime]]></category>
		<category><![CDATA[time]]></category>
		<category><![CDATA[timestamp]]></category>

		<guid isPermaLink="false">http://rogeriolino.com/?p=478</guid>
		<description><![CDATA[<p>SQL to Human:</p> /* * date */ $format = 'm/d/Y'; // en-US // $format = 'd/m/Y'; // pt-BR $date = '2012-02-01'; echo date($format, strtotime($date)); /* * datetime */ $format .= ' H:i:s'; $datetime = '2012-02-01 11:33:59'; echo date($format, strtotime($datetime)); <p>Human to SQL:</p> /* * date */ $sqlFormat = 'Y-m-d'; $date = '02/01/2012'; // en-US echo [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p><strong>SQL to Human:</strong></p>
<pre name="code" class="php">
/*
 * date
 */
$format = 'm/d/Y'; // en-US
// $format = 'd/m/Y'; // pt-BR
$date = '2012-02-01';
echo date($format, strtotime($date));

/*
 * datetime
 */
$format .= ' H:i:s';
$datetime = '2012-02-01 11:33:59';
echo date($format, strtotime($datetime));
</pre>
<p><strong>Human to SQL:</strong></p>
<pre name="code" class="php">
/*
 * date
 */
$sqlFormat = 'Y-m-d';
$date = '02/01/2012';

// en-US
echo date($sqlFormat, strtotime($date));
// pt-BR
echo join('-', array_reverse(explode('/', $date)));

/*
 * datetime
 */
$sqlFormat = 'Y-m-d H:i:s';

// en-US
$datetime = '02/01/2012 11:33:59';
echo date($sqlFormat, strtotime($datetime));

// pt-BR
$datetime = '01/02/2012 11:33:59';
$datetime = explode(' ', $datetime);
$date = join('-', array_reverse(explode('/', $datetime[0])));
echo $date . ' ' . $datetime[1];
</pre>
<p><strong>Reference:</strong></p>
<p><a href="http://php.net/strtotime" title="PHP.net">strtotime</a><br />
The function expects to be given a string containing an English date format and will try to parse that format into a Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC), relative to the timestamp given in now, or the current time if now is not supplied.</p>
<p><a href="http://php.net/date" title="PHP.net">date</a><br />
Returns a string formatted according to the given format string using the given integer timestamp or the current time if no timestamp is given. In other words, timestamp is optional and defaults to the value of <a href="http://php.net/time" title="PHP.net">time()</a>.</p>
<p><a href="http://php.net/explode" title="PHP.net">explode</a><br />
Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter.</p>
<p><a href="http://php.net/array_reverse" title="PHP.net">array_reverse</a><br />
Takes an input array and returns a new array with the order of the elements reversed.</p>
<p><a href="http://php.net/join" title="PHP.net">join / implode</a><br />
Join array elements with a glue string.</p>
<div class="shr-publisher-478"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><div class='shareaholic-like-buttonset' style='float:none;height:30px;'><a class='shareaholic-fblike' data-shr_layout='button_count' data-shr_showfaces='false' data-shr_href='http%3A%2F%2Frogeriolino.com%2F2012%2F02%2F01%2Fphp-easy-sql-date-time-formatting%2F' data-shr_title='PHP%3A+Easy+SQL+date+time+formatting'></a><a class='shareaholic-googleplusone' data-shr_size='medium' data-shr_count='true' data-shr_href='http%3A%2F%2Frogeriolino.com%2F2012%2F02%2F01%2Fphp-easy-sql-date-time-formatting%2F' data-shr_title='PHP%3A+Easy+SQL+date+time+formatting'></a><a class='shareaholic-tweetbutton' data-shr_count='horizontal' data-shr_href='http%3A%2F%2Frogeriolino.com%2F2012%2F02%2F01%2Fphp-easy-sql-date-time-formatting%2F' data-shr_title='PHP%3A+Easy+SQL+date+time+formatting'></a></div><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://rogeriolino.com/2012/02/01/php-easy-sql-date-time-formatting/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP: Manga Framework</title>
		<link>http://rogeriolino.com/2011/09/20/php-manga-framework/</link>
		<comments>http://rogeriolino.com/2011/09/20/php-manga-framework/#comments</comments>
		<pubDate>Tue, 20 Sep 2011 18:35:56 +0000</pubDate>
		<dc:creator>Rogério Alencar Lino Filho</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[engine]]></category>
		<category><![CDATA[facelets]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[git]]></category>
		<category><![CDATA[github]]></category>
		<category><![CDATA[ioc]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jsf]]></category>
		<category><![CDATA[lithium]]></category>
		<category><![CDATA[manga]]></category>
		<category><![CDATA[opensource]]></category>
		<category><![CDATA[playframework]]></category>
		<category><![CDATA[rails]]></category>
		<category><![CDATA[rest]]></category>
		<category><![CDATA[ror]]></category>
		<category><![CDATA[router]]></category>
		<category><![CDATA[ruby]]></category>
		<category><![CDATA[symfony]]></category>
		<category><![CDATA[template]]></category>
		<category><![CDATA[vraptor]]></category>
		<category><![CDATA[yii]]></category>

		<guid isPermaLink="false">http://rogeriolino.com/?p=364</guid>
		<description><![CDATA[<p>Criado o projeto para o framework <a href="https://github.com/rogeriolino/manga-framework" title="Manga Framework">Manga, no Github</a> (PHP 5.3+).</p> <p>Entre algumas funcionalidades, destaca-se o seu template engine baseado no <a href="http://facelets.java.net/" title="Facelets">Facelets</a>.</p> <p>Os arquivos de configuração poderão ser escritos em mais de um formato, inicialmente suporte a XML e YAML. Annotations são utilizadas para enxugar esses arquivos de configuração, deixando [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>Criado o projeto para o framework <a href="https://github.com/rogeriolino/manga-framework" title="Manga Framework">Manga, no Github</a> (PHP 5.3+).</p>
<p>Entre algumas funcionalidades, destaca-se o seu template engine baseado no <a href="http://facelets.java.net/" title="Facelets">Facelets</a>.</p>
<p>Os arquivos de configuração poderão ser escritos em mais de um formato, inicialmente suporte a XML e YAML. Annotations são utilizadas para enxugar esses arquivos de configuração, deixando o código mais intuitivo.</p>
<p>O próximo passo é implementar suporte à <a href="http://en.wikipedia.org/wiki/Inversion_of_control" title="Inversion of Control">IoC</a>, que inicialmente pode ser simulado pelo arquivo de configuração de rotas (com suporte <a href="http://en.wikipedia.org/wiki/Representational_state_transfer" title="Representational State Transfer">REST</a>).</p>
<p>A intenção não é desenvolver um framework revolucionário, e sim adaptar as ideias e metodologias já utilizadas por outros em um único framework afim de aumentar a produtividade. Servem como inspiração os seguintes frameworks:</p>
<p><strong>Ruby</strong></p>
<ul>
<li><a href="http://rubyonrails.org/" title="Ruby on Rails">RoR</a></li>
</ul>
<p><strong>Java</strong></p>
<ul>
<li><a href="http://javaserverfaces.java.net/" title="Java Server Faces">JSF2</a></li>
<li><a href="http://www.springsource.org/" title="Spring">Spring 3</a></li>
<li><a href="http://vraptor.caelum.com.br/" title="VRaptor">VRaptor</a></li>
<li><a href="www.playframework.org" title="Play Framework">Play Framework</a></li>
</ul>
<p><strong>PHP</strong></p>
<ul>
<li><a href="http://lithify.me/" title="Lithium">Lithium</a></li>
<li><a href="http://symfony.com/" title="Symfony">Symfony</a></li>
<li><a href="http://www.yiiframework.com/" title="Yii">Yii</a></li>
</ul>
<div class="shr-publisher-364"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><div class='shareaholic-like-buttonset' style='float:none;height:30px;'><a class='shareaholic-fblike' data-shr_layout='button_count' data-shr_showfaces='false' data-shr_href='http%3A%2F%2Frogeriolino.com%2F2011%2F09%2F20%2Fphp-manga-framework%2F' data-shr_title='PHP%3A+Manga+Framework'></a><a class='shareaholic-googleplusone' data-shr_size='medium' data-shr_count='true' data-shr_href='http%3A%2F%2Frogeriolino.com%2F2011%2F09%2F20%2Fphp-manga-framework%2F' data-shr_title='PHP%3A+Manga+Framework'></a><a class='shareaholic-tweetbutton' data-shr_count='horizontal' data-shr_href='http%3A%2F%2Frogeriolino.com%2F2011%2F09%2F20%2Fphp-manga-framework%2F' data-shr_title='PHP%3A+Manga+Framework'></a></div><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://rogeriolino.com/2011/09/20/php-manga-framework/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>CakePHP: Layout Inheritance</title>
		<link>http://rogeriolino.com/2011/03/16/cakephp-layout-inheritance/</link>
		<comments>http://rogeriolino.com/2011/03/16/cakephp-layout-inheritance/#comments</comments>
		<pubDate>Wed, 16 Mar 2011 18:37:26 +0000</pubDate>
		<dc:creator>Rogério Alencar Lino Filho</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[cakephp]]></category>
		<category><![CDATA[dica]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[inheritance]]></category>
		<category><![CDATA[layout]]></category>
		<category><![CDATA[template]]></category>
		<category><![CDATA[tip]]></category>

		<guid isPermaLink="false">http://rogeriolino.com/?p=356</guid>
		<description><![CDATA[<p>Para quem está utilizando o CakePHP ou já utilizou e também sentiu falta de herança nos layouts. Segue abaixo uma dica para ajudar na criações de templates utilizando o CakePHP.</p> &#60;?php // sublayout.ctp ob_start(); ?&#62; &#60;?php eco $content_for_layout; ?&#62; &#60;?php $content = ob_get_contents(); ob_end_clean(); echo $this->renderLayout( $content, 'default' // parent layout ); &#60;?php // controller [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>Para quem está utilizando o CakePHP ou já utilizou e também sentiu falta de herança nos layouts. Segue abaixo uma dica para ajudar na criações de templates utilizando o CakePHP.</p>
<pre name="code" class="php">
&lt;?php
// sublayout.ctp

ob_start();

?&gt;
 <!-- html content -->
 &lt;?php eco $content_for_layout; ?&gt;
 <!-- html content -->
&lt;?php

$content = ob_get_contents();
ob_end_clean();

echo $this->renderLayout(
        $content,
        'default' // parent layout
);
</pre>
<pre name="code" class="php">
&lt;?php
// controller class
class MyController extends AppController {

    function test() {
        $this->layout = 'sublayout';
    }

}
</pre>
<div class="shr-publisher-356"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><div class='shareaholic-like-buttonset' style='float:none;height:30px;'><a class='shareaholic-fblike' data-shr_layout='button_count' data-shr_showfaces='false' data-shr_href='http%3A%2F%2Frogeriolino.com%2F2011%2F03%2F16%2Fcakephp-layout-inheritance%2F' data-shr_title='CakePHP%3A+Layout+Inheritance'></a><a class='shareaholic-googleplusone' data-shr_size='medium' data-shr_count='true' data-shr_href='http%3A%2F%2Frogeriolino.com%2F2011%2F03%2F16%2Fcakephp-layout-inheritance%2F' data-shr_title='CakePHP%3A+Layout+Inheritance'></a><a class='shareaholic-tweetbutton' data-shr_count='horizontal' data-shr_href='http%3A%2F%2Frogeriolino.com%2F2011%2F03%2F16%2Fcakephp-layout-inheritance%2F' data-shr_title='CakePHP%3A+Layout+Inheritance'></a></div><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://rogeriolino.com/2011/03/16/cakephp-layout-inheritance/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP: Template Engines</title>
		<link>http://rogeriolino.com/2010/09/09/php-template-engines/</link>
		<comments>http://rogeriolino.com/2010/09/09/php-template-engines/#comments</comments>
		<pubDate>Thu, 09 Sep 2010 21:22:29 +0000</pubDate>
		<dc:creator>Rogério Alencar Lino Filho</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[django]]></category>
		<category><![CDATA[dwoo]]></category>
		<category><![CDATA[engine]]></category>
		<category><![CDATA[facelets]]></category>
		<category><![CDATA[flexy]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[fxl]]></category>
		<category><![CDATA[h2o]]></category>
		<category><![CDATA[inheritance]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jinja]]></category>
		<category><![CDATA[jsf]]></category>
		<category><![CDATA[mvc]]></category>
		<category><![CDATA[pear]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[quickskin]]></category>
		<category><![CDATA[smarty]]></category>
		<category><![CDATA[template]]></category>
		<category><![CDATA[tinybutstrong]]></category>
		<category><![CDATA[vemplator]]></category>
		<category><![CDATA[vlib]]></category>
		<category><![CDATA[xtemplate]]></category>

		<guid isPermaLink="false">http://rogeriolino.com/?p=315</guid>
		<description><![CDATA[<p>Todo mundo que programa em PHP sente falta de uma boa alternativa para separar o código PHP do visual (HTML). Nessas horas vale a pena estudar algumas template engines para PHP disponíveis para saber qual que melhor se adapta à suas necessidades e projeto. Alguns frameworks MVC possuem sua própria engine, outros tentam.</p> <p><a href="http://www.smarty.net/">Smarty</a></p> [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>Todo mundo que programa em PHP sente falta de uma boa alternativa para separar o código PHP do visual (HTML). Nessas horas vale a pena estudar algumas template engines para PHP disponíveis para saber qual que melhor se adapta à suas necessidades e projeto. Alguns frameworks MVC possuem sua própria engine, outros tentam.</p>
<p><a href="http://www.smarty.net/">Smarty</a></p>
<p>O mais famoso e usado como inspiração por muitos outros projetos. Robusto (possuindo blocos condicionais/loops e várias funções próprias) e rápido (&#8220;compilando&#8221; suas páginas para arquivos PHP).</p>
<pre name="code" class="html">
&lt;ul&gt;
{foreach from=$myArray item=foo}
    &lt;li&gt;{$foo}&lt;/li&gt;
{/foreach}
&lt;/ul&gt;
</pre>
<pre name="code" class="php">
$smarty = new Smarty;
$arr = array(1000, 1001, 1002);
$smarty->assign ('myArray', $arr);
$smarty->display ('HelloWorld.tpl');
</pre>
<p><a href="http://vlib.clausvb.de/vlibtemplate.php">vlibtemplate</a></p>
<p>Com esta engine saímos de um problema e entramos em outro, é necessário aprender (lembrar) algumas palavras reservadas para sinalizar variáveis, além do uso dos limitadores das expressões.</p>
<pre name="code" class="html">
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;{tmpl_var name='title_text'}&lt;/title&gt;
&lt;meta http-equiv="content-type" content="text/html; charset=iso-8859-1" /&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;p&gt;{tmpl_var name='body_text'}&lt;/p&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
<pre name="code" class="php">
$tmpl = new vlibTemplate('tmpl/basic.htm');
$tmpl->setvar('title_text', 'TITLE: This is the vLIB basic example ...');
$tmpl->setvar('body_text', 'BODY: This is the message set using setvar()');
$tmpl->pparse();
</pre>
<p><a href="http://www.feverxl.org/template/">FXL Template</a></p>
<p>Muito pouco usual, o FXL faz uso dos blocos de comentário HTML para definir os loops. Outros semelhantes e nada melhores são: <a href="http://quickskin.worxware.com/">QuickSkin</a> e <a href="http://xtemplate.sourceforge.net/">XTemplate</a>.</p>
<pre name="code" class="html">
 &lt;table&gt;
     &lt;!-- START row --&gt;
         &lt;tr&gt;
             &lt;!-- START cell --&gt;
             &lt;td &gt;{td_value} &lt;/td&gt;
             &lt;!-- END cell --&gt;
         &lt;/tr&gt;
     &lt;!-- END row --&gt;
 &lt;/table&gt;
</pre>
<pre name="code" class="php">
$fxlt = new fxl_template('example.tpl');
$fxlt_row = $fxlt->get_block('row');
$fxlt_cell = $fxlt_row->get_block('cell');
for ($tr = 1; $tr <= 3; $tr++) {
    for ($td = 1; $td <= 3; $td++) {
        $fxlt_cell->assign('td_value', $tr.':'.$td);
        $fxlt_row->assign('cell', $fxlt_cell);
        $fxlt_cell->clear();
    }
    $fxlt->assign('row', $fxlt_row);
    $fxlt_row->clear();
}
$fxlt->display();
</pre>
<p><a href="http://www.greaterscope.net/projects/Vemplator">Vemplator</a></p>
<p>Mais do mesmo, mas com alterações de sintaxe.</p>
<pre name="code" class="html">
 &lt;h1&gt;{if:logged} Welcome {username} {else:} User not logged {end:} &lt;/h1&gt;
&lt;ul&gt;
{foreach:rows,row}
    &lt;li&gt;
    {row['name']}
    &lt;/li&gt;
{end:}
&lt;/ul&gt;
</pre>
<pre name="code" class="php">
$t = new vemplator();
// if/else
$t->assign('logged', true);
$t->assign('username', 'Rogerio');
// loop
$items = array(
	array('name' => 'Laptop'),
	array('name' => 'Memory Stick')
);
$t->assign('rows', $rows);
echo $t->output('example.template.html');
</pre>
<p><a href="http://www.tinybutstrong.com/">TinyButStrong</a></p>
<p>Uma alternativa ao estilo Smarty de muitos, porém é mais confuso e segue um padrão de nomenclatura bem particular.</p>
<pre name="code" class="html">
 &lt;table &gt;
 &lt;tr&gt;&lt;td&gt;[blk.val;block=tr]&lt;/td&gt;&lt;/tr&gt;
 &lt;/table &gt;
</pre>
<pre name="code" class="php">
$TBS =&#038; new clsTinyButStrong ;
$TBS->LoadTemplate('template.htm') ;
$list = array('X','Y','Z') ;
$TBS->MergeBlock('blk',$list) ;
$TBS->Show();
</pre>
<p><a href="http://dwoo.org/">Dwoo</a></p>
<p>Possui como diferencial um <a href="http://wiki.dwoo.org/index.php/TemplateInheritance">Template Inheritance</a>, o que facilita muito a vida na construção de templates.</p>
<pre name="code" class="html">
 &lt;html&gt;
 &lt;head&gt;
 &lt;title&gt;{block "title"}My site name{/block} &lt;/title&gt;
 &lt;/head&gt;
 &lt;body&gt;
     &lt;h1&gt;{block "page-title"}Default page title{/block} &lt;/h1&gt;
     &lt;div id="content"&gt;
      {block "content"}
        Welcome to my amazing homepage
      {/block}
     &lt;/div&gt;
 &lt;/body&gt;
 &lt;/html&gt;
</pre>
<pre name="code" class="html">
{extends "base.html"}
{block "title"}
Gallery
{/block}
{foreach $images img}
    <img src="{$img.url}" alt="{$img.description}" />
  {/foreach}
</pre>
<pre name="code" class="php">
$dwoo = Dwoo();
$images = array(
    array('url' => 'img1.jpg', 'description' => 'Ferrari'),
    array('url' => 'img2.jpg', 'description' => 'BMW')
);
$params = array();
$params['images'] = $images;
echo $dwoo->get("gallery.tpl", $params);
</pre>
<p><a href="http://www.h2o-template.org/">h2o</a></p>
<p>Baseado no Smarty, <a href="http://www.djangoproject.com/">Django Templates</a> e <a href="http://jinja.pocoo.org/">Jinja</a> (os dois últimos para Python).</p>
<pre name="code" class="html">
 &lt;html&gt;
 &lt;head&gt;
 &lt;title&gt;{{ page.title }}&lt;/title&gt;
 &lt;/head&gt;
 &lt;body&gt;
     {{ page.content }}
 &lt;/body&gt;
 &lt;/html&gt;
</pre>
<pre name="code" class="php">
$h2o = new h2o('index.html');
$page = array(
  'title' => 'title of a page',
  'body' => 'Hello world'
);
echo $h2o->render(compact('page'));
</pre>
<p><a href="http://pear.php.net/package/HTML_Template_Flexy/">PEAR Flexy</a></p>
<p>Entre os projetos disponíveis no PEAR (<a href="http://pear.php.net/package/HTML_Template_PHPLIB/">PHPLIB</a>, <a href="http://pear.php.net/package/HTML_Template_Sigma/">Sigma</a> e <a href="http://pear.php.net/package/HTML_Template_IT/">IT</a>) esse é o melhor. </p>
<p>Tem como desvantagem o fato de ter que definir as propriedades da sua classe como public (pelo menos dá para trabalhar com classes), linhas de includes e configurações exageradas (não presentes no exemplo abaixo), e algumas automações que precisam ser bem explicadas senão o programador (usuário) fica doido. Além de ter que codificar muito mais linhas se compararmos com os demais exemplos. </p>
<pre name="code" class="html">
 &lt;html&gt;
 &lt;head&gt;
 &lt;title&gt;{title}&lt;/title&gt;
 &lt;/head&gt;
 &lt;body&gt;
    &lt;!-- o valor do input será adicionado em $element['input'] --&gt;
    Input Box: &lt;input name="input" /&gt;
    &lt;ul&gt;
        &lt;!-- isso é o mesmo que foreach ($numbers as $number => $string) --&gt;
        &lt;li flexy:foreach="numbers,number,string" &gt;
            &lt;a href="mypage.html?id={number}"&gt;{string}&lt;/a&gt;
        &lt;/li&gt;
    &lt;/ul&gt;
    &lt;!-- chamando o método da classe --&gt;
    {someMethod()}
 &lt;/body&gt;
 &lt;/html&gt;
</pre>
<pre name="code" class="php">
class controller_test  {

    var $title;
    var $numbers = array();
    var $elements = array();

    function controller_test() {
        $this->start();
        $this->output();
    }

    function start() {
        $this->title = "Hello World";
        // create an HTML Element for the form element.
        $this->elements['input'] = new HTML_Template_Flexy_Element;
        $this->elements['input']->setValue('Hello');

        for ($i = 1;$i< 5;$i++) {
            $this->numbers[$i] = "Number $i";
        }
    }

    function output() {
        $output = new HTML_Template_Flexy();
        $output->compile("home.html");
        $output->outputObject($this,$this->elements);
    }

    function someMethod() {
        return "Hello From A Method";
    }

}
new controller_test();
</pre>
<p><em>Todos os exemplos a cima foram retirados dos próprios sites dos projetos, sofrendo alterações afim de minimizar as linhas e focar em suas caracterísicas, vantagens e desvantagens.</em></p>
<p>Em meados do ano passado comecei escrever uma engine baseada no <a href="https://javaserverfaces.dev.java.net/">JSF</a>+<a href="https://facelets.dev.java.net/">Facelets</a> (Java) e nesse mês voltei a trabalhar nela e espero que no próximo ano (2011) já tenha uma versão liberada (farei um post sobre).</p>
<div class="shr-publisher-315"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><div class='shareaholic-like-buttonset' style='float:none;height:30px;'><a class='shareaholic-fblike' data-shr_layout='button_count' data-shr_showfaces='false' data-shr_href='http%3A%2F%2Frogeriolino.com%2F2010%2F09%2F09%2Fphp-template-engines%2F' data-shr_title='PHP%3A+Template+Engines'></a><a class='shareaholic-googleplusone' data-shr_size='medium' data-shr_count='true' data-shr_href='http%3A%2F%2Frogeriolino.com%2F2010%2F09%2F09%2Fphp-template-engines%2F' data-shr_title='PHP%3A+Template+Engines'></a><a class='shareaholic-tweetbutton' data-shr_count='horizontal' data-shr_href='http%3A%2F%2Frogeriolino.com%2F2010%2F09%2F09%2Fphp-template-engines%2F' data-shr_title='PHP%3A+Template+Engines'></a></div><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://rogeriolino.com/2010/09/09/php-template-engines/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>PHP: Socket Class</title>
		<link>http://rogeriolino.com/2010/04/22/php-socket-class/</link>
		<comments>http://rogeriolino.com/2010/04/22/php-socket-class/#comments</comments>
		<pubDate>Thu, 22 Apr 2010 19:19:03 +0000</pubDate>
		<dc:creator>Rogério Alencar Lino Filho</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[class]]></category>
		<category><![CDATA[classe]]></category>
		<category><![CDATA[connection]]></category>
		<category><![CDATA[license]]></category>
		<category><![CDATA[socket]]></category>
		<category><![CDATA[source]]></category>
		<category><![CDATA[tcp]]></category>
		<category><![CDATA[udp]]></category>

		<guid isPermaLink="false">http://rogeriolino.com/?p=284</guid>
		<description><![CDATA[<p> [UPDATE 16-05-2012]<br /> Criei um projeto no Github e também adicionei suporte ao Websocket.<br /> <a href="http://rogeriolino.com/2012/05/16/html5-websocket">Clique aqui para ver o post novo</a><br /> [/UPDATE] </p> <p>Muitas linguagens oferecem suporte a <a href="http://en.wikipedia.org/wiki/Internet_socket">Sockets</a>, e com <a href="http://php.net/manual/en/book.sockets.php">PHP</a> não é diferente, porém a falta de orientação a objetos nas funções do PHP pode ser um [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><blockquote><p>
<strong>[UPDATE 16-05-2012]</strong><br />
Criei um projeto no Github e também adicionei suporte ao Websocket.<br />
<a href="http://rogeriolino.com/2012/05/16/html5-websocket">Clique aqui para ver o post novo</a><br />
<strong>[/UPDATE]</strong>
</p></blockquote>
<p>Muitas linguagens oferecem suporte a <a href="http://en.wikipedia.org/wiki/Internet_socket">Sockets</a>, e com <a href="http://php.net/manual/en/book.sockets.php">PHP</a> não é diferente, porém a falta de orientação a objetos nas funções do PHP pode ser um inconveniente para algumas pessoas. E como eu me incluo entre essas pessoas, quando precisei utilizar sockets em PHP acabei criando um classe para englobar essas funções soltas e fornecer tratamento a erros.</p>
<pre name="code" class="php">
/**
 * Copyright 2010 http://rogeriolino.com
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Socket
 *
 * @author rogeriolino
 */
class Socket {

    private $port     = 3000;
    private $address  = "localhost";
    private $blocking = true;

    private $buffer   = 2048;
    private $backlog  = 5;

    private $type     = SOCK_STREAM;
    private $family   = AF_INET;
    private $protocol = SOL_TCP;

    private $resource;

    /**
     * Socket constructor
     * @param  $resource
     */
    public function  __construct($resource = null) {
        if ($resource == null) {
            $this-&gt;resource = socket_create($this-&gt;family, $this-&gt;type, $this-&gt;protocol);
        } else {
            $this-&gt;resource = $resource;
        }
    }

    /**
     * Returns the socket port
     * @return int
     */
    public function getPort() {
        return $this-&gt;port;
    }

    /**
     * Define the socket port
     * @param int $port
     */
    public function setPort($port) {
        $this-&gt;port = $port;
    }

    /**
     *
     * @return string
     */
    public function getAddress() {
        return $this-&gt;address;
    }

    public function setAddress($address) {
        $this-&gt;address = $address;
    }

    /**
     * Returns if the socket is blocking mode
     * @return boolean
     */
    public function isBlocking() {
        return $this-&gt;blocking;
    }

    /**
     * Defines whether the socket is blocking or nonblocking mode
     * @param boolean $block
     */
    public function setBlocking($blocking) {
        $this-&gt;blocking = ($blocking == true);
        $this-&gt;updateBlockingMode();
    }

    /**
     * Returns the socket communication type
     * @return int
     */
    public function getType() {
        return $this-&gt;type;
    }

    /**
     * Define the socket communication type
     * @param int $type
     */
    public function setType($type) {
        if ($type == SOCK_STREAM || $type == SOCK_DGRAM || $type == SOCK_SEQPACKET || $type == SOCK_RAW || $type == SOCK_RDM) {
            $this-&gt;type = $type;
        } else {
            throw new SocketException("Invalid socket communication type");
        }
    }

    /**
     * Returns the socket protocol family
     * @return int
     */
    public function getFamily() {
        return $this-&gt;family;
    }

    /**
     * Define the socket protocol family
     * @param int $family
     */
    public function setFamily($family) {
        if ($family == AF_INET || $family == AF_INET6 || $family == AF_UNIX) {
            $this-&gt;family = $family;
        } else {
            throw new SocketException("Invalid socket protocol family");
        }
    }

    /**
     * Returns the socket protocol
     * @return int
     */
    public function getProtocol() {
        return $this-&gt;protocol;
    }

    /**
     * Define the socket protocol, must be compatible whit the protocol family
     * @param int $protocol
     */
    public function setProtocol($protocol) {
        if ($protocol == SOL_TCP || $protocol == SOL_UDP || $protocol == SOL_SOCKET) {
            $this-&gt;protocol = $protocol;
        } else {
            throw new SocketException("Invalid socket protocol");
        }
    }

    /**
     * Binds to a socket
     * @throws SocketException
     */
    public function bind() {
        if (socket_bind($this-&gt;resource, $this-&gt;address, $this-&gt;port) === false) {
            throw new SocketException("Socket bind failed: " . $this-&gt;error());
        }
    }

    /**
     * Listens for a connection on a socket
     * @throws SocketException
     */
    public function listen() {
        if (socket_listen($this-&gt;resource, $this-&gt;backlog) === false) {
            throw new SocketException("Socket listen failed: " . $this-&gt;error());
        }
    }

    /**
     * Accepts a connection
     * @throws SocketException
     * @return Socket
     */
    public function accept() {
        $sock = socket_accept($this-&gt;resource);
        if ($sock === false) {
            throw new SocketException("Socket accept failed: " . $this-&gt;error());
        }
        return new Socket($sock);
    }

    /**
     * Reads data from the connected socket
     * @return string
     */
    public function read() {
        $data = "";
        while (($m = socket_read($this-&gt;resource, $this-&gt;buffer)) != "") {
            $data .= $m;
        }
        return $data;
    }

    /**
     * Write the data to connected socket
     * @param string $message
     */
    public function write($data) {
        socket_write($this-&gt;resource, $data, strlen($data));
    }

    /**
     * Initiates a connection on a socket
     * @throws SocketException
     * @return boolean
     */
    public function connect() {
        try {
            return socket_connect($this-&gt;resource, $this-&gt;address, $this-&gt;port);
        } catch (SocketException $e) {
            return false;
        }
    }

    /**
     * Close the socket connection
     */
    public function close() {
        socket_close($this-&gt;resource);
    }

    private function updateBlockingMode() {
        if ($this-&gt;blocking) {
            socket_set_block($this-&gt;resource);
        } else {
            socket_set_nonblock($this-&gt;resource);
        }
    }

    private function error() {
        return socket_strerror(socket_last_error($this-&gt;resource));
    }

}
</pre>
<p>Classe para as exceções:</p>
<pre name="code" class="php">/**
 * Copyright 2010 http://rogeriolino.com
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * SocketException
 *
 * @author rogeriolino
 */
class SocketException extends Exception {

    public function  __construct($message, $code = 0, $previous = null) {
        $this-&gt;message = $message;
        $this-&gt;code = $code;
        $this-&gt;message = $previous;
    }

}
</pre>
<p>Espero que seja de bom aproveito.</p>
<div class="shr-publisher-284"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><div class='shareaholic-like-buttonset' style='float:none;height:30px;'><a class='shareaholic-fblike' data-shr_layout='button_count' data-shr_showfaces='false' data-shr_href='http%3A%2F%2Frogeriolino.com%2F2010%2F04%2F22%2Fphp-socket-class%2F' data-shr_title='PHP%3A+Socket+Class'></a><a class='shareaholic-googleplusone' data-shr_size='medium' data-shr_count='true' data-shr_href='http%3A%2F%2Frogeriolino.com%2F2010%2F04%2F22%2Fphp-socket-class%2F' data-shr_title='PHP%3A+Socket+Class'></a><a class='shareaholic-tweetbutton' data-shr_count='horizontal' data-shr_href='http%3A%2F%2Frogeriolino.com%2F2010%2F04%2F22%2Fphp-socket-class%2F' data-shr_title='PHP%3A+Socket+Class'></a></div><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://rogeriolino.com/2010/04/22/php-socket-class/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>PHP: Annotations</title>
		<link>http://rogeriolino.com/2010/03/26/php-annotations/</link>
		<comments>http://rogeriolino.com/2010/03/26/php-annotations/#comments</comments>
		<pubDate>Fri, 26 Mar 2010 13:21:12 +0000</pubDate>
		<dc:creator>Rogério Alencar Lino Filho</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[addendum]]></category>
		<category><![CDATA[annotations]]></category>
		<category><![CDATA[doctrine]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[jpa]]></category>
		<category><![CDATA[persistence]]></category>
		<category><![CDATA[reflection]]></category>

		<guid isPermaLink="false">http://rogeriolino.com/?p=249</guid>
		<description><![CDATA[<p>É indiscutível a agilidade e facilidade de configuração que as annotations provêm no <a href="http://java.sun.com/">Java</a>, e com o objetivo de trazer tal comodidade ao <a href="http://php.net">PHP</a> surgiu o projeto <a href="http://code.google.com/p/addendum/">Addendum</a> &#8211; escrito por <a href="http://jsmf.net/">Jan Suchal</a> &#8211; que permite via <a href="http://en.wikipedia.org/wiki/Reflection_(computer_science)">Reflection</a> acessar as annotations das classes.</p> <p>As annotations devem ser escritas em blocos [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>É indiscutível a agilidade e facilidade de configuração que as annotations provêm no <a href="http://java.sun.com/">Java</a>, e com o objetivo de trazer tal comodidade ao <a href="http://php.net">PHP</a> surgiu o projeto <a href="http://code.google.com/p/addendum/">Addendum</a> &#8211; escrito por <a href="http://jsmf.net/">Jan Suchal</a> &#8211; que permite via <a href="http://en.wikipedia.org/wiki/Reflection_(computer_science)">Reflection</a> acessar as annotations das classes.</p>
<p>As annotations devem ser escritas em blocos de comentários, uma vez que o <a href="http://thesmithfam.org/blog/2006/05/07/php-the-operator/">@</a> (caracter que inicia uma annotation) é um caractere reservado no PHP. Elas podem ser mono ou multi valoradas de acordo com os exemplos abaixo.</p>
<pre name="code" class="php">

// Custom annotation
class Persistent extends Annotation {}

// Custom annotation
class Table extends Annotation {}

// Multi valued annotation
class Secured extends Annotation {
   public $role;
   public $level;
}

/**
 * @Persistent
 * @Table("people")
 * @Secured(role = "admin", level = 2)
 */
class Person {
   // some code
}

// getting the annotation by class name
$reflection = new ReflectionAnnotatedClass('Person');

// getting the annotation by instance
$person = new Person();
$reflection = new ReflectionAnnotatedClass($person);

// true
$reflection->hasAnnotation('Persistent'); 

// contains string "people"
$reflection->getAnnotation('Table')->value; 
</pre>
<p>E seguindo na mesma onda da <a href="http://java.sun.com/javaee/technologies/persistence.jsp">JPA</a>, a <a href="http://www.doctrine-project.org/blog/php-5-3-and-doctrine-2-0-teaser">versão 2.0 do projeto Doctrine</a> implementou também a mesma funcionalidade e agora possui suas próprias annotations facilitando a configuração das classes de persistência e seus relacionamentos.</p>
<pre name="code" class="php">

/**
 * @DoctrineEntity(tableName="cms_articles")
 */
class CmsArticle {

   /**
    * @DoctrineId
    * @DoctrineColumn(type="integer")
    * @DoctrineIdGenerator("auto")
    */
   public $id;

   /**
    * @DoctrineColumn(type="varchar", length=255)
    */
   public $topic;

   /**
    * @DoctrineColumn(type="varchar")
    */
   public $text;

   /**
    * @DoctrineManyToOne(targetEntity="CmsUser",
           joinColumns={"user_id" = "id"})
    */
   public $user;

   /**
    * @DoctrineOneToMany(targetEntity="CmsComment", mappedBy="article")
    */
   public $comments;
}
</pre>
<div class="shr-publisher-249"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><div class='shareaholic-like-buttonset' style='float:none;height:30px;'><a class='shareaholic-fblike' data-shr_layout='button_count' data-shr_showfaces='false' data-shr_href='http%3A%2F%2Frogeriolino.com%2F2010%2F03%2F26%2Fphp-annotations%2F' data-shr_title='PHP%3A+Annotations'></a><a class='shareaholic-googleplusone' data-shr_size='medium' data-shr_count='true' data-shr_href='http%3A%2F%2Frogeriolino.com%2F2010%2F03%2F26%2Fphp-annotations%2F' data-shr_title='PHP%3A+Annotations'></a><a class='shareaholic-tweetbutton' data-shr_count='horizontal' data-shr_href='http%3A%2F%2Frogeriolino.com%2F2010%2F03%2F26%2Fphp-annotations%2F' data-shr_title='PHP%3A+Annotations'></a></div><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://rogeriolino.com/2010/03/26/php-annotations/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>SGA Livre</title>
		<link>http://rogeriolino.com/2010/03/18/sga-livre/</link>
		<comments>http://rogeriolino.com/2010/03/18/sga-livre/#comments</comments>
		<pubDate>Thu, 18 Mar 2010 12:51:13 +0000</pubDate>
		<dc:creator>Rogério Alencar Lino Filho</dc:creator>
				<category><![CDATA[Javascript]]></category>
		<category><![CDATA[Linux]]></category>
		<category><![CDATA[PHP]]></category>
		<category><![CDATA[Programas]]></category>
		<category><![CDATA[dataprev]]></category>
		<category><![CDATA[libjsx]]></category>
		<category><![CDATA[livre]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[opensource]]></category>
		<category><![CDATA[postgresql]]></category>
		<category><![CDATA[publico]]></category>
		<category><![CDATA[sga]]></category>
		<category><![CDATA[software]]></category>

		<guid isPermaLink="false">http://rogeriolino.com/?p=236</guid>
		<description><![CDATA[<p></p> <p>SGA LIVRE significa Sistema de Gerenciamento do Atendimento, versão Livre. É desenvolvido pela DATAPREV, totalmente baseado em tecnologias de software livre e de código aberto.</p> <p>Através do SGA é possível gerenciar filas e fluxo de atendimento em quaisquer tipos de empresas ou organizações que prestam serviço de atendimento presencial à pessoas.</p> <p>O SGA oferece [...]]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p><img class="aligncenter size-full wp-image-239" title="SGA" src="http://rogeriolino.com/wp-content/uploads/2010/03/sga_logo.jpg" alt="" width="382" height="229" /></p>
<blockquote><p><strong>SGA LIVRE</strong> significa Sistema de Gerenciamento do Atendimento, versão Livre. É desenvolvido pela DATAPREV, totalmente baseado em tecnologias de software livre e de código aberto.</p>
<p>Através do SGA é possível gerenciar filas e fluxo de atendimento em quaisquer tipos de empresas ou organizações que prestam serviço de atendimento presencial à pessoas.</p>
<p>O SGA oferece o controle de filas de atendimento através de emissão de senhas e chamada das mesmas através de painéis. As filas de atendimento podem conter um único serviço ou um grupo de serviços. Os painéis podem chamar um, vários ou todos os serviços. Uma unidade de atendimento pode ter vários painéis.</p>
<p>O SGA é mais do que um sistema de controle de filas. Ao gerenciar o fluxo de atendimento, o sistema apresenta uma série de recursos que auxiliam na gerência e administração das unidades de atendimento.</p>
<p>Fornece uma diversidade de informações gerenciais preciosas, através de relatórios, estatísticas e gráficos avançados sobre atendimentos de uma unidade, de um grupo de unidades ou de todas elas. É possível obter estatísticas e tempos médios de atendimento por atendente, por período e por unidade, entre outras. Pode-se obter dados detalhados ou agregados.</p>
<p>As informações gerenciais fornecidas pelo SGA possibilitam aos gestores planejar, acompanhar, monitorar, otimizar e agilizar o atendimento aos clientes.</p>
<p>fonte: <a href="http://www.softwarepublico.gov.br/ver-comunidade?community_id=15719494">http://www.softwarepublico.gov.br/ver-comunidade?community_id=15719494</a></p></blockquote>
<p>Não é novidade o lançamento da versão livre do SGA, porém é com muito orgulho que hoje vejo este software ganhando força no cenário nacional, e também por ter participado do seu desenvolvimento. O software foi desenvolvido em <a href="http://php.net">PHP</a> fornecendo uma camada para abstração do <a href="http://en.wikipedia.org/wiki/Relational_database_management_system">RDMS</a>, utilizando como interface de acesso o <a href="http://php.net/manual/en/book.pdo.php">PDO</a> (suporte padrão ao <a href="http://www.postgresql.org">PostgreSQL</a>). Tal contribuição foi desde definir a estrutura do sistema, passando por diagramação, HTML, CSS, até a programação PHP e Javascript.</p>
<div id="attachment_238" class="wp-caption aligncenter" style="width: 304px"><a href="http://rogeriolino.com/wp-content/uploads/2010/03/sga_instalacao.jpg"><img class="size-medium wp-image-238" title="SGA: Instalação" src="http://rogeriolino.com/wp-content/uploads/2010/03/sga_instalacao-294x300.jpg" alt="" width="294" height="300" /></a><p class="wp-caption-text">Tela de instalação do SGA</p></div>
<p>Dividido em módulos é fácil customizar a ferramenta para atender as  necessidades específicas de qualquer centro de atendimento. Para facilitar o uso de requisições assíncronas no sistema foi  utilizada o código <a href="http://pt.wikipedia.org/wiki/AJAX_(programação)">Ajax</a> da lib escrita por mim e já comentada nesse blog (<a href="http://rogeriolino.com/2009/03/11/javascript-libjsx/">libjsx</a>, <a href="http://code.google.com/p/libjsx/source/browse/trunk/org/libjsx/ajax/Ajax.js">Ajax.js</a>).</p>
<p><a href="http://rogeriolino.com/wp-content/uploads/2010/03/sga_atendimento.jpg"></a></p>
<div id="attachment_237" class="wp-caption aligncenter" style="width: 310px"><a href="http://rogeriolino.com/wp-content/uploads/2010/03/sga_atendimento.jpg"><img class="size-medium wp-image-237" title="SGA: Atendimento" src="http://rogeriolino.com/wp-content/uploads/2010/03/sga_atendimento-300x239.jpg" alt="" width="300" height="239" /></a><p class="wp-caption-text">Tela de atendimento do SGA</p></div>
<p>Quem quiser utilizar ou contribuir com o projeto basta se cadastrar no site <a title="Portal do Software Público Brasileiro" href="http://www.softwarepublico.gov.br/">http://www.softwarepublico.gov.br/</a> e acessar a página da <a href="http://www.softwarepublico.gov.br/ver-comunidade?community_id=15719494">comunidade</a>.</p>
<div class="shr-publisher-236"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><div class='shareaholic-like-buttonset' style='float:none;height:30px;'><a class='shareaholic-fblike' data-shr_layout='button_count' data-shr_showfaces='false' data-shr_href='http%3A%2F%2Frogeriolino.com%2F2010%2F03%2F18%2Fsga-livre%2F' data-shr_title='SGA+Livre'></a><a class='shareaholic-googleplusone' data-shr_size='medium' data-shr_count='true' data-shr_href='http%3A%2F%2Frogeriolino.com%2F2010%2F03%2F18%2Fsga-livre%2F' data-shr_title='SGA+Livre'></a><a class='shareaholic-tweetbutton' data-shr_count='horizontal' data-shr_href='http%3A%2F%2Frogeriolino.com%2F2010%2F03%2F18%2Fsga-livre%2F' data-shr_title='SGA+Livre'></a></div><div style="clear: both; min-height: 1px; height: 3px; width: 100%;"></div><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://rogeriolino.com/2010/03/18/sga-livre/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

