<?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>Polar Geek &#187; php</title>
	<atom:link href="http://www.polargeek.net/tag/php/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.polargeek.net</link>
	<description>Polar Geek es un blog sobre desarrollo web en general (php, Javascript, jquery, css..), diseño, programación y recursos de todo tipo.</description>
	<lastBuildDate>Wed, 01 Sep 2010 11:58:46 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>PHP Principiantes: Instalación</title>
		<link>http://www.polargeek.net/php-principiantes-instalacion/</link>
		<comments>http://www.polargeek.net/php-principiantes-instalacion/#comments</comments>
		<pubDate>Tue, 31 Aug 2010 05:45:41 +0000</pubDate>
		<dc:creator>José</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[principiantes]]></category>

		<guid isPermaLink="false">http://www.polargeek.net/?p=1739</guid>
		<description><![CDATA[Con este post inicio una serie de artículos sobre PHP, desde 0. Asumiré que se tiene un poco de idea de programación pero poco más, así que si no sabes programar en PHP y quieres aprender este es el camino, al menos el que he preparado para tí. PHP y su entorno PHP y el [...]]]></description>
			<content:encoded><![CDATA[<p>Con este post inicio una serie de artículos sobre PHP, desde 0. Asumiré que se tiene un poco de idea de programación pero poco más, así que si no sabes programar en PHP y quieres aprender este es el camino, al menos el que he preparado para tí.</p>
<h2>PHP y su entorno</h2>
<h3>PHP y el servidor</h3>
<p>Lo primero que debemos aprender es qué es PHP y que papel tiene en el desarollo web. Pues bien, PHP es un lenguaje de programación de uso gratuito y del lado del servidor, esto significa que haremos programas para que se ejecuten en un servidor, cuando alguien, normalmente un navegador, nos pida o envíe datos.</p>
<p>Para entenderlo mejor echa un vistazo al siguiente esquema, que muestra una petición GET:</p>
<div class="img"><img src="http://static.polargeek.net/uploads/getpost/ejemplo_get.jpg" alt="Ejemplo GET" /></div>
<p>Pues bien, nuestros scripts estarán en el lado de la derecha, de tal forma que normalmente se pedirán a raíz de una petición, como he dicho antes.</p>
<h3>Influencias de PHP</h3>
<p>La sintaxis es muy similar a la C, así que si sabes este lenguaje tienes mucho ganado, por supuesto también si sabes Java, ya que también tiene la sintaxis similar a C.</p>
<p>Además de C, PHP tiene muchas influencias, una de ellas y la más notable desde el principio es que las variables tengan un símbolo de dólar ($) al principio, pues bien, esto viene de Perl. Otros que de los que deriva son Python o C++, pero no te preocupes porque iremos paso a paso sobre todo.</p>
<h3>Tipo de lenguaje</h3>
<p>Si sabes otros lenguajes probablemente te ayude a su aprendizaje saber que PHP es un lenguaje multiparadigma, soportando la orientación a objetos y la programación imperativa. Si no sabes lo que estos palabros significan no te preocupes por ahora, paso a paso irás entendiendo lo que esto implica para nosotros como desarrolladores.</p>
<h2>Instalación de PHP</h2>
<p>Bueno queremos programar en PHP pero primero tendremos que instalarlo. Para ello veamos distintos tipos de sistemas operativos y cómo instalarlo en cada uno de ellos.</p>
<h3>Windows</h3>
<p>Descargar el programa WAMP de <a href="http://www.wampserver.com/en/index.php">aquí</a>. Recuerda que no solo estás instalando PHP sino también Apache y MySQL, necesario el primero para PHP y el segundo necesario para el caso de que utilicemos bases de datos, que también lo haremos.</p>
<p>Si no te gusta esta opción y quieres instalarlo a mano, <a href="http://dotpress.wordpress.com/2007/03/22/wamp-guia-para-instalar-php-en-apache-sobre-windows/">aquí</a> tienes una excelente guía paso a paso que estoy seguro te ayudará.</p>
<h3>Mac</h3>
<p>Para Mac existe una solución similar a WAMP llamada MAMP (las siglas son Mac | Apache | MySQL | PHP). A modo de curiosidad cuando veas ofertas para programadores LAMP están pidiendo gente que sea capaz de majer Apache, Linux, MySQL y PHP o Python, aunque esto último es menos común.</p>
<p>Pero volviendo al asunto que nos ocupa, la aplicación la puedes descargar de la <a href="http://www.mamp.info/en/index.html">página oficial de MAMP</a>, cuenta con una versión gratuita y otra de pago, pero en general la gratuita suele ser suficiente.</p>
<h3>Linux y otros entornos Unix</h3>
<p>En estos entornos normalmente los documentos que servirá Apache estarán en /var/www, a diferencia de Windows y Mac que viene marcado por el programa de instalación que hayamos usado. En cualquier caso suele ser configurable así que no importa demasiado, pero debes tenerlo en cuenta para alojar tus scripts de PHP que haremos más adelante.</p>
<p>Para los usuarios de Ubuntu/Debian, que suelen ser la mayoría os dejo <a href="http://www.vensign.com/blog/instalar-un-servidor-lamp-en-ubuntulinux.html">este tutorial</a>, también genial explicado.</p>
<p>Y para los que no usáis una distribución basada en Debian, pues <a href="http://fried.wordpress.com/2009/07/11/instalar-apache-mysql-php-lamp-en-fedora-11/">aquí</a> tenís cómo instalarlo en Fedora.</p>
<h2>Haciendo nuestro primer script</h2>
<p>Hagamos ahora el script más sencillo del mundo, si, es un hola mundo. Para ello cremos un archivo vacío de texto normal y ponemos la etiqueta de inicio y de fin de PHP, quedando:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
  <span style="color: #666666; font-style: italic;">//Código</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p>Ahora mostramos un mensaje por pantalla, con echo, que saca el string que le demos por la salida estándar, en este caso el html que muestra el navegador.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
  <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">'Hola Mundo'</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p>Pues con esto en un archivo, lo guardamos como index.php, por ejemplo y lo ponemos en el directorio que en Apache hayamos configurado, esto depende del sistema operativo y la forma de instalarlo así que no hay un sitio fijo para todos, pero seguro que en el programa que hayas usado te viene. En Mac, con MAMP suele estar en Sites, bajo la carpeta de usuario.</p>
<h2>Sólo es el comienzo</h2>
<p>Bien ya podemos hacer scripts en PHP y que funcionen y además no tendremos problemas para conectarnos con MySQL si has seguido las instrucciones de los posts. A partir de ahora aprenderemos PHP íntegramente sin preocuparnos demasiado por el entorno. Espero que te sea útil, y si es así házmelo saber en los comentarios, nos queda un largo camino por delante. Un saludo.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.polargeek.net/php-principiantes-instalacion/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Librerías útiles de PHP</title>
		<link>http://www.polargeek.net/librerias-utiles-de-php/</link>
		<comments>http://www.polargeek.net/librerias-utiles-de-php/#comments</comments>
		<pubDate>Thu, 17 Jun 2010 21:46:26 +0000</pubDate>
		<dc:creator>José</dc:creator>
				<category><![CDATA[Recursos]]></category>
		<category><![CDATA[paquetes]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.polargeek.net/?p=1548</guid>
		<description><![CDATA[Recopilatorio de librerías que te pueden sacar de un apuro. Desde generación de PDF&#8217;s con PHP hasta gráficos estadísticos, pasando por envío de correos, o generación de passwords. Estoy seguro de que alguna librería del listado te resultará útil. SimplePie. Parsear RSS Analizar datos periódicamente, crear un lector de feeds online, o simplemente extraer información [...]]]></description>
			<content:encoded><![CDATA[<p>Recopilatorio de librerías que te pueden sacar de un apuro. Desde generación de PDF&#8217;s con PHP hasta gráficos estadísticos, pasando por envío de correos, o generación de passwords. Estoy seguro de que alguna librería del listado te resultará útil.</p>
<h2>SimplePie. Parsear RSS</h2>
<p>Analizar datos periódicamente, crear un lector de feeds online, o simplemente extraer información automáticamente para otros propósitos. Los RSS son casi un estándar en cuánto a la lectura periódica de blogs o páginas se refiere, así que esta clase es realmente útil.</p>
<div class="img">
	<img src="http://static.polargeek.net/uploads/clasesPHP/simplepie.jpg" alt="SimplePie" title="SimplePie"/>
</div>
<p><a href="http://github.com/rmccue/simplepie/downloads">Descarga SimplePie</a> | <a href="http://simplepie.org/wiki/">Documentación</a></p>
<h2>Swift Mailer. Envío de emails</h2>
<p>Esta librería permite enviar mails a través SMTP, sendmail u otros. Soporta encriptación, adjuntos y un largo etcétera. Ha tenido una buena acogida en la comunidad y es más nuevo que PHPMailer, del que quizá has oído hablar en alguna ocasión.</p>
<div class="img">
	<img src="http://static.polargeek.net/uploads/clasesPHP/swiftmailer.jpg" alt="Swift Mailer" title="Swift Mailer"/>
</div>
<p>                            </p>
<p><a href="http://swiftmailer.org/download">Descarga Swift Mailer</a> | <a href="http://swiftmailer.org/docs/introduction">Documentación</a></p>
<h2>pChart. Gráficas con estilo</h2>
<p>A veces es inevitable tener que generar las gráficas desde PHP. En ocasiones tenemos la posiblidad de hacerlo con javascript, pero no siempre, así que esta librería será útil en esos casos. Tiene una buena documentación, por lo que la clase es fácilmente ampliable.</p>
<div class="img">
	<img src="http://static.polargeek.net/uploads/clasesPHP/pchart.jpg" alt="pChart" title="pChart"/>
</div>
<p><a href="http://pchart.sourceforge.net/download.php">Descargar pChart</a> | <a href="http://pchart.sourceforge.net/documentation.php">Documentación</a> | <a href="http://pchart.sourceforge.net/demo.php">Demos</a></p>
<h2>FPDF. Generación de PDF&#8217;s</h2>
<p>Esta librería facilita muchísimo el proceso de generación de PDF&#8217;s desde PHP. Y es algo bastante necesitado en programación, con posibilidades como generación automática de informes desde la base de datos.</p>
<div class="img">
	<img src="http://static.polargeek.net/uploads/clasesPHP/fpdf.jpg" alt="FPDF" title="FPDF"/>
</div>
<p><a href="http://www.fpdf.org/">Descarga y Documentación de FPDF</a></p>
<h2>DomPDF. De HTML a PDF</h2>
<p>Convierte un documento HTML a PDF, soporta imágenes, enlaces con anchor y CSS, entre otras cosas. Es como un analizador de HTML que lo &#8220;renderiza&#8221; en forma de PDF.</p>
<div class="img">
	<img src="http://static.polargeek.net/uploads/clasesPHP/dompdf.jpg" alt="DomPDF" title="DomPDF"/>
</div>
<p><a href="http://www.digitaljunkies.ca/dompdf/downloads.php">Descarga DomPDF</a> | <a href="http://www.digitaljunkies.ca/dompdf/doc/">Documentación</a> | <a href="http://www.digitaljunkies.ca/dompdf/examples.php">Ver demo</a></p>
<h2>Text Password. Creación de Passwords aleatorias</h2>
<p>Permite la generación de claves pronunciables o no, y es muy fácil de usar, la verdad. Es interesante como está implementado también, así que échale un vistazo al código si quieres.</p>
<div class="img">
	<img src="http://static.polargeek.net/uploads/clasesPHP/textPassword.jpg" alt="Text Password" title="Text Password"/>
</div>
<p><a href="http://pear.php.net/package/Text_Password/download">Descarga Text Password</a> | <a href="http://pear.php.net/package/Text_Password/docs">Documentación</a></p>
<h2>Akismet. Protegerse del spam</h2>
<p>El spam es junto con IE los dos problemas creados más absurdos y molestos que existen en Internet. Para lo primero podemos usar Akismet, para lo segundo no podemos hacer demasiado. En principio es gratuito si no tienes una empresa muy grande o un blog con demasiado éxito, pero puedes ver los detalles en la página de Akismet.</p>
<div class="img">
	<img src="http://static.polargeek.net/uploads/clasesPHP/akismet.jpg" alt="Akismet" title="Akismet"/>
</div>
<p><a href="http://akismet.com/download/">Descarga Akismet</a> | <a href="http://www.achingbrain.net/stuff/php/akismet">Librería PHP5 para usar Akismet</a></p>
<h2>Extra. Pear 550+ paquetes</h2>
<p>Pear es, en resumen, una biblioteca de código estructurada, donde puedes acceder a más de 550 paquetes para realizar tareas comunes, y así evitar tener que programarlas de nuevo. Cada paquete tiene un equipo de desarrollo independiente, así que algunos pueden estar más actualizados que otros, pero casi todos resultan útiles. Así que en el enlace puedes ver la lista de paquetes y cómo descargarlos.</p>
<div class="img">
	<img src="http://static.polargeek.net/uploads/clasesPHP/pear.jpg" alt="Pear" title="Pear"/>
</div>
<p>                             </p>
<p><a href="http://pear.php.net/">Página oficial de Pear</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.polargeek.net/librerias-utiles-de-php/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>¿Qué framework de PHP debería elegir?</title>
		<link>http://www.polargeek.net/que-framework-de-php-deberia-elegir/</link>
		<comments>http://www.polargeek.net/que-framework-de-php-deberia-elegir/#comments</comments>
		<pubDate>Sun, 13 Jun 2010 00:51:57 +0000</pubDate>
		<dc:creator>José</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.polargeek.net/?p=1530</guid>
		<description><![CDATA[Características a tener en cuenta al elegir framework Probablemente casi todos los desarrolladores que eligen un framework de PHP para trabajar con él por primera vez, lo hagan sin pensar demasiado en lo que puede o no puede hacer. Quizá por una recomendación, simplemente por probar o ambas, pero al trabajar en un proyecto tenemos [...]]]></description>
			<content:encoded><![CDATA[<h2>Características a tener en cuenta al elegir framework</h2>
<p>Probablemente casi todos los desarrolladores que eligen un framework de PHP para trabajar con él por primera vez, lo hagan sin pensar demasiado en lo que puede o no puede hacer. Quizá por una recomendación, simplemente por probar o ambas, pero al trabajar en un proyecto tenemos que tener en cuenta que cosas podemos esperar de un framework y cuáles no. Veamos las característica más importantes a tener en cuenta.</p>
<div class="img">
	<img src="http://static.polargeek.net/uploads/comparativa_mvc/logos_frameworks.jpg" alt="Logos Frameworks" title="Logos Frameworks"/>
</div>
<h3>Módulos disponibles</h3>
<p>Casi todos los framework en PHP tienen una serie de librerías, módulos o helpers (cada uno lo llama de una forma) que básicamente consisten en una serie de funciones &#8220;extra&#8221; que tenemos disponibles para trabajar con ellas. Normalmente se agrupan en archivos, como funciones relacionadas con arrays, o funciones relacionadas con strings.</p>
<p>Un ejemplo de este tipo de funciones puede ser repeater(), del helper de strings de CodeIgniter que hace simplemente esto: </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$string</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;No volveré a decir tacos en clase.&quot;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> repeater<span style="color: #009900;">&#40;</span><span style="color: #000088;">$string</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">5</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>En la salida repite 5 veces la frase dada. Es una función de utilidad discutible, puesto que sustituye a un simple for de manera elegante, pero tomémoslo como un ejemplo de funciones que aportan los framework y que no tenemos que implementar. Hay algunos módulos, por ejemplo para parsear RSS, o lidiar más fácilmente con las bases de datos.</p>
<h3>Versión de PHP</h3>
<p>Quizá no parezca importante para trabajar en nuestros ordenadores, pero no siempre tenemos acceso a la última versión de PHP, así que es importante tener claro si vamos a trabajar en una versión u otra qué framework elegir.</p>
<h3>Desarrollo activo</h3>
<p>Es de suma importancia que elijas un framework que se encuentre bajo desarrollo activo. Es decir, que el autor o autores no hayan abandonado el proyecto hace tiempo. Esto es básicamente por dos razones: </p>
<ol>
<li>Cuando tengas una duda habrá desarrolladores para contestarla, interesados también en el framework. Si no estuviera bajo desarrollo, nadie se preocuparía de usarlo y no habría nadie que te pudiera ayudar.</li>
<li>El desarrollo de PHP afectará al desarrollo del framework por lo que mejorará. La implementación interna de los frameworks de PHP es, lógicamente, en PHP. Como sabrás es un lenguaje que está en un desarrollo intensísimo, y muchas funciones se convierten en <i>deprecated</i> (antiguas, que no se aconseja su uso) en poco tiempo. Si el framework está evolucionando corregirá este tipo de implementaciones con las nuevas versiones proporcionadas por PHP.</li>
</ol>
<p>A veces también conviene tener en cuenta quién está detrás de cada framework. Por ejemplo detrás del framework Zend está la empresa que fue fundada por los creadores de PHP tal y como lo conocemos hoy. Así que es casi una garantía de éxito que ese framework llegara a triunfar.</p>
<h3>Modelo Vista Controlador (MVC)</h3>
<p>Modelo Vista Controlador es un patrón de diseño que se basa en dividir la implementación en tres partes:</p>
<ul>
<li><strong>Modelo. </strong> Normalmente es la representación de la información. Si vamos a tratar con coches y hacemos una clase &#8220;coches&#8221;, esta clase será nuestra parte modelo, a grandes rasgos.</li>
<li><strong>Vista. </strong> La interfaz de usuario, en desarrollo web suele ser la propia web con el HTML y CSS.</li>
<li><strong>Controlador. </strong> El encargado de recibir acciones y actuar en consecuencia, por ejemplo, si el usuario rellena un formulario y me lo envía en controlador será el encargado de manejar esa información.</li>
</ul>
<p>Además, y sin entrar en muchas más profundidad sobre el tema para no desviarnos, hay relaciones entre estas partes, las más importantes suelen ser estas: </p>
<div class="img">
	<img src="http://static.polargeek.net/uploads/comparativa_mvc/esquema_MVC.png" alt="Esquema Modelo Vista Controlador" title="Esquema Modelo Vista Controlador"/>
</div>
<p>Por lo tanto si queremos desarrollar con este patrón tenemos que ver si el framework está orientado a él o no. Aunque te adelanto que la mayoría lo están.</p>
<h3>Curva de aprendizaje</h3>
<p>Esta no es tanto una característica interna de los framework, sino más bien una consecuencia de trabajar con ellos. Normalmente a mayor complejidad y funcionalidad más tiempo se tarda en aprenderlo. Mi consejo aquí es que si vas a tardar más tiempo aprendiendo el framework que utilizándalo estás usando el framework equivocado.</p>
<p>Es decir, el tiempo que le vayas a dedicar a aprender como usar el framework si no lo conoces, debe ser proporcional al tiempo que vaya a durar un proyecto.</p>
<h3>Necesidades propias</h3>
<p>Hay muchas más características que podríamos estudiar antes de decidirnos pero como receta general solo se puede nombrar las anteriores, básicamente, porque el resto dependerá de las necesidades del proyecto. Así que si tienes oportunidad investiga un poco más sobre cada característica que te ofrezca el framework que elijas. Porque cada uno tiene una serie de propiedades, que intentaré comparar a contuación y que lo hacen único.</p>
<h2>Comparativa de frameworks famosos</h2>
<p>Esta comparativa se basa en datos recopilados en diferentes webs y en las oficiales de los propios frameworks. He destacado ciertas características más o menos importantes, como puedes ver casi todos tienen de todo, siendo el más completo Zend Framework, pero quizá el que más tiempo se tarda en aprender, aunque esto depende mucho de la experiencia previa que tengas como programador y de la persona en sí.</p>
<div class="img">
	<img src="http://static.polargeek.net/uploads/comparativa_mvc/comparativa_frameworks.png" alt="Comparativa Frameworks Famosos" title="Comparativa Frameworks Famosos"/>
</div>
<p> </p>
<p>Algunas características pueden ser discutidas, puesto que se pueden conseguir instalando algo extra de manera relativamente sencilla, pero he intentado representar lo que trae el framework &#8220;de fábrica&#8221; y que realmente está listo para ser usado.</p>
<h3>Uso de módulos independientes</h3>
<p>Se ha destacado la facilidad de uso de módulos independientes sin tener que depender del resto del framework.</p>
<h3>ORM</h3>
<p>ORM (Object Relational-Maping o Mapeo objeto-relacional) es una técnica que simboliza los datos que tenemos en una base de datos con clases. De tal forma que tendremos, por ejemplo, una clase coche con los atributos X e Y y una tabla con los mismos atributos. Lo cierto es que salvo operaciones concretas no afecta demasiado al rendimiento, y facilita enormemente la programación, reduciendo líneas de código. Haré un post sobre esto en el futuro, así que no te preocupes si no lo entiendes completamente.</p>
<h2>Otras alternativas</h2>
<h3>Frameworks de PHP menos famosos</h3>
<p>Además de las alternativas mencionadas, las más famosas y utilizadas hay muchísimas más bajo desarrollo que están emergiendo y que se merecen también que le echemos un vistazo. Algunos de ellos son: <a href="http://www.pradosoft.com/">Prado</a>, <a href="http://www.yiiframework.com/">Yii</a> o <a href="http://www.akelos.org/">Akelos</a>, aunque hay muchos más.</p>
<h3>DIY (hazlo tú mismo)</h3>
<p>Hay muchos defensores de que el mejor framework que puedes usar para programar es el que te construyas tú mismo. Es decir que poco a poco crees una serie de librerías y estructuras de directorio hechas por tí y las utilices en varios proyectos.</p>
<p>En realidad es un ejercicio genial que te aconsejo encarecidamente que hagas. Te enseñará mucho de programación, pero por otra parte a veces no hay tiempo y en muchos proyectos se utilizan frameworks por el simple hecho de que están testados en muchas situaciones y el desarrollo sobre ellos en mucho más rápido.</p>
<p>Trata de identificar cuando realmente necesitas un framework, porque no siempre hará falta, y a veces la intención inicial de hacer el proyecto más rápido puede resultar en horas buscando documentación de funciones que no conoces por el simple hecho de utilizar el framework en vez de PHP simplemente.</p>
<h2>Conclusiones</h2>
<p>Como habrás podido ver elegir un framework no es algo fácil, sobre todo si el proyecto va a llevar mucho tiempo. Cosas como la documentación o el soporte de ciertas funciones de manera nativa pueden resultar en horas ahorradas de implementación, así que piénsalo bien y trata de echarle un vistazo a varios antes de elegir uno.</p>
<p>Aquí dejo una serie de enlaces para entender más en profundidad los diferentes frameworks y ciertos términos que hemos visto como MVC u ORM.</p>
<ul>
<li><a href="http://framework.zend.com/">Página Oficial de Zend</a></li>
<li><a href="http://codeigniter.com/">Página Oficial de CodeIgniter</a></li>
<li><a href="http://cakephp.org/">Página Oficial de CakePHP</a></li>
<li><a href="http://www.symfony-project.org/">Página Oficial de Symfony</a></li>
<li><a href="http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">MVC en la wikipedia</a></li>
<li><a href="http://en.wikipedia.org/wiki/Object-relational_mapping">ORM en la wikipedia</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.polargeek.net/que-framework-de-php-deberia-elegir/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>Hacer un sistema de puntuación con PHP y jQuery</title>
		<link>http://www.polargeek.net/hacer-un-sistema-de-puntuacion-con-php-y-jquery/</link>
		<comments>http://www.polargeek.net/hacer-un-sistema-de-puntuacion-con-php-y-jquery/#comments</comments>
		<pubDate>Tue, 08 Jun 2010 22:12:33 +0000</pubDate>
		<dc:creator>José</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[jquery]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.polargeek.net/?p=1494</guid>
		<description><![CDATA[Introducción En muchas páginas se utilizan sistemas de puntuación. Normalmente suelen ser de 5 estrellas, en los que la gente vota que le ha parecido del 1 al 5. Desde el punto de vista de los desarrolladores plantéa muchas cuestiones interesantes, algunas más complejas que otras. En cualquier caso no es demasiado difícil, por lo [...]]]></description>
			<content:encoded><![CDATA[<h2>Introducción</h2>
<p>En muchas páginas se utilizan sistemas de puntuación. Normalmente suelen ser de 5 estrellas, en los que la gente vota que le ha parecido del 1 al 5. Desde el punto de vista de los desarrolladores plantéa muchas cuestiones interesantes, algunas más complejas que otras. En cualquier caso no es demasiado difícil, por lo que podemos cubrirlo en un solo tutorial.</p>
<div class="img">
	<img src="http://static.polargeek.net/uploads/sistemas_puntuaciones_estrellas/final.png" alt="Resultado Final del sistema de puntuación" title="Resultado Final del sistema de puntuación"/>
</div>
<p>Aquí vamos a diseñar, implementar y sobre todo explicar como hacer un <strong>sistema de puntuación de 5 estrellas con decimales intermedios</strong>, por lo que la gente puede votar cosas como 4.5 o 1.5. Además <strong>un mismo usuario no podrá votar más de una vez</strong>, por lo que intentaremos hacer este sistema de votación lo más acorde con los gustos reales de la media de los usuarios.</p>
<div class="descarga">
<a href="http://static.polargeek.net/uploads/sistemas_puntuaciones_estrellas/puntuacion.zip" class="descargar"></a><a href="http://www.polargeek.net/wp-content/uploads/demos/puntuacion/index.html" class="demo"></a>
</div>
<h2><span>Paso 1. </span>Diseño</h2>
<p>Antes que nada tenemos que hacer el maquetado del sistema de puntuación. Tenemos que pensar en términos de medias estrellas, porque vamos a admitir la votación de 4.5, por ejemplo, como hemos comentado en la introducción. Esto plantéa la primera dificultad, porque ¿cómo hacemos para unirlas todas? o ¿cómo sabemos que el usuario está seleccionando una u otra parte de la estrella? Podrías pensar en utilizar 5 imágenes, de tres tipos, estrellas vacías, medias estrellas y estrellas enteras. Pero entonces no podrías diferenciar fácilmente si un usuario está en la parte izquierda o en la derecha. Así que es un poco más complicado que eso.</p>
<p>En realidad gran parte de la solución vendrá con jQuery, pero de momento hay un hecho a remarcar. Tenemos que usar sprites. Sprite es una imagen compuesta de varias, que se envía una vez, y con CSS se selecciona la imagen dentro del archivo que queremos mostrar. Normalmente se usa para hacer más rápida la carga de la página, porque el navegador y el servidor sólo se tienen que conectar una vez para pasar todas las imágenes en un solo archivo. Pero en nuestro caso no es esa cuestión la más importante, lo importante es que <strong>si no tuviéramos sprites, cuando cambiáramos parte de una estrella tendríamos que enviar el archivo, después de finalizar la carga de la página.</strong> Esto supone una carga innecesaria en el ancho de banda fuera de tiempo.</p>
<p>Echemos un vistazo al código HTML, será algo bastante simple, basándonos en nuestra implementación concreta y dado que solo queremos 5 estrellas.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
</pre></td><td class="code"><pre class="html4strict" style="font-family:monospace;"><span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">id</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;1&quot;</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;puntuacion&quot;</span>&gt;</span>		
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;estrella estrella_izq&quot;</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">a</span> <span style="color: #000066;">title</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;0.5/5&quot;</span> <span style="color: #000066;">href</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;#0.5&quot;</span>&gt;</span>0.5<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">a</span>&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;estrella estrella_der&quot;</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">a</span> <span style="color: #000066;">title</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;1/5&quot;</span> <span style="color: #000066;">href</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;#1&quot;</span>&gt;</span>1<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">a</span>&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;estrella estrella_izq&quot;</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">a</span> <span style="color: #000066;">title</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;1.5/5&quot;</span> <span style="color: #000066;">href</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;#1.5&quot;</span>&gt;</span>1.5<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">a</span>&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;estrella estrella_der&quot;</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">a</span> <span style="color: #000066;">title</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;2/5&quot;</span> <span style="color: #000066;">href</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;#2&quot;</span>&gt;</span>2<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">a</span>&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;estrella estrella_izq&quot;</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">a</span> <span style="color: #000066;">title</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;2.5/5&quot;</span> <span style="color: #000066;">href</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;#2.5&quot;</span>&gt;</span>2.5<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">a</span>&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;estrella estrella_der&quot;</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">a</span> <span style="color: #000066;">title</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;3/5&quot;</span> <span style="color: #000066;">href</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;#3&quot;</span>&gt;</span>3<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">a</span>&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;estrella estrella_izq&quot;</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">a</span> <span style="color: #000066;">title</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;3.5/5&quot;</span> <span style="color: #000066;">href</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;#3.5&quot;</span>&gt;</span>3.5<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">a</span>&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;estrella estrella_der&quot;</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">a</span> <span style="color: #000066;">title</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;4/5&quot;</span> <span style="color: #000066;">href</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;#4&quot;</span>&gt;</span>4<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">a</span>&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;estrella estrella_izq&quot;</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">a</span> <span style="color: #000066;">title</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;4.5/5&quot;</span> <span style="color: #000066;">href</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;#4.5&quot;</span>&gt;</span>4.5<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">a</span>&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">class</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;estrella estrella_der&quot;</span>&gt;&lt;<span style="color: #000000; font-weight: bold;">a</span> <span style="color: #000066;">title</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;5/5&quot;</span> <span style="color: #000066;">href</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;#5&quot;</span>&gt;</span>5<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">a</span>&gt;&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span> <span style="color: #808080; font-style: italic;">&lt;!-- fin puntuacion #1 --&gt;</span>
&nbsp;
<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">div</span> <span style="color: #000066;">id</span><span style="color: #66cc66;">=</span><span style="color: #5485C4;">&quot;num_votos&quot;</span>&gt;</span>
	<span style="color: #009900;">&lt;<span style="color: #000000; font-weight: bold;">p</span>&gt;</span>Votos: <span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">p</span>&gt;</span>
<span style="color: #009900;">&lt;<span style="color: #66cc66;">/</span><span style="color: #000000; font-weight: bold;">div</span>&gt;</span> <span style="color: #808080; font-style: italic;">&lt;!-- fin #num_votos --&gt;</span></pre></td></tr></table></div>

<p>Cada línea dentro del div con id 1 representa media estrella, probablemente te parezca raro que no haya ningún tag <img>, pero no te preocupes, verás la razón en el código jQuery. Además, para codificar el CSS debemos pensar en cuantos &#8220;estados&#8221; van a tener nuestras estrellas. La respuesta es 3, uno para cuando esté vacía, otro para cuando esté establecida y otro para el estado <i>hover</i>, cuando un usuario esté poniendo el ratón por encima. Mira este gráfico para aclararte un poco:</p>
<div class="img">
	<img src="http://static.polargeek.net/uploads/sistemas_puntuaciones_estrellas/esquema_tipos_estrellas.jpg" alt="Gráfico de los tres tipos de estrellas" title="Gráfico de los tres tipos de estrellas"/>
</div>
<p>Por tanto, en el CSS tendremos en cuenta esto. Y ya que estamos, recordaremos que tenemos sprites, por lo que el fondo, se va a realizar simplemente con CSS sobre la misma imagen. En concreto debemos tener un sprite para la parte derecha de las distintas estrellas y uno para la parte izquierda. Adicionalmente, añadimos un sprite para las estrellas enteras, pero esto es una mera formalidad y en realidad no se usará. Nuestro CSS quedará así:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
</pre></td><td class="code"><pre class="css" style="font-family:monospace;"><span style="color: #6666ff;">.puntuacion</span> <span style="color: #00AA00;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">cursor</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">pointer</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">margin-right</span><span style="color: #00AA00;">:</span> <span style="color: #933;">5px</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">clear</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">both</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">display</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">block</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">float</span><span style="color: #00AA00;">:</span> <span style="color: #000000; font-weight: bold;">right</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">overflow</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">visible</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span>  
&nbsp;
<span style="color: #6666ff;">.puntuacion</span><span style="color: #3333ff;">:after </span><span style="color: #00AA00;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">content</span><span style="color: #00AA00;">:</span> <span style="color: #ff0000;">'.'</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">display</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">block</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">height</span><span style="color: #00AA00;">:</span> <span style="color: #cc66cc;">0</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">width</span><span style="color: #00AA00;">:</span> <span style="color: #cc66cc;">0</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">clear</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">both</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">visibility</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">hidden</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span>    
&nbsp;
<span style="color: #6666ff;">.estrella</span> <span style="color: #00AA00;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">float</span><span style="color: #00AA00;">:</span> <span style="color: #000000; font-weight: bold;">left</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">width</span><span style="color: #00AA00;">:</span> <span style="color: #933;">35px</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">height</span><span style="color: #00AA00;">:</span> <span style="color: #933;">35px</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">overflow</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">hidden</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">display</span><span style="color: #00AA00;">:</span> inline-<span style="color: #993333;">block</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">text-indent</span><span style="color: #00AA00;">:</span> <span style="color: #933;">-999em</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">cursor</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">pointer</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">margin-top</span><span style="color: #00AA00;">:</span> <span style="color: #933;">1em</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span>         
&nbsp;
<span style="color: #6666ff;">.estrella_izq</span><span style="color: #00AA00;">,</span> <span style="color: #6666ff;">.estrella_der</span> <span style="color: #00AA00;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">width</span><span style="color: #00AA00;">:</span> <span style="color: #933;">18px</span>
<span style="color: #00AA00;">&#125;</span>
&nbsp;
<span style="color: #6666ff;">.estrella</span><span style="color: #00AA00;">,</span> <span style="color: #6666ff;">.estrella</span> a <span style="color: #00AA00;">&#123;</span> 
	<span style="color: #000000; font-weight: bold;">background</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">url</span><span style="color: #00AA00;">&#40;</span><span style="color: #ff0000;">'imagenes/estrella_sprite.png'</span><span style="color: #00AA00;">&#41;</span> <span style="color: #993333;">no-repeat</span> <span style="color: #cc66cc;">0</span> <span style="color: #933;">0px</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span>
&nbsp;
<span style="color: #6666ff;">.estrella_izq</span><span style="color: #00AA00;">,</span> <span style="color: #6666ff;">.estrella_izq</span> a <span style="color: #00AA00;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">background</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">url</span><span style="color: #00AA00;">&#40;</span><span style="color: #ff0000;">'imagenes/estrella_sprite_izq.png'</span><span style="color: #00AA00;">&#41;</span> <span style="color: #993333;">no-repeat</span> <span style="color: #cc66cc;">0</span> <span style="color: #933;">0px</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span>
&nbsp;
<span style="color: #6666ff;">.estrella_der</span><span style="color: #00AA00;">,</span> <span style="color: #6666ff;">.estrella_der</span> a <span style="color: #00AA00;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">background</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">url</span><span style="color: #00AA00;">&#40;</span><span style="color: #ff0000;">'imagenes/estrella_sprite_der.png'</span><span style="color: #00AA00;">&#41;</span> <span style="color: #993333;">no-repeat</span> <span style="color: #cc66cc;">0</span> <span style="color: #933;">0px</span><span style="color: #00AA00;">;</span>
<span style="color: #00AA00;">&#125;</span>
&nbsp;
<span style="color: #6666ff;">.estrella</span> a <span style="color: #00AA00;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">display</span><span style="color: #00AA00;">:</span> <span style="color: #993333;">block</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">width</span><span style="color: #00AA00;">:</span> <span style="color: #933;"><span style="color: #cc66cc;">100</span>%</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">height</span><span style="color: #00AA00;">:</span> <span style="color: #933;"><span style="color: #cc66cc;">100</span>%</span><span style="color: #00AA00;">;</span>
	<span style="color: #000000; font-weight: bold;">background-position</span><span style="color: #00AA00;">:</span> <span style="color: #cc66cc;">0</span> <span style="color: #933;">0px</span><span style="color: #00AA00;">;</span> <span style="color: #808080; font-style: italic;">/* Estrella Vacía */</span>
<span style="color: #00AA00;">&#125;</span>
&nbsp;
div<span style="color: #6666ff;">.puntuacion</span> div<span style="color: #6666ff;">.on</span> a <span style="color: #00AA00;">&#123;</span>
	<span style="color: #000000; font-weight: bold;">background-position</span><span style="color: #00AA00;">:</span> <span style="color: #933;">0px</span> <span style="color: #933;">-45px</span><span style="color: #00AA00;">;</span> <span style="color: #808080; font-style: italic;">/* Estrella Establecida */</span>
<span style="color: #00AA00;">&#125;</span>
&nbsp;
div<span style="color: #6666ff;">.puntuacion</span> div<span style="color: #6666ff;">.hover</span> a<span style="color: #00AA00;">,</span>
div<span style="color: #6666ff;">.puntuacion</span> div a<span style="color: #3333ff;">:hover </span><span style="color: #00AA00;">&#123;</span>      
	<span style="color: #000000; font-weight: bold;">background-position</span><span style="color: #00AA00;">:</span> <span style="color: #933;">0px</span> <span style="color: #933;">-90px</span><span style="color: #00AA00;">;</span>  <span style="color: #808080; font-style: italic;">/* Estrella Hover */</span>
<span style="color: #00AA00;">&#125;</span></pre></td></tr></table></div>

<p>Los detalles de como maquetarlo para que quede lo mejor posible no son demasiado importantes, quizá destacar que nos movemos por el sprite para seleccionar los diferentes tipos de estrellas. Además cuando establezcas un elemento con una imagen como <i>background</i>, debes tener en cuenta que si el elemento no tiene ancho definido, debes hacerlo para que el fondo se vea correctamente.</p>
<h2><span>Paso 2. </span>Plugin en jQuery</h2>
<p>Para realizar toda la funcionalidad que necesitamos podremos simplemente codificarlo en jQuery, pero de cara a una posible mejora en el futuro, meteremos todo el código en un plugin hecho por nosotros. Así que veamos en primer lugar como se crea un plugin muy rápidamente: </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #006600; font-style: italic;">// Declaración del plugin</span>
jQuery.<span style="color: #660066;">fn</span>.<span style="color: #660066;">plugin_tonto</span> <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>param1<span style="color: #339933;">,</span> param2<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #000066;">alert</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'Soy un plugin y estoy funcionando'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">//Llamada al plugin</span>
$<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#elemento'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">plugin_tonto</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'valor1'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'valor2'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Como puedes ver es muy simple, es importante resaltar, como probablemente ya supongas, que en $(this) dentro del plugin tendremos el elemento que lo ha llamado, en este caso $(&#8216;#elemento&#8217;).</p>
<p>Así que ahora empezemos a codificar nuestro plugin de verdad. Debemos tener 1 parámetro, la url donde vamos a mandar los datos para que se procesen (será un script en PHP, que veremos luego). Además este plugin se va a encargar de mucha cosas, por lo que mejor vemos parte por parte desde arriba del código hasta el final.</p>
<h3>Funciones con Cookies y estableciendo variables</h3>
<p>Aquí vemos como establecemos una serie de variables necesarias para que el plugin funcione, como la url a dónde mandaremos la petición POST, o la serie de estrellas que tenemos en nuestro HTML. Además utilizamos dos funciones para manejar las cookies en javascript plano.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">function</span> createCookie<span style="color: #009900;">&#40;</span><span style="color: #000066;">name</span><span style="color: #339933;">,</span>value<span style="color: #339933;">,</span>days<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>days<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003366; font-weight: bold;">var</span> date <span style="color: #339933;">=</span> <span style="color: #003366; font-weight: bold;">new</span> Date<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		date.<span style="color: #660066;">setTime</span><span style="color: #009900;">&#40;</span>date.<span style="color: #660066;">getTime</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">+</span><span style="color: #009900;">&#40;</span>days<span style="color: #339933;">*</span><span style="color: #CC0000;">24</span><span style="color: #339933;">*</span><span style="color: #CC0000;">60</span><span style="color: #339933;">*</span><span style="color: #CC0000;">60</span><span style="color: #339933;">*</span><span style="color: #CC0000;">1000</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #003366; font-weight: bold;">var</span> expires <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;; expires=&quot;</span><span style="color: #339933;">+</span>date.<span style="color: #660066;">toGMTString</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #000066; font-weight: bold;">else</span> <span style="color: #003366; font-weight: bold;">var</span> expires <span style="color: #339933;">=</span> <span style="color: #3366CC;">&quot;&quot;</span><span style="color: #339933;">;</span>
	document.<span style="color: #660066;">cookie</span> <span style="color: #339933;">=</span> <span style="color: #000066;">name</span><span style="color: #339933;">+</span><span style="color: #3366CC;">&quot;=&quot;</span><span style="color: #339933;">+</span>value<span style="color: #339933;">+</span>expires<span style="color: #339933;">+</span><span style="color: #3366CC;">&quot;; path=/&quot;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">function</span> readCookie<span style="color: #009900;">&#40;</span><span style="color: #000066;">name</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #003366; font-weight: bold;">var</span> nameEQ <span style="color: #339933;">=</span> <span style="color: #000066;">name</span> <span style="color: #339933;">+</span> <span style="color: #3366CC;">&quot;=&quot;</span><span style="color: #339933;">;</span>
	<span style="color: #003366; font-weight: bold;">var</span> ca <span style="color: #339933;">=</span> document.<span style="color: #660066;">cookie</span>.<span style="color: #660066;">split</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">';'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #000066; font-weight: bold;">for</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">var</span> i<span style="color: #339933;">=</span><span style="color: #CC0000;">0</span><span style="color: #339933;">;</span>i <span style="color: #339933;">&lt;</span> ca.<span style="color: #660066;">length</span><span style="color: #339933;">;</span>i<span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #003366; font-weight: bold;">var</span> c <span style="color: #339933;">=</span> ca<span style="color: #009900;">&#91;</span>i<span style="color: #009900;">&#93;</span><span style="color: #339933;">;</span>
		<span style="color: #000066; font-weight: bold;">while</span> <span style="color: #009900;">&#40;</span>c.<span style="color: #660066;">charAt</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">==</span><span style="color: #3366CC;">' '</span><span style="color: #009900;">&#41;</span> c <span style="color: #339933;">=</span> c.<span style="color: #660066;">substring</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">1</span><span style="color: #339933;">,</span>c.<span style="color: #660066;">length</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>c.<span style="color: #660066;">indexOf</span><span style="color: #009900;">&#40;</span>nameEQ<span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #CC0000;">0</span><span style="color: #009900;">&#41;</span> <span style="color: #000066; font-weight: bold;">return</span> c.<span style="color: #660066;">substring</span><span style="color: #009900;">&#40;</span>nameEQ.<span style="color: #660066;">length</span><span style="color: #339933;">,</span>c.<span style="color: #660066;">length</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #000066; font-weight: bold;">return</span> <span style="color: #003366; font-weight: bold;">null</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Este par de funciones se sale del objetivo del tutorial, pero básicamente sirven para establecer y guardar cookies, usando javascript. Si quieres más información la tienes por <a href="http://www.quirksmode.org/js/cookies.html">aquí</a>.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #000066; font-weight: bold;">if</span><span style="color: #009900;">&#40;</span>url <span style="color: #339933;">==</span> <span style="color: #003366; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span> <span style="color: #000066; font-weight: bold;">return</span><span style="color: #339933;">;</span>
<span style="color: #003366; font-weight: bold;">var</span> container <span style="color: #339933;">=</span> jQuery<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
jQuery.<span style="color: #660066;">extend</span><span style="color: #009900;">&#40;</span>container<span style="color: #339933;">,</span> <span style="color: #009900;">&#123;</span>
	puntos<span style="color: #339933;">:</span> <span style="color: #CC0000;">0</span><span style="color: #339933;">,</span>
	url<span style="color: #339933;">:</span> url
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #003366; font-weight: bold;">var</span> estrellas <span style="color: #339933;">=</span> jQuery<span style="color: #009900;">&#40;</span>container<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">children</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'.estrella'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p><strong>Línea 6</strong>. Establecemos los atributos puntos y url, como si pertenecieran a container. De tal forma que cuando queramos acceder a ellos simplemente haremos container.url o container.puntos</p>
<p><strong>Línea 9</strong>. Seleccionamos todas las estrellas (en realidad serán media estrellas) y tendremos un total de 10 elementos en la variable <i>estrellas</i>.</p>
<h3>Definiendo eventos sobre las estrellas</h3>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;">estrellas
		.<span style="color: #660066;">mouseover</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
			  eventos.<span style="color: #660066;">quitar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			  eventos.<span style="color: #660066;">llenar</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>
		.<span style="color: #660066;">mouseout</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
			  eventos.<span style="color: #660066;">quitar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			  eventos.<span style="color: #660066;">reiniciar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>
		.<span style="color: #000066;">focus</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
			  eventos.<span style="color: #660066;">quitar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			  eventos.<span style="color: #660066;">llenar</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span>
		.<span style="color: #000066;">blur</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
			  eventos.<span style="color: #660066;">quitar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
			  eventos.<span style="color: #660066;">reiniciar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #006600; font-style: italic;">//Cuando se hace click en una estrella</span>
estrellas.<span style="color: #660066;">click</span><span style="color: #009900;">&#40;</span><span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
   	<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>readCookie<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'votado'</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #003366; font-weight: bold;">null</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		container.<span style="color: #660066;">puntos</span> <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>estrellas.<span style="color: #660066;">index</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">*</span> .5<span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> .5<span style="color: #339933;">;</span>
&nbsp;
      	$.<span style="color: #660066;">post</span><span style="color: #009900;">&#40;</span>container.<span style="color: #660066;">url</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#123;</span>
      		<span style="color: #3366CC;">&quot;id&quot;</span><span style="color: #339933;">:</span> $<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">parent</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">attr</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'id'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
        	<span style="color: #3366CC;">&quot;puntos&quot;</span><span style="color: #339933;">:</span> $<span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">children</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'a'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#91;</span><span style="color: #CC0000;">0</span><span style="color: #009900;">&#93;</span>.<span style="color: #660066;">href</span>.<span style="color: #660066;">split</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#91;</span><span style="color: #CC0000;">1</span><span style="color: #009900;">&#93;</span> 
      	<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      	createCookie<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;votado&quot;</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">1</span><span style="color: #339933;">,</span> <span style="color: #CC0000;">365</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
      	eventos.<span style="color: #660066;">establecer_de_BD</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>		
	<span style="color: #009900;">&#125;</span>   
<span style="color: #009900;">&#125;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>En la primera parte del código establecemos las acciones a realizar cuando pase una de esos eventos predefinidos en jQuery. Todas las llamadas que son <i>eventos.algo</i> pertenecen a un array que definiremos después.</p>
<p> Además definimos el evento click sobre cualquiera de las estrellas. Esto generará que se calcule la puntuación seleccionada y se envía a través del método POST a la url pasada al plugin. Antes de hacer nada para no molestar al servidor si realmente el usuario no puede votar porque ya lo ha hecho, miramos si tiene la cookie que pusimos en una ejecución anterior.</p>
<p>Si realmente es su primera vez votando, se manda la actualización, se establece una cookie para que no vote de nuevo y cuando se ha finalizado el envío se hace una consulta a la BD para actualizar la nueva puntuación. Esto resulta un poco ineficiente pero no quería perder el lado docente del tutorial, y creo que es más claro. En cualquier caso debes tener en mente que se podría devolver la nueva puntuación directamente desde la primera petición POST. </p>
<h3>Algunas funciones útiles e inicio de la puntuación</h3>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
</pre></td><td class="code"><pre class="javascript" style="font-family:monospace;"><span style="color: #003366; font-weight: bold;">var</span> eventos <span style="color: #339933;">=</span> <span style="color: #009900;">&#123;</span>
	<span style="color: #006600; font-style: italic;">// llenar hasta la posición del ratón.</span>
	llenar<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>el<span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> 		
		<span style="color: #003366; font-weight: bold;">var</span> index <span style="color: #339933;">=</span> estrellas.<span style="color: #660066;">index</span><span style="color: #009900;">&#40;</span>el<span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #CC0000;">1</span><span style="color: #339933;">;</span>
		estrellas
			.<span style="color: #660066;">children</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'a'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">css</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'width'</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">'100%'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">end</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
			.<span style="color: #660066;">slice</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">0</span><span style="color: #339933;">,</span>index<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">addClass</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'hover'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">end</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
&nbsp;
	<span style="color: #006600; font-style: italic;">// quitar todas las estrellas.</span>
	quitar<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> 		
		estrellas
			.<span style="color: #660066;">filter</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'.on'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">removeClass</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'on'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">end</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
			.<span style="color: #660066;">filter</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'.hover'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">removeClass</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'hover'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">end</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
&nbsp;
	<span style="color: #006600; font-style: italic;">// reiniciar el sistema.</span>
	reiniciar<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> 	
		<span style="color: #003366; font-weight: bold;">var</span> unidad <span style="color: #339933;">=</span> parseInt<span style="color: #009900;">&#40;</span>container.<span style="color: #660066;">puntos</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #003366; font-weight: bold;">var</span> decimales <span style="color: #339933;">=</span> container.<span style="color: #660066;">puntos</span> <span style="color: #339933;">-</span> unidad<span style="color: #339933;">;</span>
		<span style="color: #003366; font-weight: bold;">var</span> num_estrellas <span style="color: #339933;">=</span> <span style="color: #009900;">&#40;</span>unidad <span style="color: #339933;">*</span> <span style="color: #CC0000;">2</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">+</span> <span style="color: #CC0000;">1</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #000066; font-weight: bold;">if</span> <span style="color: #009900;">&#40;</span>decimales <span style="color: #339933;">&gt;=</span> .5<span style="color: #009900;">&#41;</span>
			num_estrellas <span style="color: #339933;">+=</span> <span style="color: #CC0000;">1</span><span style="color: #339933;">;</span>
&nbsp;
		estrellas.<span style="color: #660066;">slice</span><span style="color: #009900;">&#40;</span><span style="color: #CC0000;">0</span><span style="color: #339933;">,</span> num_estrellas<span style="color: #009900;">&#41;</span>.<span style="color: #660066;">addClass</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'on'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">end</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
&nbsp;
	establecer_de_BD<span style="color: #339933;">:</span> <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #006600; font-style: italic;">//Establecemos la puntuación desde la BD</span>
		$.<span style="color: #660066;">post</span><span style="color: #009900;">&#40;</span>container.<span style="color: #660066;">url</span><span style="color: #339933;">,</span> <span style="color: #009900;">&#123;</span> <span style="color: #3366CC;">&quot;peticion&quot;</span><span style="color: #339933;">:</span> <span style="color: #CC0000;">1</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;id&quot;</span><span style="color: #339933;">:</span> estrellas.<span style="color: #660066;">parent</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">attr</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'id'</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span>
		   <span style="color: #003366; font-weight: bold;">function</span><span style="color: #009900;">&#40;</span>data<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
		     $<span style="color: #009900;">&#40;</span><span style="color: #3366CC;">'#num_votos p'</span><span style="color: #009900;">&#41;</span>.<span style="color: #660066;">html</span><span style="color: #009900;">&#40;</span><span style="color: #3366CC;">&quot;Votos: &quot;</span> <span style="color: #339933;">+</span> data.<span style="color: #660066;">votos</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 		     
		     container.<span style="color: #660066;">puntos</span> <span style="color: #339933;">=</span> data.<span style="color: #660066;">puntuacion</span><span style="color: #339933;">;</span>  
		     eventos.<span style="color: #660066;">reiniciar</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
		   <span style="color: #009900;">&#125;</span><span style="color: #339933;">,</span> <span style="color: #3366CC;">&quot;json&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span><span style="color: #339933;">;</span>    
&nbsp;
<span style="color: #006600; font-style: italic;">//Al principio establecemos el sistema con el valor que corresponde</span>
eventos.<span style="color: #660066;">establecer_de_BD</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000066; font-weight: bold;">return</span><span style="color: #009900;">&#40;</span><span style="color: #000066; font-weight: bold;">this</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p><strong>Línea 3</strong>. Ahora creamos un array del que antes hemos hablado, llamado eventos, es un array asociativo compuesto por funciones. En esta línea definimos la primera función, que se encarga de ir componiendo las estrellas con la clase hover, para dar el efecto de llenado progresivo según se mueve el ratón.</p>
<p><strong>Línea 11</strong>. Esta función se encarga de quitar el efecto hover cuando dejamos de poner el ratón encima de las estrellas.</p>
<p><strong>Línea 18</strong>. Reiniciar es una funcíón para establecer el número de medias estrellas vacías que tenemos, para ello se &#8220;parte&#8221; el número entre la unidad y los decimales, y se opera con ellos. Los detalles los puedo explicar en los comentarios, pero es relativamente sencillo, teniendo en cuenta que tenemos siempre el doble de elementos por ser medias estrellas. Así que he establecido que si se tiene de X a X.5 se marca la mitad de una estrella, y si se tiene de X.5 a X+1 se tiene otra nueva estrella completa.</p>
<p><strong>Línea 29</strong>. Para que el sistema de puntuación funcione necesitamos ver el número de votos y la puntuación de la base de datos y establecerla con la funcion reiniciar. Así que se hace una petición POST y con el resultado en json se establece el resultado.</p>
<p>En la parte final del plugin ejecutamos por primera vez <i>establecer_de_BD</i> para poner el número de estrellas cuando se carga la página así como el número de votos.</p>
<h2><span>Paso 3. </span>Parte servidor con PHP y MySQL</h2>
<p>Hasta ahora tenemos una serie de estrellas que al hacer click en ellas nos mandan los datos actualizados y cuando se cargan nos lo piden. Pero de momento no tenemos un script que se encargue de recibir esas peticiones y actuar en consecuencia.</p>
<p>Es por ello que necesitamos pensar en dos cosas, qué vamos a hacer y cómo vamos a guardar los datos de las puntuaciones. Contestemos primero al problema de almacenar las puntuaciones.</p>
<h3>MySQL es la solución</h3>
<p>Contradiciendo a la navaja de Ockham, en este caso la solución más compleja es la mejor. Y es que podríamos planternos la posibilidad de guardar los votos en un archivo de texto, por ejemplo, pero esto resultaría en problemas de concurrencia, que MySQL resuelve por sí mismo, sin ni siquiera tener que saber como desarrollador que algo llamado concurrencia existe (uno de los temas más complejos en programación, por cierto).</p>
<p>Así que creemos una tabla realmente simple donde meteremos nuestros datos: </p>
<div class="image">
	<img src="http://static.polargeek.net/uploads/sistemas_puntuaciones_estrellas/Tabla_BD_Puntuaciones.png" alt="Tabla BD Puntuaciones" title="Tabla BD Puntuaciones"/>
</div>
<p>Para crearla haríamos lo siguiente con un IDE de bases de datos o desde un terminal:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="mysql" style="font-family:monospace;"><span style="color: #990099; font-weight: bold;">CREATE</span> <span style="color: #990099; font-weight: bold;">TABLE</span> puntuaciones
<span style="color: #FF00FF;">&#40;</span>
id <span style="color: #999900; font-weight: bold;">INT</span><span style="color: #FF00FF;">&#40;</span><span style="color: #008080;">11</span><span style="color: #FF00FF;">&#41;</span> <span style="color: #CC0099; font-weight: bold;">NOT</span> <span style="color: #9900FF; font-weight: bold;">NULL</span> <span style="color: #FF9900; font-weight: bold;">AUTO_INCREMENT</span><span style="color: #000033;">,</span>
puntos <span style="color: #999900; font-weight: bold;">DOUBLE PRECISION</span> <span style="color: #CC0099; font-weight: bold;">NOT</span> <span style="color: #9900FF; font-weight: bold;">NULL</span><span style="color: #000033;">,</span>
votos <span style="color: #999900; font-weight: bold;">INT</span><span style="color: #FF00FF;">&#40;</span><span style="color: #008080;">11</span><span style="color: #FF00FF;">&#41;</span> <span style="color: #990099; font-weight: bold;">DEFAULT</span> <span style="color: #9900FF; font-weight: bold;">NULL</span><span style="color: #000033;">,</span>
<span style="color: #990099; font-weight: bold;">PRIMARY KEY</span> <span style="color: #FF00FF;">&#40;</span>id<span style="color: #FF00FF;">&#41;</span>
<span style="color: #FF00FF;">&#41;</span> CHARACTER <span style="color: #990099; font-weight: bold;">SET</span><span style="color: #CC0099;">=</span>utf8<span style="color: #000033;">;</span></pre></td></tr></table></div>

<h3>Completando el sistema con PHP</h3>
<p>Por último necesitamos un archivo de configuración para simplificar la defición de constantes, una clase para facilitar el acceso a la BD y un script (<i>post.php</i>) para recibir y atender las peticiones.</p>
<p>Nuestro esquema de comunicación se puede resumir en algo así, siendo el plugin de jQuery el encargado de comunicarse con el servidor y de lidiar con las votaciones repetidas.</p>
<div class="img">
	<img src="http://static.polargeek.net/uploads/sistemas_puntuaciones_estrellas/esquema_puntuacion.png" alt="Esquema conexión de nuestro sistema de puntuación" title="Esquema conexión de nuestro sistema de puntuación"/>
</div>
<p>Así que vamos con el primer archivo PHP.Este archivo de configuración será simplemente: </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #009933; font-style: italic;">/** El nombre de tu base de datos */</span>
<span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'DB_NAME'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'nombre_base_de_datos'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009933; font-style: italic;">/** Tu nombre de usuario de MySQL */</span>
<span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'DB_USERNAME'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'usuario'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009933; font-style: italic;">/** Tu contraseña de MySQL */</span>
<span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'DB_PASSWORD'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'pass'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'DB_HOSTNAME'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'hostname'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #009933; font-style: italic;">/** Codificación de caracteres para la base de datos. */</span>
<span style="color: #990000;">define</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'DB_CHARSET'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'utf8'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>La clase, llamada <i>puntos.class.php</i> será bastante sencilla también: </p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
&nbsp;
<span style="color: #b1b100;">require_once</span> <span style="color: #0000ff;">'config.inc.php'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> Puntos <span style="color: #009900;">&#123;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000088;">$db</span><span style="color: #339933;">;</span>
	<span style="color: #000000; font-weight: bold;">private</span> <span style="color: #000088;">$id</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #000000; font-weight: bold;">function</span> __construct<span style="color: #009900;">&#40;</span><span style="color: #000088;">$id</span><span style="color: #009900;">&#41;</span> 
	<span style="color: #009900;">&#123;</span>
		<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">db</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_connect</span><span style="color: #009900;">&#40;</span>DB_HOSTNAME<span style="color: #339933;">,</span> DB_USERNAME<span style="color: #339933;">,</span> DB_PASSWORD<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>	
		<span style="color: #990000;">mysql_set_charset</span><span style="color: #009900;">&#40;</span>DB_CHARSET<span style="color: #339933;">,</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">db</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>		
		<span style="color: #990000;">mysql_select_db</span><span style="color: #009900;">&#40;</span>DB_NAME<span style="color: #339933;">,</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">db</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>  
&nbsp;
		<span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">id</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_real_escape_string</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$id</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>	
&nbsp;
		<span style="color: #000088;">$query</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;INSERT IGNORE INTO puntuaciones (id, votos, puntos) &quot;</span>
		 		<span style="color: #339933;">.</span><span style="color: #0000ff;">&quot;VALUES (<span style="color: #006699; font-weight: bold;">$this-&gt;id</span>,0,0)&quot;</span><span style="color: #339933;">;</span> 
&nbsp;
		<span style="color: #990000;">mysql_query</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$query</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Incluimos el archivo de configuración y en el constructor hacemos tres cosas:</p>
<ol>
<li>Establecemos la conexión con la base de datos.</li>
<li>Establecemos como atributo privado de la clase el id del sistema de puntuación que nos pasan.</li>
<li>Insertamos una nueva fila con votos y puntuación a 0 si no existía ya.</li>
</ol>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">	<span style="color: #000000; font-weight: bold;">function</span> getPuntuacion<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> 
	<span style="color: #009900;">&#123;</span>						
		<span style="color: #000088;">$query</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;SELECT puntos as puntuacion, votos &quot;</span>
				<span style="color: #339933;">.</span><span style="color: #0000ff;">&quot;FROM puntuaciones &quot;</span>
				<span style="color: #339933;">.</span><span style="color: #0000ff;">&quot;WHERE id = <span style="color: #006699; font-weight: bold;">$this-&gt;id</span>&quot;</span><span style="color: #339933;">;</span>
&nbsp;
		<span style="color: #000088;">$resultado</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_query</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$query</span><span style="color: #339933;">,</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">db</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
&nbsp;
		<span style="color: #b1b100;">return</span> <span style="color: #990000;">mysql_fetch_assoc</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$resultado</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Aquí recogemos en un array asociativo la consulta de el número de votos y los puntos que tiene un determinado sistema. Otra vez, lo sabremos por el id que nos pasaron en el constructor y que ya tenemos guardado como atributo.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">	<span style="color: #000000; font-weight: bold;">function</span> setPuntuacion<span style="color: #009900;">&#40;</span><span style="color: #000088;">$puntos</span><span style="color: #009900;">&#41;</span> 
	<span style="color: #009900;">&#123;</span>
		<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #990000;">isset</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_COOKIE</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'votado'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #b1b100;">return</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>     
			<span style="color: #000088;">$puntos</span> <span style="color: #339933;">=</span> <span style="color: #990000;">mysql_real_escape_string</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$puntos</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
			<span style="color: #000088;">$query</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;UPDATE puntuaciones &quot;</span><span style="color: #339933;">.</span>
					 <span style="color: #0000ff;">&quot;SET puntos = ((puntos * votos) + <span style="color: #006699; font-weight: bold;">$puntos</span>) / (votos + 1), &quot;</span><span style="color: #339933;">.</span>
					 <span style="color: #0000ff;">&quot;votos = votos + 1 &quot;</span><span style="color: #339933;">.</span> 
					 <span style="color: #0000ff;">&quot;WHERE id = <span style="color: #006699; font-weight: bold;">$this-&gt;id</span>&quot;</span><span style="color: #339933;">;</span>
&nbsp;
			 <span style="color: #b1b100;">return</span> <span style="color: #990000;">mysql_query</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$query</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span> <span style="color: #666666; font-style: italic;">//Fin de la clase</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>Este último método mira si se tiene una cookie previamente establecida y si no es así actualiza la base de datos con los puntos pasados como parámetro, aumentando también el número de votos a uno más de los que había. La comprobación de la cookie no es estrictamente necesaria, porque previamente el plugin se ha encargado de ver eso, pero no está de más y no supone casi carga al servidor.</p>
<p>El sistema de establecer una cookie cuando un usuario vote para que no lo haga más no es una solución perfecta, porque se puede saltar fácilmente, pero es una primera aproximación y quizá en un futuro enseñe como mejorar esto. En cualquier caso se puede ver un uso práctico de las cookies con PHP y una aplicación real.</p>
<h4>Script que recibe las peticiones</h4>
<p>Por último tenemos nuestro archivo <i>post.php</i> en el que recibimos las peticiones:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #666666; font-style: italic;">//Incluimos la clase puntos</span>
<span style="color: #b1b100;">require_once</span> <span style="color: #0000ff;">'puntos.class.php'</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #990000;">empty</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_POST</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #339933;">!</span><span style="color: #990000;">empty</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'id'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
       <span style="color: #000088;">$pt</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Puntos<span style="color: #009900;">&#40;</span><span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'id'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #990000;">empty</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'peticion'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">&amp;&amp;</span> <span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'peticion'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
		<span style="color: #b1b100;">echo</span> <span style="color: #990000;">json_encode</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$pt</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getPuntuacion</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">elseif</span> <span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #990000;">empty</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'puntos'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
		<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$pt</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setPuntuacion</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$_POST</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'puntos'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	<span style="color: #009900;">&#125;</span>  
<span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p><strong>Línea 8. </strong>Nos han hecho una petición para saber el número de votos y la puntuación. Así que llamamos al método definido antes que se encarga de manejar esa petición.</p>
<p><strong>Línea 11. </strong>Establecemos la nueva puntuación y aumentamos el número de votos en 1. Nuestro método ya se encarga de comprobar la cookie y de limpiar la entrada de datos, usando <i>mysql_real_escape_string</i>, como hemos comentado antes.</p>
<div class="descarga">
<a href="http://static.polargeek.net/uploads/sistemas_puntuaciones_estrellas/puntuacion.zip" class="descargar"></a><a href="http://www.polargeek.net/wp-content/uploads/demos/puntuacion/index.html" class="demo"></a>
</div>
<h2>Conclusiones</h2>
<p>Si bien es cierto que hay cosas que pulir, como por ejemplo en términos de accesibilidad si no se tiene javascript activado, o de seguridad, para evitar que un usuario pueda saltarse el control que hemos hecho con la cookie, este tutorial cubre muchos puntos, que espero, te hayan sido útiles.</p>
<p>El plugin está basado en uno mucho más complejo y grande que ya va por su versión 3.13. Lo puedes encontrar <a href="http://www.fyneworks.com/jquery/star-rating/">aquí</a>.</p>
<p>Las estrellas usadas (aunque estaban enteras) son de <a href="http://www.customicondesign.com"> Customicon Design</a>.</p>
<p>Si tienes cualquier duda, no dudes en preguntar en la sección de comentarios.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.polargeek.net/hacer-un-sistema-de-puntuacion-con-php-y-jquery/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Quitar espacios extra de string con PHP</title>
		<link>http://www.polargeek.net/quitar-espacios-extra-de-string-con-php/</link>
		<comments>http://www.polargeek.net/quitar-espacios-extra-de-string-con-php/#comments</comments>
		<pubDate>Sat, 20 Feb 2010 18:31:01 +0000</pubDate>
		<dc:creator>José</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[trim]]></category>

		<guid isPermaLink="false">http://www.polargeek.net/?p=1254</guid>
		<description><![CDATA[Introducción Como probablemente sabrás existe en PHP una función en PHP llamada trim. Cuyo funcionamiento básico es quitar los espacios sobrantes a la izquierda y a la derecha de un string dado. Por ejemplo 1 2 3 4 5 &#60;?php //String con espacios sobrantes $string = &#34; En un lugar de la Mancha &#34;; echo [...]]]></description>
			<content:encoded><![CDATA[<h2>Introducción</h2>
<p>Como probablemente sabrás existe en PHP una función en PHP llamada trim. Cuyo funcionamiento básico es quitar los espacios sobrantes <strong>a la izquierda y a la derecha</strong> de un string dado. Por ejemplo</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
   <span style="color: #666666; font-style: italic;">//String con espacios sobrantes</span>
   <span style="color: #000088;">$string</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;  En un lugar de la Mancha  &quot;</span><span style="color: #339933;">;</span>
   <span style="color: #b1b100;">echo</span> <span style="color: #990000;">trim</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$string</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>La salida sería el string sin los espacios del principio y el final: </p>
<div class="bubble_wrapper">
<div class="bubble_wrapper">
<div class="pmeta_bubble_bg pmeta_bubble_bg_ok">
<div class="box-inner">
En un lugar de la Mancha
</div>
</div>
</div>
</div>
<p>El problema surge cuando tenemos un string con espacios sobrantes <strong>en mitad del string</strong>. Algo como esto:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
   <span style="color: #666666; font-style: italic;">//String con espacios sobrantes en la mitad</span>
   <span style="color: #000088;">$string_complicado</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;  En un          lugar de la Mancha  &quot;</span><span style="color: #339933;">;</span>
   <span style="color: #b1b100;">echo</span> <span style="color: #990000;">trim</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$string_complicado</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>En este caso trim no funciona, dado que no hace nada con los que están en medio. Por tanto necesitamos una alternativa para hacer esto, una alternativa en forma de función claro.</p>
<h2>Función para quitar los espacios repetidos</h2>
<p>Aquí se plantean varias alternativas, una posible solución podría ser con expresiones regulares, pero quizá sea menos clara. Así que utilicemos la función que sale en <a href="http://es2.php.net/manual/en/function.trim.php#87164">un comentario</a> de la <a href="http://es2.php.net/manual/en/function.trim.php">página de documentación de trim</a>, y añadámosle la línea &#8220;$ret_str = &#8220;&#8221;;&#8221; para evitar un error de PHP, la función completa quedaría así:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #000000; font-weight: bold;">function</span> quitar_espacios_extra<span style="color: #009900;">&#40;</span><span style="color: #000088;">$str</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
	<span style="color: #666666; font-style: italic;">//Utilizamos trim antes de empezar</span>
	<span style="color: #000088;">$str</span> <span style="color: #339933;">=</span> <span style="color: #990000;">trim</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$str</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>	   
&nbsp;
	<span style="color: #666666; font-style: italic;">//Inicializamos el string que devolvemos</span>
	<span style="color: #000088;">$ret_str</span> <span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;&quot;</span><span style="color: #339933;">;</span>
&nbsp;
	<span style="color: #666666; font-style: italic;">//Recorremos el string</span>
	<span style="color: #b1b100;">for</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$i</span><span style="color: #339933;">=</span><span style="color: #cc66cc;">0</span><span style="color: #339933;">;</span><span style="color: #000088;">$i</span> <span style="color: #339933;">&lt;</span> <span style="color: #990000;">strlen</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$str</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span><span style="color: #000088;">$i</span><span style="color: #339933;">++</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
		<span style="color: #666666; font-style: italic;">/*Si estamos en algo que no es un espacio, seguimos copiando el 
		string de entrada al de salida */</span>
		<span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">substr</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$str</span><span style="color: #339933;">,</span> <span style="color: #000088;">$i</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">!=</span> <span style="color: #0000ff;">&quot; &quot;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #000088;">$ret_str</span> <span style="color: #339933;">.=</span> <span style="color: #990000;">trim</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">substr</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$str</span><span style="color: #339933;">,</span> <span style="color: #000088;">$i</span><span style="color: #339933;">,</span> <span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
		<span style="color: #009900;">&#125;</span> <span style="color: #b1b100;">else</span> <span style="color: #009900;">&#123;</span>
			<span style="color: #666666; font-style: italic;">/*Si es un espacio nos lo saltamos, aumentando el contador i del bucle*/</span>
			<span style="color: #b1b100;">while</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">substr</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$str</span><span style="color: #339933;">,</span><span style="color: #000088;">$i</span><span style="color: #339933;">,</span><span style="color: #cc66cc;">1</span><span style="color: #009900;">&#41;</span> <span style="color: #339933;">==</span> <span style="color: #0000ff;">&quot; &quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
				<span style="color: #000088;">$i</span><span style="color: #339933;">++;</span>
			<span style="color: #009900;">&#125;</span>		
&nbsp;
			<span style="color: #666666; font-style: italic;">/* Dado que no queremos quitar todos los espacios, sino solo los repetidos
			añadimos un espacio después de habernos
			saltado un nº indeterminado de ellos SI nos saltamos uno, ponemos uno
			SI nos saltamos 20, ponemos uno igual */</span>
			<span style="color: #000088;">$ret_str</span><span style="color: #339933;">.=</span> <span style="color: #0000ff;">&quot; &quot;</span><span style="color: #339933;">;</span>
			<span style="color: #000088;">$i</span><span style="color: #339933;">--;</span>
		<span style="color: #009900;">&#125;</span>
	<span style="color: #009900;">&#125;</span>
	<span style="color: #b1b100;">return</span> <span style="color: #000088;">$ret_str</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span>		   
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>Con esta función, usándolo con el string anterior:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
 <span style="color: #666666; font-style: italic;">//String con espacios sobrantes en la mitad</span>
<span style="color: #000088;">$string_complicado</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">&quot;  En un          lugar de la Mancha  &quot;</span><span style="color: #339933;">;</span>      
&nbsp;
<span style="color: #b1b100;">echo</span> quitar_espacios_extra<span style="color: #009900;">&#40;</span><span style="color: #000088;">$string_complicado</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>La salida sería:</p>
<div class="bubble_wrapper">
<div class="pmeta_bubble_bg pmeta_bubble_bg_ok">
<div class="box-inner">
En un lugar de la Mancha
</div>
</div>
</div>
<p>Cualquier duda o error como siempre a la sección de comentarios.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.polargeek.net/quitar-espacios-extra-de-string-con-php/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>Javascript cross-domain resuelto con PHP</title>
		<link>http://www.polargeek.net/javascript-cross-domain-resuelto-con-php/</link>
		<comments>http://www.polargeek.net/javascript-cross-domain-resuelto-con-php/#comments</comments>
		<pubDate>Tue, 16 Feb 2010 18:23:35 +0000</pubDate>
		<dc:creator>José</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[cross-domain]]></category>
		<category><![CDATA[javascript]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.polargeek.net/?p=1240</guid>
		<description><![CDATA[Problema cross-domain en Javascript De una forma sencilla, digamos que en principio no es posible acceder desde el javascript de una página en el dominio A a otra en el dominio B. Es decir, si desde javascript queremos hacer una petición desde www.ejemplo.com/index.html a www.midominio.com/index.html, por motivos de seguridad no podemos. Hay una forma de [...]]]></description>
			<content:encoded><![CDATA[<h2>Problema cross-domain en Javascript</h2>
<p>De una forma sencilla, digamos que en principio no es posible acceder desde el javascript de una página en el dominio A a otra en el dominio B. </p>
<p>Es decir, si desde javascript queremos hacer una petición desde www.ejemplo.com/index.html a www.midominio.com/index.html, por motivos de seguridad no podemos.</p>
<p>Hay una forma de acceder a esos datos, y es que si lo hacemos a través del formato JSONP, no hay mayor problema, pero como sabrás, no todas las páginas a las que queremos acceder por lo que sea, tienen el formato JSONP disponible.</p>
<p>¿Cómo se resuelve esto? Pues aquí es cuando entra Simple PHP Proxy.</p>
<h2>Simple PHP Proxy</h2>
<p>Para acceder a una página que no está en nuestro dominio y no tiene el formato JSONP, utilizamos esta clase. </p>
<p>La idea es que el servidor donde se va a ejecutar nuestro código haga una copia local de la página a la que vamos a acceder a través de Javascript, y así no estamos haciendo cross-domain, estamos en nuestro servidor! </p>
<p><img src="http://static.polargeek.net/uploads/cross-domain.jpg" border="0" /><br />
Te podrías plantear la duda de: ¿y por qué no lo hago a mano? Bueno el problema es que las páginas cambian y hacerlo de manera manual, cada vez que quieras acceder a otro dominio te va a ser casi imposible.</p>
<h2>Cómo utilizar Simple PHP Proxy</h2>
<p>En la <a href="http://benalman.com/code/projects/php-simple-proxy/examples/simple/">página de ejemplo</a> podemos ver como funciona y el código en sí, en el que se utiliza para mostrar las cabeceras de un dominio que se le pase a través de Javascript, lo que demuestra que ha podido acceder a ese dominio superando así el problema del cross-domain.</p>
<h2>Enlaces</h2>
<p>Página del proyecto | <a href="http://benalman.com/projects/php-simple-proxy/">benalman.com</a><br />
Código y seguimiento | <a href="http://github.com/cowboy/php-simple-proxy">Github</a><br />
Documentación más exhaustiva | <a href="http://benalman.com/code/projects/php-simple-proxy/docs/files/ba-simple-proxy-php.html">benalman.com</a><br />
Código fuente de Simple PHP Proxy | <a href="http://github.com/cowboy/php-simple-proxy/raw/master/ba-simple-proxy.php">Descarga</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.polargeek.net/javascript-cross-domain-resuelto-con-php/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Comprimir CSS usando PHP</title>
		<link>http://www.polargeek.net/comprimir-css-usando-php/</link>
		<comments>http://www.polargeek.net/comprimir-css-usando-php/#comments</comments>
		<pubDate>Thu, 11 Feb 2010 00:39:52 +0000</pubDate>
		<dc:creator>José</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[compresion]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.polargeek.net/?p=1233</guid>
		<description><![CDATA[La idea La idea es poder hacer de un archivo amplio, con saltos de línea y espacios innecesarios para el funcionamiento del archivo, un archivo sin espacios, ni saltos de línea&#8230;etc de tal forma que reduzcamos su tamaño y nuestra página cargue más rápido. Cómo hacerlo Para poder hacer esto necesitamos un lenguaje, en este [...]]]></description>
			<content:encoded><![CDATA[<h2>La idea</h2>
<p>La idea es poder hacer de un archivo amplio, con saltos de línea y espacios innecesarios para el funcionamiento del archivo, un archivo sin espacios, ni saltos de línea&#8230;etc de tal forma que reduzcamos su tamaño y nuestra página cargue más rápido.</p>
<h2>Cómo hacerlo</h2>
<p>Para poder hacer esto necesitamos un lenguaje, en este caso PHP en un simple script al que le indiquemos que archivos queremos cambiar. Echemos un vistazo al código necesario:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
  <span style="color: #990000;">header</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Content-type: text/css'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #990000;">ob_start</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;compress&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">function</span> compress<span style="color: #009900;">&#40;</span><span style="color: #000088;">$buffer</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
    <span style="color: #666666; font-style: italic;">/* quitamos comentarios */</span>
    <span style="color: #000088;">$buffer</span> <span style="color: #339933;">=</span> <span style="color: #990000;">preg_replace</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'!/\*[^*]*\*+([^/][^*]*\*+)*/!'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">''</span><span style="color: #339933;">,</span> <span style="color: #000088;">$buffer</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #666666; font-style: italic;">/* quitamos espacios en blanco, salto de lineas..... */</span>
    <span style="color: #000088;">$buffer</span> <span style="color: #339933;">=</span> <span style="color: #990000;">str_replace</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\r</span><span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\r</span>&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\n</span>&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;<span style="color: #000099; font-weight: bold;">\t</span>&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'  '</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'    '</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'    '</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">''</span><span style="color: #339933;">,</span> <span style="color: #000088;">$buffer</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">return</span> <span style="color: #000088;">$buffer</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #666666; font-style: italic;">/* incluimos los archivos css que queremos comprimir */</span>
  <span style="color: #b1b100;">include</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'master.css'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #b1b100;">include</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'print.css'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #990000;">ob_end_flush</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>Este método es de Reinhold Weber y personalmente, me parece uno de los más fáciles de entender. (<a href="http://reinholdweber.com/css/css-deployment-php-snippet-compresses-multiple-css-files-into-one-single-line/">fuente</a>) Además hay que tener en cuenta que si incluimos más de uno los combinará en uno solo.</p>
<p>Los archivos que se les pasen, no tienen por qué estar en el mismo directorio, se le puede pasar una ruta, por supuesto. </p>
<p>Si tienes cualquier problema con el script a la sección de comentarios.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.polargeek.net/comprimir-css-usando-php/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
		<item>
		<title>[PHP] Sistema de plantillas con Smarty</title>
		<link>http://www.polargeek.net/php-sistema-de-plantillas-con-smarty/</link>
		<comments>http://www.polargeek.net/php-sistema-de-plantillas-con-smarty/#comments</comments>
		<pubDate>Mon, 04 Jan 2010 00:48:36 +0000</pubDate>
		<dc:creator>José</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[smarty]]></category>

		<guid isPermaLink="false">http://www.polargeek.net/?p=1075</guid>
		<description><![CDATA[Introducción Un sistema de plantillas (template engine) es un framework que te permite separar la vista del modelo y el controlador (MVC) de manera casi obligatoria. Por motivos de trabajo durante algunos meses me tocó pelearme con un sistema de plantillas llamado Smarty. Vamos a ver qué nos ofrece y como utilizarlo. Parte PHP El [...]]]></description>
			<content:encoded><![CDATA[<h2>Introducción</h2>
<p>Un sistema de plantillas (template engine) es un framework que te permite separar la vista del modelo y el controlador (MVC) de manera casi obligatoria.</p>
<p>Por motivos de trabajo durante algunos meses me tocó pelearme con un sistema de plantillas llamado Smarty. Vamos a ver qué nos ofrece y como utilizarlo. </p>
<p><a href="http://upload4.net/files/get/svBfGyxQ26/smarty.zip"><img src="http://static.polargeek.net/uploads/2010/01/smarty-book.jpeg" alt="" title="smarty-book" width="232" height="300" class="aligncenter size-full wp-image-1089" /></a></p>
<h2>Parte PHP</h2>
<p>El paso de variables desde PHP es realmente sencillo:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">//Llamamos a la clase de Smarty</span>
<span style="color: #b1b100;">require_once</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Smarty/libs/Smarty.class.php&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>  
&nbsp;
<span style="color: #666666; font-style: italic;">//Creamos nuestra plantilla</span>
<span style="color: #000088;">$miSmarty</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Smarty<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>         
&nbsp;
<span style="color: #666666; font-style: italic;">//Configuramos los directorios</span>
<span style="color: #000088;">$miSmarty</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">template_dir</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'templates'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$miSmarty</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">config_dir</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'config'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$miSmarty</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">cache_dir</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'cache'</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$miSmarty</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">compile_dir</span> <span style="color: #339933;">=</span> <span style="color: #0000ff;">'templates_c'</span><span style="color: #339933;">;</span> 
&nbsp;
<span style="color: #666666; font-style: italic;">//Asignamos variables</span>
<span style="color: #000088;">$miSmarty</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">assign</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;titulo&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;Formulario de Consultas&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$miSmarty</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">assign</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;fecha_hoy&quot;</span><span style="color: #339933;">,</span><span style="color: #990000;">date</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;m.d.y&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>           
&nbsp;
<span style="color: #666666; font-style: italic;">//Nos guardamos el html y lo mostramos</span>
<span style="color: #000088;">$html_final</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$miSmarty</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">fetch</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;miplantilla.tpl&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">echo</span> <span style="color: #000088;">$html_final</span><span style="color: #339933;">;</span>                            
&nbsp;
<span style="color: #666666; font-style: italic;">//O mostramos la plantilla</span>
<span style="color: #000088;">$miSmarty</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">display</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;miplantilla.tpl.html&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<h2>Parte Smarty</h2>
<p>Teniendo el codigo anterior veamos que pinta tendría nuestra plantilla (<em>miplantilla.tpl.html</em>)</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="smarty" style="font-family:monospace;"><span style="color: #009000;">&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;</span>
<span style="color: #009000;">&lt;head&gt;</span>
<span style="color: #008080; font-style: italic;">{*Comentario en Smarty*}</span>
<span style="color: #009000;">&lt;title&gt;</span><span style="color: #D36900;">&#123;</span><span style="color: #00aaff;">$titulo</span><span style="color: #D36900;">&#125;</span><span style="color: #009000;">&lt;/title&gt;</span>
<span style="color: #009000;">&lt;/head&gt;</span>
<span style="color: #009000;">&lt;body&gt;</span>         
&nbsp;
<span style="color: #008080; font-style: italic;">{*Notese que usamos siempre el mismo 
nombre que le pusimos en el script de PHP*}</span>
Hoy estamos a <span style="color: #D36900;">&#123;</span><span style="color: #00aaff;">$fecha_hoy</span><span style="color: #D36900;">&#125;</span>
<span style="color: #009000;">&lt;/body&gt;</span>
<span style="color: #009000;">&lt;/html&gt;</span></pre></td></tr></table></div>

<h2>Precauciones sobre el uso</h2>
<p>Cuando utilicemos Javascript tenemos que empezar antes del código con {literal} y después terminamos con {/literal}. </p>
<p>Esto, como podrás suponer, es para que no haya lío entre la sintaxis de javascript y el sistema de plantillas. Si en mitad del código de js queremos introducir código smarty simplemente hacemos:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
</pre></td><td class="code"><pre class="smarty" style="font-family:monospace;"><span style="color: #009000;">&lt;html xmlns=&quot;http://www.w3.org/1999/xhtml&quot;&gt;</span>
 <span style="color: #009000;">&lt;head&gt;</span>
   <span style="color: #D36900;">&#123;</span>literal<span style="color: #D36900;">&#125;</span>
   <span style="color: #009000;">&lt;script&gt;</span>
   //código javascript
   var fecha = <span style="color: #D36900;">&#123;</span><span style="color: #D36900;">/</span>literal<span style="color: #D36900;">&#125;</span><span style="color: #D36900;">&#123;</span><span style="color: #00aaff;">$fecha_hoy</span><span style="color: #D36900;">&#125;</span><span style="color: #D36900;">&#123;</span>literal<span style="color: #D36900;">&#125;</span>;
   //Más código 
   <span style="color: #009000;">&lt;/script&gt;</span>
   <span style="color: #D36900;">&#123;</span><span style="color: #D36900;">/</span>literal<span style="color: #D36900;">&#125;</span>
 <span style="color: #009000;">&lt;/head&gt;</span>
&nbsp;
 <span style="color: #009000;">&lt;body&gt;</span>
  ...
 <span style="color: #009000;">&lt;/body&gt;</span>
<span style="color: #009000;">&lt;/html&gt;</span></pre></td></tr></table></div>

<h2>Enlaces</h2>
<ul class="padding">
<li><a href="http://www.smarty.net/download.php">Descarga</a></li>
<li><a href="http://www.smarty.net/manual/es/installing.smarty.basic.php">Instalación</a></li>
<li><a href="http://www.smarty.net/distributions/manual/es/Smarty-2.6.14-docs.pdf">Documentación</a></li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://www.polargeek.net/php-sistema-de-plantillas-con-smarty/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>[PHP] Google Sets</title>
		<link>http://www.polargeek.net/php-google-sets/</link>
		<comments>http://www.polargeek.net/php-google-sets/#comments</comments>
		<pubDate>Sun, 06 Dec 2009 00:52:49 +0000</pubDate>
		<dc:creator>José</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[clases]]></category>
		<category><![CDATA[google]]></category>
		<category><![CDATA[php]]></category>

		<guid isPermaLink="false">http://www.polargeek.net/?p=803</guid>
		<description><![CDATA[Introducci&#243;n Google Sets es un servicio de Google, que permite obtener palabras del mismo conjunto que las que introducimos. Es decir, si damos &#8216;rojo&#8217;,'verde&#8217;, obtenemos Predicted Items verde rojo azul amarillo blanco negro naranja rosa gris &#8230; Su uso es muy amplio, desde simple admiración por lo que Google ha llegado a acumular en cuanto [...]]]></description>
			<content:encoded><![CDATA[<h1>Introducci&oacute;n</h1>
<p>Google Sets es un servicio de Google, que permite obtener palabras del mismo conjunto que las que introducimos. Es decir, si damos &#8216;rojo&#8217;,'verde&#8217;, obtenemos</p>
<table style="height: 338px;margin:auto;" border="0" cellspacing="2" cellpadding="8%" width="324" align="center" summary="List of items which may be members of your set, one item per row">
<tbody>
<tr>
<td style="background-color: #e6f2ea;" width="300" valign="top"><center><strong><span style="font-family: Arial,sans-serif; color: #000000;">Predicted Items</span></strong></center></td>
</tr>
<tr>
<td style="background-color: #f9f4df; text-align: center;" valign="top"><span style="font-family: Arial,sans-serif;"><a href="http://www.google.com/search?hl=en&amp;q=verde">verde</a></span></td>
</tr>
<tr style="text-align: center;">
<td style="background-color: #fff9e4;" valign="top"><span style="font-family: Arial,sans-serif;"><a href="http://www.google.com/search?hl=en&amp;q=rojo">rojo</a></span></td>
</tr>
<tr>
<td style="background-color: #f9f4df; text-align: center;" valign="top"><span style="font-family: Arial,sans-serif;"><a href="http://www.google.com/search?hl=en&amp;q=azul">azul</a></span></td>
</tr>
<tr>
<td style="background-color: #fff9e4; text-align: center;" valign="top"><span style="font-family: Arial,sans-serif;"><a href="http://www.google.com/search?hl=en&amp;q=amarillo">amarillo</a></span></td>
</tr>
<tr>
<td style="background-color: #f9f4df; text-align: center;" valign="top"><span style="font-family: Arial,sans-serif;"><a href="http://www.google.com/search?hl=en&amp;q=blanco">blanco</a></span></td>
</tr>
<tr>
<td style="background-color: #fff9e4; text-align: center;" valign="top"><span style="font-family: Arial,sans-serif;"><a href="http://www.google.com/search?hl=en&amp;q=negro">negro</a></span></td>
</tr>
<tr>
<td style="background-color: #f9f4df; text-align: center;" valign="top"><span style="font-family: Arial,sans-serif;"><a href="http://www.google.com/search?hl=en&amp;q=naranja">naranja</a></span></td>
</tr>
<tr>
<td style="background-color: #fff9e4; text-align: center;" valign="top"><span style="font-family: Arial,sans-serif;"><a href="http://www.google.com/search?hl=en&amp;q=rosa">rosa</a></span></td>
</tr>
<tr>
<td style="background-color: #f9f4df; text-align: center;" valign="top"><span style="font-family: Arial,sans-serif;"><a href="http://www.google.com/search?hl=en&amp;q=gris">gris</a></span></td>
</tr>
<tr>
<td style="background-color: #fff9e4; text-align: center;" valign="top">&#8230;</td>
</tr>
</tbody>
</table>
<p>Su uso es muy amplio, desde simple admiración por lo que Google ha llegado a acumular en cuanto a información se refiere, hasta black SEO, utilizando como palabras relacionadas lo que nos devuelva.</p>
<p>El problema es que solo hay una interfaz web, no existe una API ni nada parecido, por lo que he decidido crear una clase en PHP, que permita obtener de manera medianamente sencilla, un array con todas las palabras. En un alarde de originalidad la he llamado Gooset.</p>
<p>Para ello he hecho uso de <a href="http://simplehtmldom.sourceforge.net/">PHP Simple HTML DOM Parser</a>, que es una clase para parsear html (recomendada 100%).</p>
<p>Despu&eacute;s he hecho la clase y en el constructor ya obtengo todo el conjunto, de tal forma que solo hace falta llamar al m&eacute;todo <em>get_set</em> para que nos lo devuelva en un array.</p>
<p>La clase en si es muy simple, de todas formas si tienes alguna duda no dudes en usar los comentarios</p>
<h1>Uso</h1>
<p></br ></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #b1b100;">include</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'./gooset.php'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$obj_gooset</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> gooset<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'bmw'</span><span style="color: #339933;">,</span><span style="color: #0000ff;">'ferrari'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$obj_gooset</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">get_set</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$elemento</span><span style="color: #009900;">&#41;</span>
	<span style="color: #b1b100;">print</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$elemento</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;/br &gt;'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> 
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>Salida:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">bmw 
ferrari 
ford
honda
audi
hyundai
jaguar
chrysler
chevrolet
jeep
kia
...</pre></td></tr></table></div>

<p>El m&aacute;ximo de par&aacute;metros son 5. Con un n&uacute;mero mayor el resultado no cambia, as&iacute; que en ese caso se devuelve un error a trav&eacute;s de una expepci&oacute;n, lo que es un punto a favor, puesto que despu&eacute;s de eso no tenemos que comprobar nada (en PHP el script se para cuando se eleva una excepci&oacute;n).</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #b1b100;">include</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'./gooset.php'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$obj_gooset</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> gooset<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'bmw'</span><span style="color: #339933;">,</span><span style="color: #0000ff;">'ferrari'</span><span style="color: #339933;">,</span><span style="color: #0000ff;">'mercedes'</span><span style="color: #339933;">,</span><span style="color: #0000ff;">'audi'</span><span style="color: #339933;">,</span><span style="color: #0000ff;">'hummer'</span><span style="color: #339933;">,</span><span style="color: #0000ff;">'jaguar'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$obj_gooset</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">get_set</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$elemento</span><span style="color: #009900;">&#41;</span>
	<span style="color: #b1b100;">print</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$elemento</span> <span style="color: #339933;">.</span> <span style="color: #0000ff;">'&lt;/br &gt;'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000000; font-weight: bold;">?&gt;</span></pre></td></tr></table></div>

<p>Salida:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="text" style="font-family:monospace;">Error de uso: 5 elementos máximo</pre></td></tr></table></div>

<h1>Descarga desde GitHub</h1>
<div class="desc_clase"><a href="http://github.com/polargeek/PHP-Google-Sets/blob/master/gooset.php"><img src="http://static.polargeek.net/uploads/coding_128_clase.png" alt="" style="width: 128px; padding-top: 12px;"/></a></div>
]]></content:encoded>
			<wfw:commentRss>http://www.polargeek.net/php-google-sets/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
	</channel>
</rss>
