<?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>AxiaCore &#187; Symfony</title>
	<atom:link href="http://axiacore.com/tag/symfony/feed/" rel="self" type="application/rss+xml" />
	<link>http://axiacore.com</link>
	<description>Tenemos poderes magicos...</description>
	<lastBuildDate>Wed, 25 Jan 2012 14:19:55 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>Capturar evento logout y login en Symfony</title>
		<link>http://axiacore.com/2010/09/capturar-evento-logout-y-login-en-symfony/</link>
		<comments>http://axiacore.com/2010/09/capturar-evento-logout-y-login-en-symfony/#comments</comments>
		<pubDate>Tue, 07 Sep 2010 23:46:56 +0000</pubDate>
		<dc:creator>Juan Pablo Romero Bernal</dc:creator>
				<category><![CDATA[Desarrollo]]></category>
		<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Tips]]></category>

		<guid isPermaLink="false">http://axiacore.com/?p=1358</guid>
		<description><![CDATA[Este es un post muy corto, en donde comentaré de forma muy rápida como capturar los eventos logout y login en Symfony (puedes leer una introducción al manejo de eventos con Symfony), particularmente cuando se usa el plugin sfGuardUser (bien sea con Propel o Doctrine). Lo primero que se debe tener en cuenta, es sobreescribir [...]]]></description>
			<content:encoded><![CDATA[<p>Este es un post muy corto, en donde comentaré de forma muy rápida como capturar los eventos logout y login en Symfony (puedes leer una <a href="http://axiacore.com/2010/07/introduccion-al-manejo-de-eventos-con-symfony/">introducción al manejo de eventos con Symfony</a>), particularmente cuando se usa el plugin sfGuardUser (bien sea con Propel o Doctrine).  Lo primero que se debe tener en cuenta, es sobreescribir el método <strong>signOut</strong> o <strong>signIn</strong> (dependiendo de que evento queramos capturar) de la clase sfGuardSecurityUser, modificando la clase myUser de nuestra aplicación. Como ejemplo, sobreescribiré el método <strong>signOut</strong>:</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="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #666666; font-style: italic;">//Archivo ubicado en: SYMFONY_ROOT/apps/mi_aplicacion/lib/myUser.class.php</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> myUser <span style="color: #000000; font-weight: bold;">extends</span> sfGuardSecurityUser
<span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> signOut<span style="color: #009900;">&#40;</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;">dispatcher</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">notify</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> sfEvent<span style="color: #009900;">&#40;</span>
                <span style="color: #000088;">$this</span><span style="color: #339933;">,</span>
                <span style="color: #0000ff;">'user.logout'</span><span style="color: #339933;">,</span>
                <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'user_id'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getGuardUser</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">id</span><span style="color: #009900;">&#41;</span>
        <span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        parent<span style="color: #339933;">::</span><span style="color: #004000;">signOut</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></pre></td></tr></table></div>

<p>Con esto estamos notificando al objeto sfEventDispatcher la ocurrencia del evento user.logout desde la clase myUser (primer parámetro del constructor de sfEvent) y estamos pasando como información el identificador del usuario. Posteriormente, debemos asociar un listener a ese evento, el cual lo podemos definir en la clase que configura nuestra aplicación:</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="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #666666; font-style: italic;">// Archivo ubicado en: SYMFONY_ROOT/apps/mi_aplicacion/config/mi_aplicacionConfiguration.class.php</span>
<span style="color: #000000; font-weight: bold;">class</span> mi_aplicacionConfiguration <span style="color: #000000; font-weight: bold;">extends</span> sfApplicationConfiguration
<span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> configure<span style="color: #009900;">&#40;</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;">dispatcher</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">connect</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'user.logout'</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Eventos'</span><span style="color: #339933;">,</span><span style="color: #0000ff;">'test'</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: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Con esto cada vez que un usuario cierre sesión, se ejecutará el método test de la clase Eventos, el cual deberá recibir como parámetro un objeto de la clase sfEvent. La misma implementación aplicará para el método <strong>signIn</strong>, para el caso en que el usuario inicie sesión. Espero sea de utilidad. </p>
]]></content:encoded>
			<wfw:commentRss>http://axiacore.com/2010/09/capturar-evento-logout-y-login-en-symfony/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introducción al manejo de eventos con Symfony</title>
		<link>http://axiacore.com/2010/07/introduccion-al-manejo-de-eventos-con-symfony/</link>
		<comments>http://axiacore.com/2010/07/introduccion-al-manejo-de-eventos-con-symfony/#comments</comments>
		<pubDate>Mon, 26 Jul 2010 17:17:22 +0000</pubDate>
		<dc:creator>Juan Pablo Romero Bernal</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Php]]></category>
		<category><![CDATA[Symfony]]></category>

		<guid isPermaLink="false">http://axiacore.com/?p=998</guid>
		<description><![CDATA[El tratamiento de eventos en el desarrollo de aplicaciones es algo muy común, para la muestra algunas situaciones típicas: Necesitamos enviar un correo electrónico al usuario cuando se registra Es necesario registrar las acciones que ejecutan los usuarios (creación y actualización de información) Cada vez que un usuario sube un archivo o califica algún contenido [...]]]></description>
			<content:encoded><![CDATA[<p>El tratamiento de eventos en el desarrollo de aplicaciones es algo muy común, para la muestra algunas situaciones típicas:</p>
<ul>
<li>Necesitamos enviar un correo electrónico al usuario cuando se registra</li>
<li>Es necesario registrar las acciones que ejecutan los usuarios (creación y actualización de información)</li>
<li>Cada vez que un usuario sube un archivo o califica algún contenido (imagen, artículo, etc.) se debe registrar la calificación junto con la hora y el usuario.</li>
</ul>
<p>y se pueden seguir listando muchas otras situaciones (dependiendo del tipo de aplicación). Una de las más usuales y cuya implementación es poco recomendable (desde mi punto vista) es cuando queremos registrar qué usuario creó y/o actualizó determinado registro en nuestra base de datos y el procedimiento a seguir es la sobrecarga del método save() de las clases (generadas por Doctrine o Propel) que componen nuestro modelo, agregando código que no corresponde con la responsabilidad de la clase. Otra posible implementación es agregar código en las acciones (actions.class.php) que se encargue de hacer el registro de los datos mencionados, haciendo más extensos los métodos y más complicados de leer.</p>
<p>Bien, para tratar de una mejor manera estos eventos existe un componente llamado <a href="http://components.symfony-project.org/event-dispatcher/">Event Dispatcher</a> (el cual viene integrado en Symfony desde su versión 1.1) y que hace parte de una serie de <a href="http://components.symfony-project.org/">componentes </a>que proveen los desarrolladores de Symfony. Este componente es una implementación ligera del patrón Observador y que permite de forma muy flexible definir y notificar eventos en nuestra aplicación.</p>
<h2>El objeto Dispatcher y los eventos</h2>
<p>El Event Dispatcher se compone de dos objetos fundamentales: Dispatcher (clase sfEventDispatcher) y eventos (clase sfEvent). El Objeto Dispatcher es el objeto central encargado de recibir todas las notificaciones y registros de los eventos y disparar los listeners asociados a dichos eventos.   Los eventos (instancias de la clase sfEvent) se describen a través de una cadena (por ejemplo: usuario.login), no es necesario implementar interfaces o crear nuevas clases que hereden de sfEvent para crear un evento.  Es importante saber que el constructor de un objeto sfEvent toma tres argumentos:</p>
<ul>
<li>El subject (quien notifica el evento)</li>
<li>El nombre del evento</li>
<li>Un arreglo de parámetros (que se pasarán al listener y puede ser nulo)</li>
</ul>
<p>Bien,  una vez creado nuestro evento es necesario hacerle saber al objeto Dispatcher la existencia del mismo a través del método connect  y posteriormente notificar su ocurrencia. Ahora veamos esto en la práctica.</p>
<h2>Implementando el evento</h2>
<p>Tomaremos como referencia que tenemos un proyecto con el plugin de sfGuard para el control básico de usuarios y que queremos registrar en una tabla de auditoria cada vez que un usuario crea un producto. A continuación la descripción del esquema de las tablas de producto, tipo de producto y auditoria:</p>
<pre>Producto:
  tableName: Producto
  columns:
    id:
      type: integer(4)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: true
    nombre:
      type: string(255)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
    tipoproducto_id:
      type: integer(4)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
  relations:
    TipoProducto:
      local: tipoproducto_id
      foreign: id
      type: one

TipoProducto:
  connection: doctrine
  tableName: TipoProducto
  columns:
    id:
      type: integer(4)
      fixed: false
      unsigned: false
      primary: true
      autoincrement: true
    nombre:
      type: string(255)
      fixed: false
      unsigned: false
      primary: false
      notnull: true
      autoincrement: false
  relations:
    Producto:
      local: id
      foreign: tipoproducto_id
      type: many

Auditoria:
  connection: doctrine
  tableName: auditoria
  actAs: [Timestampable]
  columns:
    id:
      type: integer(4)
      fixed: false
      unsigned: true
      primary: true
      autoincrement: true
    registro_id:
      type: integer(4)
      fixed: false
      unsigned: true
      primary: false
      notnull: true
      autoincrement: false
    entidad:
      type: string
    sf_guard_user_id:
      type: integer(4)
      fixed: false
      unsigned: false
      primary: false
      notnull: false
      autoincrement: false
  relations:
    SfGuardUser:
      local: sf_guard_user_id
      foreign: id
      type: one</pre>
<p>Con este modelo en mente, vamos a generar los módulos para el crud de productos y tipos de productos, a través de la tarea:</p>
<pre>php symfony doctrine:generate-module frontend productos Producto
php symfony doctrine:generate-module frontend tiposproducto TipoProducto</pre>
<p>Ahora, vamos a crear el evento y a notificarlo al objeto Dispatcher, modificando el método que guarda el producto (método processForm) de la clase productoActions como sigue:</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="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">protected</span> <span style="color: #000000; font-weight: bold;">function</span> processForm<span style="color: #009900;">&#40;</span>sfWebRequest <span style="color: #000088;">$request</span><span style="color: #339933;">,</span> sfForm <span style="color: #000088;">$form</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$form</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">bind</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$request</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getParameter</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$form</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getName</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #b1b100;">if</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$form</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">isValid</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
      try
      <span style="color: #009900;">&#123;</span>
          <span style="color: #000088;">$producto</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$form</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">save</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
         <span style="color: #666666; font-style: italic;">// Se crea el evento y se registra en el dispatcher</span>
          <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">dispatcher</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">notify</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> sfEvent<span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'producto.create'</span><span style="color: #339933;">,</span>
                  <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'entidad'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">'Producto'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'id'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #000088;">$producto</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getId</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
	      <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getUser</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setFlash</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'save_ok'</span><span style="color: #339933;">,</span>
                  <span style="color: #0000ff;">'Registro creado/editado correctamente'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span> catch <span style="color: #009900;">&#40;</span>Doctrine_Exception <span style="color: #000088;">$pe</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;">getUser</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setFlash</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'exception'</span><span style="color: #339933;">,</span> 
                  <span style="color: #0000ff;">'Ocurrió un error al momento de agregar/editar el registro'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
      <span style="color: #009900;">&#125;</span>
      <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">redirect</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'productos/index'</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></pre></td></tr></table></div>

<p>Bien, la línea 9 es la importante:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">dispatcher</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">notify</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> sfEvent<span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'producto.create'</span><span style="color: #339933;">,</span>
                  <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'entidad'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">'Producto'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'id'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #000088;">$producto</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getId</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Cuando se crea el objeto sfEvent se le están pasando tres argumentos: </p>
<ul>
<li>Subject: en nuestro caso quien notifica el evento es la clase productoActions, por eso usamos $this</li>
<li>Nombre del evento: hemos llamado al evento: producto.create</li>
<li>Arrreglo de argumentos: pasaremos como argumentos al listener la entidad que estamos creando (entidad) y el id.</li>
</ul>
<p>Una vez creado el evento, accedemos la instancia del objeto dispatcher y usamos el método notify (para otras formas de notificación se pueden usar los métodos notifyUntil y filter, ver más en la documentación del componente), para notificar que un producto ha sido creado. </p>
<p>Ahora, es necesario que asociemos un listener a ese evento (pues hasta el momento la notificación no sirve de nada). Para esto usamos el método connect del Dispatcher.  Vamos a agregar esta llamada dentro de la clase que configura nuestra aplicación (en este caso en el archivo frontendConfiguration.class.php):</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> frontendConfiguration <span style="color: #000000; font-weight: bold;">extends</span> sfApplicationConfiguration
<span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> configure<span style="color: #009900;">&#40;</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;">dispatcher</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">connect</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'producto.create'</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'Auditoria'</span><span style="color: #339933;">,</span><span style="color: #0000ff;">'registrarCreacion'</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: #009900;">&#125;</span></pre></div></div>

<p>El método connect recibe el nombre del evento y una función o método de una clase que será llamado cuando el evento sea notificado. En este caso, estamos pasando un arreglo como segundo argumento indicando que se llamará el método registrarCreacion de la  clase Auditoria, aunque también es posible pasar solamente el nombre de una función (debemos asegurarnos que el archivo donde se encuentre la definción de esta función haya sido cargado). Si utilizamos el método de una clase, este debe estar declarado como estático. Ahora bien, revisemos el código del método registrarCreacion:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> Auditoria <span style="color: #000000; font-weight: bold;">extends</span> BaseAuditoria
<span style="color: #009900;">&#123;</span>
    <span style="color: #000000; font-weight: bold;">public</span> static <span style="color: #000000; font-weight: bold;">function</span> registrarCreacion<span style="color: #009900;">&#40;</span>sfEvent <span style="color: #000088;">$event</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
        <span style="color: #000088;">$usuario</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$event</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getSubject</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getUser</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getGuardUser</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000088;">$a</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> Auditoria<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000088;">$a</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setRegistroId</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$event</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>
        <span style="color: #000088;">$a</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setEntidad</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$event</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'entidad'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000088;">$a</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setSfGuardUserId</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$usuario</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000088;">$a</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">save</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></pre></div></div>

<p>Una vez se notifica el evento y se llama al método registrarCreacion a este se le pasa como primer argumento el objeto sfEvent correspondiente, desde el cual podemos acceder el arreglo de argumentos que se pasaron al momento de notificar el evento (en el método processForm), como se ve en:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$a</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setRegistroId</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$event</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>
<span style="color: #000088;">$a</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setEntidad</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$event</span><span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'entidad'</span><span style="color: #009900;">&#93;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>
Listo, con este método creado, cada vez que un producto sea creado, se registrará en la tabla auditoria el usuario quien lo creó junto con la fecha y la hora.  Esto mismo puede aplicarse para envio de correo (usando SwitfMailer), envio de mensajes al usuario o a otras clases, todo dependiendo el gusto del desarrollador.  Espero que sea de utilidad y como siempre, los comentarios serán bien recibidos.</p>
]]></content:encoded>
			<wfw:commentRss>http://axiacore.com/2010/07/introduccion-al-manejo-de-eventos-con-symfony/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Symfony interactive shell</title>
		<link>http://axiacore.com/2009/11/symfony-interactive-shell/</link>
		<comments>http://axiacore.com/2009/11/symfony-interactive-shell/#comments</comments>
		<pubDate>Tue, 10 Nov 2009 18:48:51 +0000</pubDate>
		<dc:creator>Juan Pablo Romero Bernal</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Php]]></category>
		<category><![CDATA[Symfony]]></category>

		<guid isPermaLink="false">http://axiacore.com/blog/?p=792</guid>
		<description><![CDATA[The command line interface (known as cli) is a good tool for most developers, due ten fingers make more things than two. In fact, when we develop web applicactions using the Symfony framework several tasks are made through the command line, for instance: model generation, creation of database schemas, cache clear and so on. This [...]]]></description>
			<content:encoded><![CDATA[<p>The command line interface (known as cli) is a good tool for most developers, due ten fingers make more things than two. In fact, when we develop web applicactions using the Symfony framework several tasks are made through the command line, for instance: model generation, creation of database schemas, cache clear and so on. This tasks simplify the work in a significant way (if you are a symfony user, you know what i&#8217;m talking about).<span id="more-792"></span></p>
<p>Of course, this functionality is offered for the php command line interface (the php-cli), that sometimes is not enough to execute some actions such as: watch the object state, perform database inserts (and the typical crud operations), call methods in a interactive way, etc,. I know that some people says: the php cli has a interactive mode (-a option), but i think it is very limited. Talking with others developers, the php interpreter needs an interactive terminal (like python) and it keeps to work with our symfony projects.</p>
<p>The good new is that the facebook team has released (under BSD license) an interactive shell for php interpreter (as their own creators says: &#8221; &#8230; ironically written in python&#8221;) called <a href="http://www.phpsh.org">phpsh</a> and  it&#8217;s a great work !. I&#8217;ve perform some tests to integrate it with Symfony and i think, it can be a great tool for support and debugging.</p>
<p>Some simple examples:</p>
<p>After we installed phpsh (see the README file), we can work with php sentences and use the common functions:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">test$ phpsh
Starting php
type <span style="color: #0000ff;">'h'</span> or <span style="color: #0000ff;">'help'</span> to see instructions <span style="color: #339933;">&amp;</span>amp<span style="color: #339933;">;</span> features
php<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Hello world&quot;</span>
Hello world
php<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #000088;">$a</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">2</span><span style="color: #339933;">+</span><span style="color: #cc66cc;">3</span><span style="color: #339933;">;</span> <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$a</span>
<span style="color: #cc66cc;">5</span>
php<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #000088;">$f</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'one'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'two'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #cc66cc;">2</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'three'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #cc66cc;">3</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
php<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #b1b100;">foreach</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$f</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$n</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$n</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span>
<span style="color: #cc66cc;">123</span>
php<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #b1b100;">foreach</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$f</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$n</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$n</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: #009900;">&#125;</span>
<span style="color: #cc66cc;">1</span>
<span style="color: #cc66cc;">2</span>
<span style="color: #cc66cc;">3</span>
php<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #b1b100;">foreach</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$f</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$n</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
<span style="color: #339933;">...</span> <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$n</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: #339933;">...</span> <span style="color: #009900;">&#125;</span>
<span style="color: #cc66cc;">1</span>
<span style="color: #cc66cc;">2</span>
<span style="color: #cc66cc;">3</span>
php<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #b1b100;">echo</span> <span style="color: #990000;">count</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$f</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #cc66cc;">3</span></pre></div></div>

<p>Well, but right now, i&#8217;ll show you something more interesting: a symfony application using the interactive shell.  It not requires additional configuration, just load a file: the frontal controller of your app (in the web directory), for example:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">test$ phpsh web<span style="color: #339933;">/</span>index<span style="color: #339933;">.</span>php
Starting php with extra includes<span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'web/index.php'</span><span style="color: #009900;">&#93;</span>
 <span style="color: #339933;">.......................</span>
php<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span></pre></div></div>

<p>To hide the html output, we can create a copy of this file and avoid the call to dispatch method:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">require_once</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">dirname</span><span style="color: #009900;">&#40;</span><span style="color: #009900; font-weight: bold;">__FILE__</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">.</span><span style="color: #0000ff;">'/config/ProjectConfiguration.class.php'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$configuration</span> <span style="color: #339933;">=</span> ProjectConfiguration<span style="color: #339933;">::</span><span style="color: #004000;">getApplicationConfiguration</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'frontend'</span><span style="color: #339933;">,</span><span style="color: #0000ff;">'prod'</span><span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
sfContext<span style="color: #339933;">::</span><span style="color: #004000;">createInstance</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$configuration</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Now, load again (i&#8217;ve called shell.php):</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">test$ phpsh shell<span style="color: #339933;">.</span>php
Starting php with extra includes<span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'shell.php'</span><span style="color: #009900;">&#93;</span>
type <span style="color: #0000ff;">'h'</span> or <span style="color: #0000ff;">'help'</span> to see instructions <span style="color: #339933;">&amp;</span>amp<span style="color: #339933;">;</span> features
php<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #000088;">$c</span> <span style="color: #339933;">=</span> CityPeer<span style="color: #339933;">::</span><span style="color: #004000;">doSelect</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Criteria<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
php<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #b1b100;">foreach</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$c</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$city</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
 <span style="color: #339933;">...</span> <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$city</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: #339933;">...</span> <span style="color: #009900;">&#125;</span>
Barranquilla
Bogota
Berlin
Medellin
php<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span></pre></div></div>

<p>As you can see, it can be access to the model classes (i&#8217;m sorry with doctrine users) and the Symfony classes. For example, if my file app.yml looks like:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">all<span style="color: #339933;">:</span>
 results_per_page<span style="color: #339933;">:</span> <span style="color: #cc66cc;">15</span>
 sf_phpmailer<span style="color: #339933;">:</span>
   mailer<span style="color: #339933;">:</span>                    <span style="color: #009900; font-weight: bold;">true</span>
   smtp_auth<span style="color: #339933;">:</span>                 <span style="color: #009900; font-weight: bold;">true</span>
   smtp_secure<span style="color: #339933;">:</span>               <span style="color: #0000ff;">&quot;ssl&quot;</span>
   host<span style="color: #339933;">:</span>                      <span style="color: #0000ff;">&quot;smtp.example.com&quot;</span>
   port<span style="color: #339933;">:</span>                      <span style="color: #cc66cc;">600</span>
   username<span style="color: #339933;">:</span>                  <span style="color: #0000ff;">&quot;user&quot;</span>
   password<span style="color: #339933;">:</span>                  <span style="color: #0000ff;">&quot;password&quot;</span>
   from<span style="color: #339933;">:</span>                      <span style="color: #0000ff;">&quot;nobody@example.com&quot;</span>
   from_name<span style="color: #339933;">:</span>                 <span style="color: #0000ff;">&quot;NoBody&quot;</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">test$ phpsh shell<span style="color: #339933;">.</span>php
Starting php with extra includes<span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'shell.php'</span><span style="color: #009900;">&#93;</span>
type <span style="color: #0000ff;">'h'</span> or <span style="color: #0000ff;">'help'</span> to see instructions <span style="color: #339933;">&amp;</span>amp<span style="color: #339933;">;</span> features
php<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #000088;">$conf</span> <span style="color: #339933;">=</span> sfConfig<span style="color: #339933;">::</span><span style="color: #004000;">get</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'app_sf_phpmailer_port'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>php<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$conf</span><span style="color: #339933;">;</span>
<span style="color: #cc66cc;">600</span>
php<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #b1b100;">echo</span> sfConfig<span style="color: #339933;">::</span><span style="color: #004000;">get</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'app_results_per_page'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #cc66cc;">15</span>
php<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span></pre></div></div>

<p>Well, it&#8217;s easy and very interesting. I hope work in detail and make more experiments. That&#8217;s all folks !.</p>
]]></content:encoded>
			<wfw:commentRss>http://axiacore.com/2009/11/symfony-interactive-shell/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Trabajando con Symfony en forma interactiva</title>
		<link>http://axiacore.com/2009/11/trabajando-con-symfony-en-forma-interactiva/</link>
		<comments>http://axiacore.com/2009/11/trabajando-con-symfony-en-forma-interactiva/#comments</comments>
		<pubDate>Mon, 09 Nov 2009 06:23:33 +0000</pubDate>
		<dc:creator>Juan Pablo Romero Bernal</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Php]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Web]]></category>

		<guid isPermaLink="false">http://axiacore.com/blog/?p=781</guid>
		<description><![CDATA[Para algunos desarrolladores nos es muy cómodo trabajar desde la línea de comandos, ya que diez dedos hacen más que dos. De hecho cuando se desarrollan aplicaciones con Symfony, el uso de la terminal de comandos es fundamental para muchas tareas (generación del modelo, creación de esquemas de base de datos, limpiar la cache, etc,.) [...]]]></description>
			<content:encoded><![CDATA[<p>Para algunos desarrolladores nos es muy cómodo trabajar desde la línea de comandos, ya que diez dedos hacen más que dos. De hecho cuando se desarrollan aplicaciones con Symfony, el uso de la terminal de comandos es fundamental para muchas tareas (generación del modelo, creación de esquemas de base de datos, limpiar la cache, etc,.) que simplifican el trabajo significativamente.<span id="more-781"></span></p>
<p>Desde luego, todo esto es gracias a la interfaz en línea de comandos del ínterprete php (más conocido como php-cli), que en algunos casos se queda corto para ejecutar algunas pruebas: ver el estado de un objeto, insertar datos en la base de datos,  probar métodos de manera interactiva, etc,. Sé que algunos dirán que php-cli tiene un modo interactivo, pero en realidad desde mi punto de vista es muy limitado.  Sería muy interesante contar con algo similar a la terminal interactiva de python y desde luego que se pueda trabajar con nuestros proyectos en Symfony.</p>
<p>Lo mejor de todo, es que la gente de facebook liberó bajo licencia BSD una shell interactiva para php y como sus mismos credadores dicen: &#8220;&#8230; irónicamente escrita en python &#8230;.&#8221;; se llama <a href="http://www.phpsh.org/">phpsh</a> y realmente es un gran trabajo. He realizado algunas pruebas de integración con Symfony y creo que puede ser de gran apoyo para pruebas y aún más para las personas que están aprendiendo a trabajar con el framework.</p>
<p>A continuación van algunos de los sencillos experimentos realizados:</p>
<p>Una vez se haya instalado phpsh (leer el README), podemos trabajar  con sentencias de php y usar las funciones:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">test$ phpsh
Starting php
type <span style="color: #0000ff;">'h'</span> or <span style="color: #0000ff;">'help'</span> to see instructions <span style="color: #339933;">&amp;</span>amp<span style="color: #339933;">;</span> features
php<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #b1b100;">echo</span> <span style="color: #0000ff;">&quot;Hola mundo&quot;</span>
Hola mundo
php<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #000088;">$a</span> <span style="color: #339933;">=</span> <span style="color: #cc66cc;">2</span><span style="color: #339933;">+</span><span style="color: #cc66cc;">3</span><span style="color: #339933;">;</span> <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$a</span>
<span style="color: #cc66cc;">5</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">php<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #000088;">$f</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'uno'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #cc66cc;">1</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'dos'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #cc66cc;">2</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'tres'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #cc66cc;">3</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
php<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #b1b100;">foreach</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$f</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$n</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$n</span><span style="color: #339933;">;</span> <span style="color: #009900;">&#125;</span>
<span style="color: #cc66cc;">123</span>
php<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #b1b100;">foreach</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$f</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$n</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span> <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$n</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: #009900;">&#125;</span>
<span style="color: #cc66cc;">1</span>
<span style="color: #cc66cc;">2</span>
<span style="color: #cc66cc;">3</span></pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">php<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #b1b100;">foreach</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$f</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$n</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
<span style="color: #339933;">...</span> <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$n</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: #339933;">...</span> <span style="color: #009900;">&#125;</span>
<span style="color: #cc66cc;">1</span>
<span style="color: #cc66cc;">2</span>
<span style="color: #cc66cc;">3</span>
php<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #b1b100;">echo</span> <span style="color: #990000;">count</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$f</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #cc66cc;">3</span></pre></div></div>

<p>Bien, pero ahora viene algo un poco más interesante: usar a través del shell interactivo nuestra aplicación hecha en Symfony.</p>
<p>No requiere ninguna configuración especial, simplemente cargar un archivo y listo; se trata del controlador frontal de nuestra aplicación (alguno de los que se encuentra en web), así:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">test$ phpsh web<span style="color: #339933;">/</span>index<span style="color: #339933;">.</span>php
Starting php with extra includes<span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'web/index.php'</span><span style="color: #009900;">&#93;</span>
&nbsp;
  <span style="color: #339933;">.......................</span>
&nbsp;
php<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span></pre></div></div>

<p>Para obviar la salida html, podemos crear una copia de ese archivo y evitar la llamada al método dispatch(), así:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">require_once</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">dirname</span><span style="color: #009900;">&#40;</span><span style="color: #009900; font-weight: bold;">__FILE__</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">.</span><span style="color: #0000ff;">'/config/ProjectConfiguration.class.php'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
<span style="color: #000088;">$configuration</span> <span style="color: #339933;">=</span> ProjectConfiguration<span style="color: #339933;">::</span><span style="color: #004000;">getApplicationConfiguration</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'frontend'</span><span style="color: #339933;">,</span><span style="color: #0000ff;">'prod'</span><span style="color: #339933;">,</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
sfContext<span style="color: #339933;">::</span><span style="color: #004000;">createInstance</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$configuration</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Ahora, de nuevo lo cargamos (ese archivo lo he llamado shell.php):</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">test$ phpsh shell<span style="color: #339933;">.</span>php
Starting php with extra includes<span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'shell.php'</span><span style="color: #009900;">&#93;</span>
type <span style="color: #0000ff;">'h'</span> or <span style="color: #0000ff;">'help'</span> to see instructions <span style="color: #339933;">&amp;</span>amp<span style="color: #339933;">;</span> features
php<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #000088;">$c</span> <span style="color: #339933;">=</span> CiudadPeer<span style="color: #339933;">::</span><span style="color: #004000;">doSelect</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Criteria<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
php<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #b1b100;">foreach</span> <span style="color: #009900;">&#40;</span><span style="color: #000088;">$c</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$ciudad</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
 <span style="color: #339933;">...</span> <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$ciudad</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: #339933;">...</span> <span style="color: #009900;">&#125;</span>
Barranquilla
Bogota
Constantinopla
Medellin
&nbsp;
php<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span></pre></div></div>

<p>Como se puede ver, puedo acceder a las clases de mi modelo (disculpas a los usuarios de Doctrine) y desde luego a las clases que nos proporciona Symfony, por ejemplo si mi archivo <strong>apps/frontend/config/app.yml</strong> es:</p>

<div class="wp_syntax"><div class="code"><pre class="yml" style="font-family:monospace;">all:
 resultados_por_pagina: 15
 sf_phpmailer:
   mailer:                    true
   smtp_auth:                 true
   smtp_secure:               &quot;ssl&quot;
   host:                      &quot;smtp.mihost&quot;
   port:                      600
   username:                  &quot;miusuario&quot;
   password:                  &quot;miclave&quot;
   from:                      &quot;nosesabe@example.com&quot;
   from_name:                 &quot;Anonimo&quot;</pre></div></div>


<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">test$ phpsh shell<span style="color: #339933;">.</span>php
Starting php with extra includes<span style="color: #339933;">:</span> <span style="color: #009900;">&#91;</span><span style="color: #0000ff;">'shell.php'</span><span style="color: #009900;">&#93;</span>
type <span style="color: #0000ff;">'h'</span> or <span style="color: #0000ff;">'help'</span> to see instructions <span style="color: #339933;">&amp;</span>amp<span style="color: #339933;">;</span> features
php<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #000088;">$conf</span> <span style="color: #339933;">=</span> sfConfig<span style="color: #339933;">::</span><span style="color: #004000;">get</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'app_sf_phpmailer_port'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
php<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$conf</span><span style="color: #339933;">;</span>
<span style="color: #cc66cc;">600</span>
php<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #b1b100;">echo</span> sfConfig<span style="color: #339933;">::</span><span style="color: #004000;">get</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'app_resultados_por_pagina'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #cc66cc;">15</span>
php<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span></pre></div></div>

<p>Bueno, esos han sido los experimentos que he alcanzado a realizar. Espero trabajar más en detalle y publicar los resultados. Hasta una próxima.</p>
]]></content:encoded>
			<wfw:commentRss>http://axiacore.com/2009/11/trabajando-con-symfony-en-forma-interactiva/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Trabajando con filtros en Symfony (II)</title>
		<link>http://axiacore.com/2009/09/trabajando-con-filtros-en-symfony-ii/</link>
		<comments>http://axiacore.com/2009/09/trabajando-con-filtros-en-symfony-ii/#comments</comments>
		<pubDate>Sun, 20 Sep 2009 23:36:22 +0000</pubDate>
		<dc:creator>Juan Pablo Romero Bernal</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Desarrollo]]></category>
		<category><![CDATA[Doctrine]]></category>
		<category><![CDATA[Symfony]]></category>

		<guid isPermaLink="false">http://axiacore.com/blog/?p=755</guid>
		<description><![CDATA[Esta es una segunda entrega acerca del trabajo con los formularios de filtro en Symfony. He tenido en cuenta los comentarios y sugerencias de  los visitantes del blog,  así que esta entrega integrará el uso de Doctrine. Antes de comenzar,  aclaro que mucha de la información aquí consignada está basada en el código generado por [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">Esta es una segunda entrega acerca del trabajo con los formularios de filtro en Symfony. He tenido en cuenta los comentarios y sugerencias de  los visitantes del blog,  así que esta entrega integrará el uso de Doctrine.</p>
<p style="text-align: justify;">Antes de comenzar,  aclaro que mucha de la información aquí consignada está basada en el código generado por el generador de administración tanto de Propel como de Doctrine y desde luego en la documentación del API de Symfony 1.2.<span id="more-755"></span></p>
<h3 style="text-align: justify;"><strong>Filtros con Doctrine</strong></h3>
<p style="text-align: justify;">En la entrada anterior hablé del uso de los formularios con Propel de manera básica y aunque las forma de trabajar los formularios de filtros con Doctrine no es muy diferente, haré algunas aclaraciones importantes.</p>
<p style="text-align: justify;">Al momento de generar el modelo con Doctrine, con la tarea:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">php symfony doctrine<span style="color: #339933;">:</span>build<span style="color: #339933;">-</span>all</pre></div></div>

<p style="text-align: justify;">al igual con con Propel, se genera en el directorio  <strong>lib/filter/doctrine/</strong> el conjunto de clases de formularios de filtro. Tomando como referencia el esquema de datos del tutorial de Jobeet (Día 3 &#8211; <a href="http://www.symfony-project.org/jobeet/1_2/Doctrine/en/03">http://www.symfony-project.org/jobeet/1_2/Doctrine/en/03</a>) los filtros generados son:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">BaseFormFilterDoctrine<span style="color: #339933;">.</span><span style="color: #000000; font-weight: bold;">class</span><span style="color: #339933;">.</span>php
JobeetAffiliateFormFilter<span style="color: #339933;">.</span><span style="color: #000000; font-weight: bold;">class</span><span style="color: #339933;">.</span>php
JobeetCategoryAffiliateFormFilter<span style="color: #339933;">.</span><span style="color: #000000; font-weight: bold;">class</span><span style="color: #339933;">.</span>php
JobeetCategoryFormFilter<span style="color: #339933;">.</span><span style="color: #000000; font-weight: bold;">class</span><span style="color: #339933;">.</span>php
JobeetJobFormFilter<span style="color: #339933;">.</span><span style="color: #000000; font-weight: bold;">class</span><span style="color: #339933;">.</span>php
base<span style="color: #339933;">/</span></pre></div></div>

<p style="text-align: justify;">Estas clases podemos modificarlas según nuestras necesidades, al igual que con los formularios. Ahora, vamos a generar el módulo que permita el CRUD de las ofertas de trabajo (Tabla Jobeet_Job):</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">php symfony doctrine<span style="color: #339933;">:</span>generate<span style="color: #339933;">-</span>module frontend job JobeetJob</pre></div></div>

<p>Bien, ahora con el módulo generado, vamos a revisar  las acciones y hacer los ajustes para el uso de los filtros. En primera forma, debemos modificar la acción index, para que nos presente el formulario de filtros:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> jobActions <span style="color: #000000; font-weight: bold;">extends</span> sfActions
<span style="color: #666666; font-style: italic;">// apps/frontend/modules/job/actions/actions.class.php</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> executeIndex<span style="color: #009900;">&#40;</span>sfWebRequest <span style="color: #000088;">$request</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>jobeet_job_list <span style="color: #339933;">=</span> Doctrine<span style="color: #339933;">::</span><span style="color: #004000;">getTable</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'JobeetJob'</span><span style="color: #009900;">&#41;</span>
    <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>createQuery<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'a'</span><span style="color: #009900;">&#41;</span>
    <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>execute<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>filtro <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> JobeetJobFormFilter<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// más código .....</span></pre></div></div>

<p>Al igual que con Propel, debemos crear una instancia del filtro, para que sea visualizada en la plantilla:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// apps/frontend/modules/job/templates/indexSuccess.php</span>
&nbsp;
<span style="color: #339933;">&lt;</span>h1<span style="color: #339933;">&gt;</span>Lista de trabajos<span style="color: #339933;">&lt;/</span>h1<span style="color: #339933;">&gt;</span>
&nbsp;
&nbsp;
<span style="color: #339933;">&lt;</span>h1<span style="color: #339933;">&gt;</span>Lista de trabajos<span style="color: #339933;">&lt;/</span>h1<span style="color: #339933;">&gt;</span>
&nbsp;
<span style="color: #339933;">&lt;</span>form action<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;&amp;lt;?php echo url_for('job/filter'); ?&amp;gt;&quot;</span> method<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;post&quot;</span><span style="color: #339933;">&gt;</span>
&nbsp;
&nbsp;
<span style="color: #339933;">&lt;</span>input <span style="color: #000000; font-weight: bold;">class</span><span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;ui-state-default ui-corner-all&quot;</span> type<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;submit&quot;</span> value<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;Filtrar&quot;</span> <span style="color: #339933;">/&gt;</span>
   <span style="color: #0000ff;">'_reset'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'method'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #0000ff;">'post'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> ?<span style="color: #339933;">&amp;</span>gt<span style="color: #339933;">;</span>
&nbsp;
<span style="color: #339933;">&lt;/</span>form<span style="color: #339933;">&gt;</span>
&nbsp;
<span style="color: #339933;">&lt;!--</span>   más código html <span style="color: #339933;">...</span> <span style="color: #339933;">--&gt;</span></pre></div></div>

<p>Creamos nuestra acción encargada de filtrar los resultados (filter):</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// apps/frontend/modules/job/actions/actions.class.php</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> executeFilter<span style="color: #009900;">&#40;</span>sfWebRequest <span style="color: #000088;">$request</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>filtro <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> JobeetJobFormFilter<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>consulta <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>filtro<span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>buildQuery<span style="color: #009900;">&#40;</span><span style="color: #000088;">$request</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>getParameter<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'jobeet_job_filters'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>jobeet_job_list <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>consulta<span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>execute<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>setTemplate<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'index'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p style="text-align: justify;">Una de las diferencias importantes con Propel, es el método que se encarga de construir la consulta según el valor de los filtros,  que es buildQuery y que recibe una arreglo de valores a partir de los cuales se construirá la consulta. Este método devuelve un objeto de tipo Doctrine_Query, por eso llamamos al método execute en forma posterior.</p>
<p style="text-align: justify;">Con lo anterior tenemos un sistema de filtros muy básico usando Doctrine como ORM.</p>
<h3 style="text-align: justify;">Adaptando el filtro</h3>
<p style="text-align: justify;">Hasta el momento, ya hemos visto como establecer un filtro, tanto si usamos Propel como Doctrine. Sin embargo, la mayoría de las veces los campos por los cuales deseamos filtrar información no corresponden con todos los de la tabla. El filtro por defecto que se genera contempla todos los campos y por ello es necesario que hagamos algunas modificaciones, para filtrar por los campos deseados.</p>
<p style="text-align: justify;">Siguiendo con el ejemplo del tutorial de Jobeet, supongamos que sólo queremos filtrar la lista de trabajos, por categoría  y tipo (campos category y type, respectivamente), para ello debemos modificar el método configure de la clase JobeetJobFormFilter:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #666666; font-style: italic;">// lib/form/doctrine/JobeetJobFormFilter.class.php</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> JobeetJobFormFilter <span style="color: #000000; font-weight: bold;">extends</span> BaseJobeetJobFormFilter
<span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> configure<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
   <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>setWidgets<span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
    <span style="color: #0000ff;">'category_id'</span>  <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">new</span> sfWidgetFormDoctrineChoice<span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'model'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #0000ff;">'JobeetCategory'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'add_empty'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
    <span style="color: #0000ff;">'type'</span>         <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">new</span> sfWidgetFormFilterInput<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
   <span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>setValidators<span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
    <span style="color: #0000ff;">'category_id'</span>  <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">new</span> sfValidatorDoctrineChoice<span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'required'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'model'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #0000ff;">'JobeetCategory'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'column'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #0000ff;">'id'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
    <span style="color: #0000ff;">'type'</span>         <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">new</span> sfValidatorPass<span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'required'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
   <span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>widgetSchema<span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>setNameFormat<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'jobeet_job_filters[%s]'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
 <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p style="text-align: justify;">Cómo se puede observar, un formulario de filtro es muy similar a un formulario, con algunas diferencias en cuanto a los widgets que se usan y algunos de los métodos.  Con esta modificación, cuando imprimamos el filtro en la plantilla, ahora sólo los campos de categoría y tipo estarán disponibles.  También podemos usar los métodos setLabel y setLabels para cambiar el nombre de las etiquetas que aparecerán al momento de imprimir el formulario de filtros, por ejemplo:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>getWidgetSchema<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>setLabels<span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
   <span style="color: #0000ff;">'category_id'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #0000ff;">'Categoria'</span><span style="color: #339933;">,</span>
   <span style="color: #0000ff;">'type'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #0000ff;">'Tipo'</span>
<span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p style="text-align: justify;">Uno de los widgets de filtros que considero más útiles es sfWidgetFormFilterDate, ya que con él es posible filtrar información por rangos de fecha, aquí un ejemplo de su uso para el campo de expiración de la oferta de trabajo (campo expires_at):</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #0000ff;">'expires_at'</span>   <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">new</span> sfWidgetFormFilterDate<span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
                 <span style="color: #0000ff;">'from_date'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">new</span> sfWidgetFormDate<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
                 <span style="color: #0000ff;">'to_date'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">new</span> sfWidgetFormDate<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
                 <span style="color: #0000ff;">'with_empty'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #cc66cc;">0</span><span style="color: #339933;">,</span>                   <span style="color: #666666; font-style: italic;">// Para que no salga el checkbox</span>
                 <span style="color: #0000ff;">'template'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #0000ff;">'desde %from_date% hasta %to_date%'</span>
                <span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span></pre></div></div>

<p>Bien, hasta aquí esta segunda entrega del trabajo con filtros en Symfony 1.2. Espero que sea  de utilidad.</p>
]]></content:encoded>
			<wfw:commentRss>http://axiacore.com/2009/09/trabajando-con-filtros-en-symfony-ii/feed/</wfw:commentRss>
		<slash:comments>24</slash:comments>
		</item>
		<item>
		<title>Trabajando con filtros en Symfony (I)</title>
		<link>http://axiacore.com/2009/09/trabajando-con-filtros-en-symfony-i/</link>
		<comments>http://axiacore.com/2009/09/trabajando-con-filtros-en-symfony-i/#comments</comments>
		<pubDate>Mon, 14 Sep 2009 03:12:32 +0000</pubDate>
		<dc:creator>Juan Pablo Romero Bernal</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Desarrollo]]></category>
		<category><![CDATA[Symfony]]></category>

		<guid isPermaLink="false">http://axiacore.com/blog/?p=744</guid>
		<description><![CDATA[Esta es una entrada bastante rápida, pero que busca mostrar la forma básica en que se pueden usar los formularios de filtros en Symfony (versión 1.2) para facilitar a los usuarios la clasificación y consulta de información.  El manejo de formularios de filtros es muy similar a los formularios que se usan para el ingreso [...]]]></description>
			<content:encoded><![CDATA[<p style="text-align: justify;">Esta es una entrada bastante rápida, pero que busca mostrar la forma básica en que se pueden usar los formularios de filtros en Symfony (versión 1.2) para facilitar a los usuarios la clasificación y consulta de información.  El manejo de formularios de filtros es muy similar a los formularios que se usan para el ingreso y/o edición de información,  con algunas variaciones. Hago claridad que las pruebas que he realizado han sido usando Propel como ORM.<span id="more-744"></span></p>
<p style="text-align: justify;">Bien, empecemos por saber que en Symfony existe una tarea que nos permite construir en forma automática los formularios de filtros, de la siguiente forma:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">$ php symfony propel<span style="color: #339933;">:</span>build<span style="color: #339933;">-</span>filters</pre></div></div>

<p>Después de la ejecución de esta tarea, en el directorio <strong>lib/filters</strong> de nuestro proyecto, se habrán creado (de acuerdo a nuestro modelo) un conjunto de clases cuyo nombre sigue la siguiente nomenclatura:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">ClaseFormFilter<span style="color: #339933;">.</span><span style="color: #000000; font-weight: bold;">class</span><span style="color: #339933;">.</span>php</pre></div></div>

<p style="text-align: justify;">y al igual que con el modelo y los formularios, tendremos unas clases Base y unas clases que extenderán de esas clases base, las cuales podemos adaptar según nuestras necesidades. Una vez creadas nuestras clases de formularios de filtros, ya podemos usarlas dentro de nuestras acciones. Tomaré como ejemplo, que tenemos un modulo llamado clientes que permite trabajar con el CRUD normal y que cada cliente tiene un nombre, telefono y una ciudad, de modo que nuestra clase base de formulario de filtro lucirá así:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> BaseClienteFormFilter <span style="color: #000000; font-weight: bold;">extends</span> BaseFormFilterPropel
<span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> setup<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
&nbsp;
  <span style="color: #009900;">&#123;</span>
     <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>setWidgets<span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
      <span style="color: #0000ff;">'nombre'</span>    <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">new</span> sfWidgetFormFilterInput<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
      <span style="color: #0000ff;">'telefono'</span>  <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">new</span> sfWidgetFormFilterInput<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
      <span style="color: #0000ff;">'ciudad_id'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">new</span> sfWidgetFormPropelChoice<span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
            <span style="color: #0000ff;">'model'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #0000ff;">'Ciudad'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'add_empty'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
       <span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>setValidators<span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
    <span style="color: #0000ff;">'nombre'</span>    <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">new</span> sfValidatorPass<span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'required'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
    <span style="color: #0000ff;">'telefono'</span>  <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">new</span> sfValidatorPass<span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'required'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
    <span style="color: #0000ff;">'ciudad_id'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">new</span> sfValidatorPropelChoice<span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'required'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #009900; font-weight: bold;">false</span><span style="color: #339933;">,</span>
                                 <span style="color: #0000ff;">'model'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #0000ff;">'Ciudad'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'column'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #0000ff;">'id'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
   <span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
   <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>widgetSchema<span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>setNameFormat<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'cliente_filters[%s]'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>errorSchema <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> sfValidatorErrorSchema<span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>validatorSchema<span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
   parent<span style="color: #339933;">::</span><span style="color: #004000;">setup</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> getModelName<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">return</span> <span style="color: #0000ff;">'Cliente'</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> getFields<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
    <span style="color: #b1b100;">return</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
     <span style="color: #0000ff;">'id'</span>        <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #0000ff;">'Number'</span><span style="color: #339933;">,</span>
     <span style="color: #0000ff;">'nombre'</span>    <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #0000ff;">'Text'</span><span style="color: #339933;">,</span>
     <span style="color: #0000ff;">'telefono'</span>  <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #0000ff;">'Text'</span><span style="color: #339933;">,</span>
     <span style="color: #0000ff;">'ciudad_id'</span> <span style="color: #339933;">=&amp;</span>gt<span style="color: #339933;">;</span> <span style="color: #0000ff;">'ForeignKey'</span><span style="color: #339933;">,</span>
   <span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p style="text-align: justify;">Tengamos en cuenta que esta clase es generada automáticamente y podemos hacer las modificaciones necesarias en la clase ClienteFormFilter, como se hace con los formularios.  Ahora bien, vamos a utilizar este formulario de filtro en nuestra acción index de nuestro módulo de clientes, de la siguiente forma:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">class</span> clientesActions <span style="color: #000000; font-weight: bold;">extends</span> sfActions
<span style="color: #009900;">&#123;</span>
  <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> executeIndex<span style="color: #009900;">&#40;</span>sfWebRequest <span style="color: #000088;">$request</span><span style="color: #009900;">&#41;</span>
  <span style="color: #009900;">&#123;</span>
     <span style="color: #666666; font-style: italic;">// creamos el filtro ....</span>
     <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>filtro <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ClienteFormFilter<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
     <span style="color: #666666; font-style: italic;">// .....</span>
     <span style="color: #666666; font-style: italic;">// más código ....</span>
     <span style="color: #666666; font-style: italic;">// Típica consulta  ....</span>
     <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>clientes <span style="color: #339933;">=</span> CientePeer<span style="color: #339933;">::</span><span style="color: #004000;">doSelect</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> Criteria<span style="color: #009900;">&#40;</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: #009900;">&#125;</span></pre></div></div>

<p>En nuestra plantilla: (indexSuccess.php)</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #339933;">&lt;</span>form action<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;&amp;lt;?php echo url_for('clientes/filtrar'); ?&amp;gt;&quot;</span> method<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;post&quot;</span><span style="color: #339933;">&gt;</span>
&nbsp;
<span style="color: #339933;">&lt;</span>table<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;</span>tbody<span style="color: #339933;">&gt;&lt;/</span>tbody<span style="color: #339933;">&gt;</span>
<span style="color: #339933;">&lt;/</span>table<span style="color: #339933;">&gt;</span>
&nbsp;
<span style="color: #339933;">&lt;</span>input name<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;filtrar&quot;</span> type<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;submit&quot;</span> value<span style="color: #339933;">=</span><span style="color: #0000ff;">&quot;Filtrar&quot;</span> <span style="color: #339933;">/&gt;</span>
<span style="color: #339933;">&lt;/</span>form<span style="color: #339933;">&gt;</span>
&nbsp;
<span style="color: #666666; font-style: italic;">// otro codigo html ....</span></pre></div></div>

<p style="text-align: justify;">Bien, hasta aquí nada nuevo, simplemente un formulario más, que aparecerá en nuestra acción index de nuestro módulo de clientes, pero con la diferencia que será procesado por la acción filtrar (o como decida llamarse). En este punto es importante mencionar, que para la ejecución del filtrado, se empleará el método buildCriteria, el cuál recibe como parámetro un arreglo (los campos por  los  cuales se desea hacer el filtro) y se encarga de construir las consultas:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> executeFiltrar<span style="color: #009900;">&#40;</span>sfWebRequest <span style="color: #000088;">$request</span><span style="color: #009900;">&#41;</span>
<span style="color: #009900;">&#123;</span>
  <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>filtro <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> ClienteFormFilter<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #666666; font-style: italic;">// Construye un objeto criteria con el valor de los filtros</span>
  <span style="color: #000088;">$criteria</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>filtro<span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>buildCriteria<span style="color: #009900;">&#40;</span><span style="color: #000088;">$request</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>getParameter<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'cliente_filters'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>clientes <span style="color: #339933;">=</span> ClientePeer<span style="color: #339933;">::</span><span style="color: #004000;">doSelect</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$criteria</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #000088;">$this</span><span style="color: #339933;">-&amp;</span>gt<span style="color: #339933;">;</span>setTemplate<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'index'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p style="text-align: justify;">El método buildCriteria es el encargado de construir la consulta según el valor de los filtros (revise la clase sfFormFilterPropel y los métodos addXXXCriteria() de la misma clase). Posteriormente pasamos ese objeto criteria a el método doSelect para devolver la consulta filtrada usando la plantilla de la acción index.  Sencillo, no ??</p>
<p style="text-align: justify;">En una próxima entrada se explicará lo referente al manejo de formularios de filtro y el mantenimiento de los resultados obtenidos por el filtro entre páginas.</p>
]]></content:encoded>
			<wfw:commentRss>http://axiacore.com/2009/09/trabajando-con-filtros-en-symfony-i/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
	</channel>
</rss>

