<?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>Jon Segador &#187; Symfony</title>
	<atom:link href="http://jonsegador.com/category/symfony/feed/" rel="self" type="application/rss+xml" />
	<link>http://jonsegador.com</link>
	<description>Desarrollador web y android, con todo lo que ello implica</description>
	<lastBuildDate>Wed, 16 May 2012 08:34:41 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Relaciones en Symfony 1.4 con Doctrine</title>
		<link>http://jonsegador.com/2011/06/relaciones-en-symfony-1-4-con-doctrine/</link>
		<comments>http://jonsegador.com/2011/06/relaciones-en-symfony-1-4-con-doctrine/#comments</comments>
		<pubDate>Thu, 16 Jun 2011 22:42:09 +0000</pubDate>
		<dc:creator>Jon</dc:creator>
				<category><![CDATA[Bases de datos]]></category>
		<category><![CDATA[Desarrollo]]></category>
		<category><![CDATA[Symfony]]></category>
		<category><![CDATA[base de datos]]></category>
		<category><![CDATA[doctrine]]></category>
		<category><![CDATA[relaciones]]></category>

		<guid isPermaLink="false">http://jonsegador.com/?p=436</guid>
		<description><![CDATA[Una de las dificultades que podemos encontrar al utilizar el ORM Doctrine (por ejemplo, en Symfony) es configurar las relaciones entre tablas en el schema.yml que define nuestra base de datos. A modo de ejemplo, voy a mostrar los tres tipos de relaciones que podemos querer configurar: Relaciones uno a uno Un caso típico para [...]]]></description>
			<content:encoded><![CDATA[<p>Una de las dificultades que podemos encontrar al utilizar el ORM <a href="http://jonsegador.com/tag/doctrine/">Doctrine</a> (por ejemplo, en <a href="http://jonsegador.com/category/symfony/">Symfony</a>) es configurar las relaciones entre tablas en el schema.yml que define nuestra <a href="http://jonsegador.com/category/bases-de-datos/">base de datos</a>. A modo de ejemplo, voy a mostrar los tres tipos de relaciones que podemos querer configurar:</p>
<h4><strong>Relaciones uno a uno</strong></h4>
<p>Un caso típico para este tipo de relación es el de un usuario y su perfil. <strong>Un usuario solamente tiene un perfil y un perfil solo puede pertenecer a un usuario.</strong></p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">User:
  tableName: user
  columns:
    id:
      type: integer(4)
      primary: true
      notnull: true
      autoincrement: true
    email:
      type: string(255)
      notnull: true
      unique: true
    password:
      type: string(45)
&nbsp;
Profile:
  tableName: profile
  columns:
    user_id:
      type: integer(4)
      primary: true
      notnull: true
      autoincrement: false
    nickname: string(255)
  relations:
    User:
      class: User
      local: user_id
      foreign: id
      foreignAlias: Profile
      type: one
      foreignType: one</pre></div></div>

<p>Con esta relación, podremos acceder al perfil de un usuario así:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$user</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">Profile</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">nickname</span> <span style="color: #666666; font-style: italic;">// obtenemos el nickname del perfil del usuario</span></pre></div></div>

<h4><strong>Relaciones uno a muchos:</strong></h4>
<p>Un ejemplo de este tipo de relación es el de los usuarios y sus números de teléfono. <strong>Un usuario puede tener varios números de teléfono pero un teléfono solo puede pertenecer a un usuario.</strong></p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">User:
  tableName: user
  columns:
    id:
      type: integer(4)
      primary: true
      notnull: true
      autoincrement: true
    email:
      type: string(255)
      notnull: true
      unique: true
    password:
      type: string(45)
&nbsp;
Telephone:
  tableName: telephone
  columns:
    id:
      type: integer(4)
      primary: true
      notnull: true
      autoincrement: true
    user_id:
      type: integer(4)
      notnull: true
    number:
      type: string(255)
  relations:
    User:
      class: User
      local: user_id
      foreign: id
      foreignAlias: Telephones
      type: one
      foreignType: many</pre></div></div>

<p>Para acceder a los números de teléfono de un usuario, podemos hacer:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$user</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">Telephones</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$telephone</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
  <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$telephone</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">number</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<h4><strong>Relaciones muchos a muchos</strong></h4>
<p>Para terminar, un caso típico de esta relación es la que podemos encontrar entre los artículos de un blog y sus etiquetas. <strong>Un artículo puede tener varias etiquetas y una etiqueta puede asignarse a varios artículos.</strong> En esta relación necesitaremos obligatoriamente una tercera tabla (article_tags) para poder relacionar la tabla articles y la tabla tags.</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">Article:
  tableName: articles
  columns:
    id:
      type: integer(4)
      primary: true
      notnull: true
      autoincrement: true
    title:
      type: string(100)
      notnull: true
&nbsp;
Tag:
  tableName: tags
  columns:
    id:
      type: integer(4)
      primary: true
      notnull: true
      autoincrement: true
    name:
      type: string(100)
      notnull: true
  relations:
    Article:
      foreignAlias: Tags
      class: Article
      refClass: ArticleTag
&nbsp;
ArticleTag:
  tableName: article_tags
  columns:
    article_id:
      type: integer(4)
      primary: true
    tag_id:
      type: integer(4)
      primary: true
  relations:
    Article:
      foreignAlias: ArticleTags
    Tag:
      foreignAlias: ArticleTags</pre></div></div>

<p>Podremos obtener el nombre de todos los tags de un artículo de la siguiente manera:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #b1b100;">foreach</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$article</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">ArticleTags</span> <span style="color: #b1b100;">as</span> <span style="color: #000088;">$article_tag</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
      <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$article_tag</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">Tag</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">name</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></div></div>

<p>¡Cualquier duda, en los comentarios!</p>
]]></content:encoded>
			<wfw:commentRss>http://jonsegador.com/2011/06/relaciones-en-symfony-1-4-con-doctrine/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Symfony 1.4 task error: The default context does not exist</title>
		<link>http://jonsegador.com/2011/05/symfony-1-4-task-error-the-default-context-does-not-exist/</link>
		<comments>http://jonsegador.com/2011/05/symfony-1-4-task-error-the-default-context-does-not-exist/#comments</comments>
		<pubDate>Wed, 11 May 2011 23:19:12 +0000</pubDate>
		<dc:creator>Jon</dc:creator>
				<category><![CDATA[Desarrollo]]></category>
		<category><![CDATA[Symfony]]></category>
		<category><![CDATA[context]]></category>
		<category><![CDATA[error]]></category>
		<category><![CDATA[sfContext]]></category>
		<category><![CDATA[task]]></category>

		<guid isPermaLink="false">http://jonsegador.com/?p=427</guid>
		<description><![CDATA[Existe un problema bastante frecuente cuando ejecutamos un task en Symfony 1.4, pareciéndonos el siguiente error: &#8220;The default context does not exist&#8221; El problema es que estás utilizando un método de un objeto que utiliza sfContext (para recuperar valores del archivo app.yml, por ejemplo). Parece ser que Symfony no crea una instancia de sfContext y [...]]]></description>
			<content:encoded><![CDATA[<p>Existe un problema bastante frecuente cuando ejecutamos un <strong>task</strong> en <strong>Symfony 1.4</strong>, pareciéndonos el siguiente error:</p>
<p><strong>&#8220;The default context does not exist&#8221;</strong></p>
<p>El problema es que estás utilizando un método de un objeto que utiliza <strong>sfContext</strong> (para recuperar valores del archivo app.yml, por ejemplo). Parece ser que Symfony no crea una instancia de sfContext y nos devuelve este error.</p>
<p>La siguiente línea debería resolver el problema. La colocaremos en primer lugar dentro de la función execute:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">sfContext<span style="color: #339933;">::</span><span style="color: #004000;">createInstance</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">configuration</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></div></div>

<p>Por ejemplo:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">protected <span style="color: #000000; font-weight: bold;">function</span> execute <span style="color: #009900;">&#40;</span><span style="color: #000088;">$arguments</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #000088;">$options</span> <span style="color: #339933;">=</span> <span style="color: #990000;">array</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>
  sfContext<span style="color: #339933;">::</span><span style="color: #004000;">createInstance</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">configuration</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #666666; font-style: italic;">// Aqui nuestro codigo</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

]]></content:encoded>
			<wfw:commentRss>http://jonsegador.com/2011/05/symfony-1-4-task-error-the-default-context-does-not-exist/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Formulario de login (y logout) básico en Symfony 1.4</title>
		<link>http://jonsegador.com/2011/03/formulario-de-login-y-logout-basico-en-symfony-1-4/</link>
		<comments>http://jonsegador.com/2011/03/formulario-de-login-y-logout-basico-en-symfony-1-4/#comments</comments>
		<pubDate>Thu, 03 Mar 2011 09:44:17 +0000</pubDate>
		<dc:creator>Jon</dc:creator>
				<category><![CDATA[Desarrollo]]></category>
		<category><![CDATA[Symfony]]></category>
		<category><![CDATA[formularios]]></category>
		<category><![CDATA[login]]></category>
		<category><![CDATA[logout]]></category>
		<category><![CDATA[registro]]></category>

		<guid isPermaLink="false">http://jonsegador.com/?p=371</guid>
		<description><![CDATA[En el post anterior creamos un sistema de registro de usuarios básico para Symfony 1.4. Lo que vamos a hacer ahora es un sistema de login (y logout) para que el usuario pueda iniciar sesión en nuestra web. Primero creamos el formulario de login, por lo que creamos un nuevo archivo: /lib/form/LoginForm.class.php 1 2 3 [...]]]></description>
			<content:encoded><![CDATA[<p>En el post anterior creamos un sistema de <a href="http://jonsegador.com/2011/03/formulario-de-registro-basico-en-symfony-1-4/"><strong>registro de usuarios básico para Symfony 1.4</strong></a>. Lo que vamos a hacer ahora es un <strong>sistema de login (y logout) para que el usuario pueda iniciar sesión en nuestra web</strong>.</p>
<p>Primero creamos el formulario de login, por lo que creamos un nuevo archivo:</p>
<p>/lib/form/LoginForm.class.php</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #000000; font-weight: bold;">class</span> LoginForm <span style="color: #000000; font-weight: bold;">extends</span> BaseForm
<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>
    parent<span style="color: #339933;">::</span><span style="color: #004000;">configure</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setWidgets</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
      <span style="color: #0000ff;">'email'</span>        <span style="color: #339933;">=&gt;</span> <span style="color: #000000; font-weight: bold;">new</span> sfWidgetFormInput<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
      <span style="color: #0000ff;">'password'</span>  <span style="color: #339933;">=&gt;</span> <span style="color: #000000; font-weight: bold;">new</span> sfWidgetFormInputPassword<span style="color: #009900;">&#40;</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;">-&gt;</span><span style="color: #004000;">setValidators</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
      <span style="color: #0000ff;">'email'</span>        <span style="color: #339933;">=&gt;</span> <span style="color: #000000; font-weight: bold;">new</span> sfValidatorEmail<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;">=&gt;</span>true<span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'required'</span><span style="color: #339933;">=&gt;</span><span style="color: #0000ff;">'El email es obligatorio'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
      <span style="color: #0000ff;">'password'</span>  <span style="color: #339933;">=&gt;</span> <span style="color: #000000; font-weight: bold;">new</span> sfValidatorString<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;">=&gt;</span>true<span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'required'</span><span style="color: #339933;">=&gt;</span><span style="color: #0000ff;">'Escribe tu contraseña'</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;">-&gt;</span><span style="color: #004000;">widgetSchema</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setNameFormat</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'login[%s]'</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;">widgetSchema</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setFormFormatterName</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'list'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>El formulario no tiene mayor misterior. Un input text para el email y un input password para la contraseña. Validamos que se hayan rellenado los dos campos.</p>
<p>Editamos las actions del módulo user que creamos en el post anterior para añadir el login.</p>
<p>/apps/frontend/modules/user/actions/actions.class.php</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #000000; font-weight: bold;">class</span> userActions <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> executeLogin<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;">-&gt;</span><span style="color: #004000;">form</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> LoginForm<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$request</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">isMethod</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;post&quot;</span><span style="color: #009900;">&#41;</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;">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: #0000ff;">&quot;login&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">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>
           <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #339933;">!</span><span style="color: #000088;">$user</span> <span style="color: #339933;">=</span> UserTable<span style="color: #339933;">::</span><span style="color: #004000;">login</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">form</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getValue</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;email&quot;</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;">form</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getValue</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;password&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
               <span style="color: #666666; font-style: italic;">// No hemos conseguido loguear al usuario</span>
               <span style="color: #666666; font-style: italic;">// Redirigimos de nuevo al login con un mensaje de error</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;">&quot;error&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;datos incorrectos&quot;</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;">redirect</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;@user_login&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
           <span style="color: #009900;">&#125;</span><span style="color: #b1b100;">else</span><span style="color: #009900;">&#123;</span>
               <span style="color: #666666; font-style: italic;">// Logueamos</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;">setAuthenticated</span><span style="color: #009900;">&#40;</span><span style="color: #009900; font-weight: bold;">true</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;">setAttribute</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;id&quot;</span><span style="color: #339933;">,</span><span style="color: #000088;">$user</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">id</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
               <span style="color: #666666; font-style: italic;">// Comprobamos si tiene referer, si no, le llevamos a la homepage</span>
               <span style="color: #000088;">$url</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;">getAttribute</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;referer&quot;</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><span style="color: #0000ff;">&quot;@homepage&quot;</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;">setAttribute</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;referer&quot;</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>
               <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: #000088;">$url</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
           <span style="color: #009900;">&#125;</span>
        <span style="color: #009900;">&#125;</span>
&nbsp;
  <span style="color: #009900;">&#125;</span>
&nbsp;
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Tenemos que comprobar si existe ese email junto con esa contraseña en nuestra base de datos. Si es así, logueamos al usuario y, si no, mostramos un mensaje de error.<br />
La comprobación de si existe el usuario en la base de datos la hacemos en la linea 12, donde llamamos al método estático &#8220;login&#8221; del archivo UserTable.class.php del modelo.</p>
<p>/lib/model/doctrine/UserTable.class.php</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #000000; font-weight: bold;">class</span> UserTable <span style="color: #000000; font-weight: bold;">extends</span> Doctrine_Table
<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> login<span style="color: #009900;">&#40;</span><span style="color: #000088;">$email</span><span style="color: #339933;">,</span><span style="color: #000088;">$password</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
      <span style="color: #b1b100;">return</span> Doctrine_Query<span style="color: #339933;">::</span><span style="color: #004000;">create</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span>
        <span style="color: #339933;">-&gt;</span><span style="color: #004000;">from</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'User u'</span><span style="color: #009900;">&#41;</span>
	<span style="color: #339933;">-&gt;</span><span style="color: #004000;">where</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'u.email = ?'</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$email</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span>
        <span style="color: #339933;">-&gt;</span><span style="color: #004000;">andWhere</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'u.password = ?'</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">md5</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$password</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span> <span style="color: #666666; font-style: italic;">// Podrimos usar otro algoritmo, en este caso utilizamos md5</span>
	<span style="color: #339933;">-&gt;</span><span style="color: #004000;">fetchOne</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>Y eso es todo, lo más sencillo para el final: la plantilla donde mostramos el formulario.</p>
<p>/apps/frontend/modules/user/templates/loginSuccess.php</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$sf_user</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getFlash</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;error&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">:</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>
    &lt;div class=&quot;error&quot;&gt;<span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$sf_user</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getFlash</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;error&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>&lt;/div&gt;
<span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #b1b100;">endif</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>
&lt;form action=&quot;<span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #b1b100;">echo</span> url_for<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;@user_login&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>&quot; method=&quot;post&quot;&gt;
  <span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$form</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>
  &lt;input type=&quot;submit&quot; value=&quot;Entrar&quot; /&gt;
&lt;/form&gt;</pre></td></tr></table></div>

<p>En este paso sería lógico desarrollar el logout para poder cerrar la sesión en la web. Para ello modificamos de nuevo la actions de nuestro módulo para añadir la nueva funcionalidad:</p>
<p>/apps/frontend/modules/user/actions/actions.class.php</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: #000000; font-weight: bold;">class</span> userActions <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> executeLogout<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;">-&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;">setAuthenticated</span><span style="color: #009900;">&#40;</span><span style="color: #009900; font-weight: bold;">false</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;">getAttributeHolder</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">clear</span><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;">-&gt;</span><span style="color: #004000;">redirect</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;@homepage&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Para ejecutar el logout, solo debemos crear un enlace en nuestra web donde se llame a esta action. No necesitamos plantilla ya que después de logout siempre redirigiremos a la homepage.</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #b1b100;">echo</span> link_to<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Cerrar sesión&quot;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'@user_logout'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span></pre></div></div>

<p>Debemos añadir las siguientes rutas en el archivo routing.yml:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">user_login:
  url:   /login
  param: { module: user, action: login }
&nbsp;
user_logout:
  url:   /logout
  param: { module: user, action: logout }</pre></div></div>

<p>Cualquier duda en los comentarios!</p>
]]></content:encoded>
			<wfw:commentRss>http://jonsegador.com/2011/03/formulario-de-login-y-logout-basico-en-symfony-1-4/feed/</wfw:commentRss>
		<slash:comments>11</slash:comments>
		</item>
		<item>
		<title>Formulario de registro básico en Symfony 1.4</title>
		<link>http://jonsegador.com/2011/03/formulario-de-registro-basico-en-symfony-1-4/</link>
		<comments>http://jonsegador.com/2011/03/formulario-de-registro-basico-en-symfony-1-4/#comments</comments>
		<pubDate>Tue, 01 Mar 2011 10:36:43 +0000</pubDate>
		<dc:creator>Jon</dc:creator>
				<category><![CDATA[Desarrollo]]></category>
		<category><![CDATA[Symfony]]></category>
		<category><![CDATA[formularios]]></category>
		<category><![CDATA[registro]]></category>

		<guid isPermaLink="false">http://jonsegador.com/?p=392</guid>
		<description><![CDATA[Es dificil no desarrollar una web sin tener registro de usuarios. Para Symfony 1.4 podemos encontrar gran cantidad de plugins que se encargan de esta función como pueden ser sfGuardPlugin (para Propel) y sfDoctrineGuardPlugin (para Doctrine). Estos plugins son muy completos y útiles, pudiéndolos usar en cualquiera de nuestros proyectos donde necesitemos las operaciones básicas [...]]]></description>
			<content:encoded><![CDATA[<p>Es dificil no desarrollar una web sin tener registro de usuarios. Para Symfony 1.4 podemos encontrar gran cantidad de plugins que se encargan de esta función como pueden ser <strong>sfGuardPlugin (para Propel)</strong> y <strong>sfDoctrineGuardPlugin (para Doctrine)</strong>. Estos plugins son muy completos y útiles, pudiéndolos usar en cualquiera de nuestros proyectos donde necesitemos las operaciones básicas con usuarios (registro, login, etc).</p>
<p>Para este post, la intención es <strong>crear un formulario de registro de usuarios sencillo desde cero para Symfony 1.4</strong>, sin la complejidad de un plugin ya que muchas veces tienen funcionalidades que no necesitaremos en nuestro proyecto.</p>
<p>Antes de empezar, evidentemente, crearemos un proyecto nuevo y generamos un modulo llamado &#8220;user&#8221;.</p>
<p>Primero <strong>modificamos el archivo schema.yml</strong>, añadiendo una tabla user básica y sencilla.</p>
<p>/config/doctrine/schema.yml</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="xml" style="font-family:monospace;">User:
  tableName: user
  actAs:
    Timestampable: ~
  columns:
    email:
      type: string(255)
    password:
      type: string(45)</pre></td></tr></table></div>

<p>Indicamos que se comporte como Timestampable para que se creen automáticamente los campos created_at y updated_at. No nos olvidemos generar las consultas sql y ejecutarlas en nuestra base de datos.</p>
<p>En el segundo paso, <strong>vamos a crear el formulario para el registro del usuario</strong>. Creamos un archivo nuevo en /lib/form/ llamado RegisterForm.class.php </p>
<p>/lib/form/RegisterForm.class.php</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #000000; font-weight: bold;">class</span> RegisterForm <span style="color: #000000; font-weight: bold;">extends</span> BaseForm
<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>
        parent<span style="color: #339933;">::</span><span style="color: #004000;">configure</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setWidgets</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
	    <span style="color: #0000ff;">'email'</span>     <span style="color: #339933;">=&gt;</span> <span style="color: #000000; font-weight: bold;">new</span> sfWidgetFormInput<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
	    <span style="color: #0000ff;">'password'</span>  <span style="color: #339933;">=&gt;</span> <span style="color: #000000; font-weight: bold;">new</span> sfWidgetFormInputPassword<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
            <span style="color: #0000ff;">'password2'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #000000; font-weight: bold;">new</span> sfWidgetFormInputPassword<span style="color: #009900;">&#40;</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;">-&gt;</span><span style="color: #004000;">setValidators</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
            <span style="color: #0000ff;">'email'</span>        <span style="color: #339933;">=&gt;</span> <span style="color: #000000; font-weight: bold;">new</span> sfValidatorEmail<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;">=&gt;</span>true<span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'required'</span><span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;El email es obligatorio&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
            <span style="color: #0000ff;">'password'</span>  <span style="color: #339933;">=&gt;</span> <span style="color: #000000; font-weight: bold;">new</span> sfValidatorString<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;">=&gt;</span>true<span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'required'</span><span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;La contraseña es obligatoria&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
            <span style="color: #0000ff;">'password2'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #000000; font-weight: bold;">new</span> sfValidatorString<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;">=&gt;</span>true<span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'required'</span><span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;La contraseña es obligatoria&quot;</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;">-&gt;</span><span style="color: #004000;">widgetSchema</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setNameFormat</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'register[%s]'</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;">widgetSchema</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setFormFormatterName</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'list'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
        <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">validatorSchema</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setPostValidator</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> sfValidatorAnd<span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
            <span style="color: #000000; font-weight: bold;">new</span> sfValidatorSchemaCompare<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'password2'</span><span style="color: #339933;">,</span> sfValidatorSchemaCompare<span style="color: #339933;">::</span><span style="color: #004000;">EQUAL</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'password'</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'throw_global_error'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'invalid'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;Las dos contraseñas no coinciden&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
            <span style="color: #000000; font-weight: bold;">new</span> sfValidatorDoctrineUnique<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;">=&gt;</span> <span style="color: #0000ff;">'User'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'column'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'email'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'invalid'</span><span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;Este email ya está en uso&quot;</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: #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>Los formularios pueden darnos muchos quebraderos de cabeza al principio ya que es algo dificil de entender a la primera, por lo que voy a explicarlo un poco más en detalle.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setWidgets</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
    <span style="color: #0000ff;">'email'</span>     <span style="color: #339933;">=&gt;</span> <span style="color: #000000; font-weight: bold;">new</span> sfWidgetFormInput<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
    <span style="color: #0000ff;">'password'</span>  <span style="color: #339933;">=&gt;</span> <span style="color: #000000; font-weight: bold;">new</span> sfWidgetFormInputPassword<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
    <span style="color: #0000ff;">'password2'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #000000; font-weight: bold;">new</span> sfWidgetFormInputPassword<span style="color: #009900;">&#40;</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></pre></td></tr></table></div>

<p>Indicamos que para el campo email queremos un input normal. Como se puede apreciar, le decimos que para los campos contraseña queremos un campo input password.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setValidators</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
    <span style="color: #0000ff;">'email'</span>        <span style="color: #339933;">=&gt;</span> <span style="color: #000000; font-weight: bold;">new</span> sfValidatorEmail<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;">=&gt;</span>true<span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'required'</span><span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;El email es obligatorio&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
    <span style="color: #0000ff;">'password'</span>  <span style="color: #339933;">=&gt;</span> <span style="color: #000000; font-weight: bold;">new</span> sfValidatorString<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;">=&gt;</span>true<span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'required'</span><span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;La contraseña es obligatoria&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
    <span style="color: #0000ff;">'password2'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #000000; font-weight: bold;">new</span> sfValidatorString<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;">=&gt;</span>true<span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'required'</span><span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;La contraseña es obligatoria&quot;</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></pre></td></tr></table></div>

<p><strong>Ahora los validadores</strong>. El campo email, evidentemente, debe ser un email. <strong>El validador sfValidatorEmail se encarga de comprobar que sea un formato de email válido</strong>.<br />
<strong>Los campos password son obligatorios y no pueden estar vacíos</strong>. Podríamos decirle que tienen que tener una longitud mínima y máxima con las opciones max_length y min_length.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td 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;">validatorSchema</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">setPostValidator</span><span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> sfValidatorAnd<span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span>
    <span style="color: #000000; font-weight: bold;">new</span> sfValidatorSchemaCompare<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'password2'</span><span style="color: #339933;">,</span> sfValidatorSchemaCompare<span style="color: #339933;">::</span><span style="color: #004000;">EQUAL</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'password'</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'throw_global_error'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #009900; font-weight: bold;">true</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'invalid'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;Las dos contraseñas no coinciden&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span>
    <span style="color: #000000; font-weight: bold;">new</span> sfValidatorDoctrineUnique<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;">=&gt;</span> <span style="color: #0000ff;">'User'</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">'column'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'email'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'invalid'</span><span style="color: #339933;">=&gt;</span> <span style="color: #0000ff;">&quot;Este email ya está en uso&quot;</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: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Vamos a añadir unos validadores un poco más complejos. En el primero, comprobamos que <strong>los dos campos de contraseña deben ser iguales</strong>. Para ello <strong>utilizamos el validador sfValidatorSchemaCompare</strong>. Es típico hacer esta comprobación en todos los formularios de registro de usuarios.<br />
En el segundo caso, comprobamos que <strong>el email introducido por el usuario no esté ya introducido en la base de datos</strong> y, por tanto, en uso por otro usuario. Utilizamos el validador <strong>sfValidatorDoctrineUnique</strong>.</p>
<p>Ya tenemos el formulario preparado para su uso. Editamos el archivo actions.class.php de nuestro módulo &#8220;user&#8221; y añadimos la acción &#8220;Register&#8221;:</p>
<p>/apps/frontend/modules/user/actions/actions.class.php</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
<span style="color: #000000; font-weight: bold;">class</span> userActions <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> executeRegister<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>
&nbsp;
    <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">redirectIf</span><span style="color: #009900;">&#40;</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;">isAuthenticated</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #0000ff;">&quot;@homepage&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">form</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> RegisterForm<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #b1b100;">if</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$request</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">isMethod</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;post&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
&nbsp;
       <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">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: #0000ff;">&quot;register&quot;</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;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">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>
&nbsp;
           <span style="color: #000088;">$user</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> User<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
           <span style="color: #000088;">$user</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">email</span> <span style="color: #339933;">=</span> <span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">form</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getValue</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;email&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
           <span style="color: #000088;">$user</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">password</span> <span style="color: #339933;">=</span> <span style="color: #990000;">md5</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$this</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">form</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getValue</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;password&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #666666; font-style: italic;">// podriamos utilizar otro sistema para encriptar la contraseña</span>
           <span style="color: #000088;">$user</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>
&nbsp;
           <span style="color: #000088;">$url</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;">getAttribute</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;referer&quot;</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><span style="color: #0000ff;">&quot;@homepage&quot;</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;">setAttribute</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;referer&quot;</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>
           <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: #000088;">$url</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
       <span style="color: #009900;">&#125;</span>
    <span style="color: #009900;">&#125;</span>
  <span style="color: #009900;">&#125;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>En la línea 7 le indicamos que si el usuario ya está logueado le redirija a la homepage.</p>
<p>Hemos utilizado el algoritmo md5 para encriptar la contraseña antes de guardarla en la base de datos. Podríamos utilizar otro algoritmo como sha1 o uno propio. <strong>Es totalmente recomendable encriptar las contraseñas y no guardarlas en texto plano en nuestra base de datos por motivos de seguridad.</strong></p>
<p>Por último, creamos la plantilla donde se mostrará el formulario de registro.</p>
<p>/apps/frontend/modules/user/templates/registerSuccess.php</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">&lt;form action=&quot;<span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #b1b100;">echo</span> url_for<span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;@user_register&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>&quot; method=&quot;post&quot;&gt;
  <span style="color: #000000; font-weight: bold;">&lt;?php</span> <span style="color: #b1b100;">echo</span> <span style="color: #000088;">$form</span><span style="color: #339933;">;</span> <span style="color: #000000; font-weight: bold;">?&gt;</span>
  &lt;input type=&quot;submit&quot; value=&quot;Registrarse&quot; /&gt;
&lt;/form&gt;</pre></td></tr></table></div>

<p>Debemos añadir la siguiente ruta en el archivo routing.yml:</p>

<div class="wp_syntax"><div class="code"><pre class="xml" style="font-family:monospace;">user_register:
  url:   /register
  param: { module: user, action: register }</pre></div></div>

<p>Y eso es todo, ya hemos creado un <strong>sistema muy básico de registro de usuarios en Symfony 1.4</strong>. A partir de aquí se puede expandir e incluir las funcionalidades que queramos.<br />
<a href="http://jonsegador.com/2011/03/formulario-de-login-y-logout-basico-en-symfony-1-4/"><strong>En un próximo post, realizaremos el login y el logout.</strong></a></p>
<p>Cualquier duda o si hay que explicar algo mejor, en los comentarios <img src='http://jonsegador.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
]]></content:encoded>
			<wfw:commentRss>http://jonsegador.com/2011/03/formulario-de-registro-basico-en-symfony-1-4/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>Transacciones MySQL con Doctrine y Symfony</title>
		<link>http://jonsegador.com/2010/11/transacciones-mysql-con-doctrine-y-symfony/</link>
		<comments>http://jonsegador.com/2010/11/transacciones-mysql-con-doctrine-y-symfony/#comments</comments>
		<pubDate>Mon, 22 Nov 2010 09:19:01 +0000</pubDate>
		<dc:creator>Jon</dc:creator>
				<category><![CDATA[Bases de datos]]></category>
		<category><![CDATA[Desarrollo]]></category>
		<category><![CDATA[Seguridad]]></category>
		<category><![CDATA[Symfony]]></category>
		<category><![CDATA[doctrine]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[transacción]]></category>
		<category><![CDATA[transacciones]]></category>

		<guid isPermaLink="false">http://jonsegador.com/?p=320</guid>
		<description><![CDATA[Lo primero de todo, ¿qué es una transacción MySQL? Una transacción en MySQL es la combinación de una o más consultas SQL que juntas forman una unidad de trabajo. El ejemplo clásico es el movimiento de dinero en un banco entre dos cuentas bancarias. Si la persona A quiere hacer una transferencia bancaria a la [...]]]></description>
			<content:encoded><![CDATA[<p>Lo primero de todo, <strong>¿qué es una transacción MySQL?</strong> Una transacción en MySQL es la combinación de una o más consultas SQL que juntas forman una unidad de trabajo. El ejemplo clásico es el movimiento de dinero en un banco entre dos cuentas bancarias. Si la persona A quiere hacer una transferencia bancaria a la persona B, habrá dos consultas: 1) la que descuenta el dinero a la persona A y 2) la que aumenta el saldo de la persona B. Si falla la consulta 2, tenemos un problema: Le habremos descontado el dinero a la persona A pero la persona B nunca recibirá su dinero.</p>
<p>En casos como estos es necesario tomar estas dos consultas como un todo y si falla una de las dos operaciones, volver atrás y deshacer la operación. Para ello se utilizan las transacciones.</p>
<p>En este ejemplo vamos a ver como realizar transacciones con el <a href="http://www.doctrine-project.org/"><strong>ORM Doctrine</strong></a> y <a href="http://www.symfony-project.org/"><strong>Symfony</strong></a> (no necesariamente debemos utilizar Symfony).</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000088;">$conn</span> <span style="color: #339933;">=</span> Doctrine_Manager<span style="color: #339933;">::</span><span style="color: #004000;">getInstance</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">getCurrentConnection</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
<span style="color: #000088;">$conn</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">beginTransaction</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
try<span style="color: #009900;">&#123;</span>
&nbsp;
    <span style="color: #009933; font-style: italic;">/** Hacemos las operaciones necesarias
      * para realizar la transferencia bancaria */</span>
&nbsp;
    <span style="color: #000088;">$userA</span> <span style="color: #339933;">=</span> UserTable<span style="color: #339933;">::</span><span style="color: #004000;">getById</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$userA_id</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    <span style="color: #000088;">$userB</span> <span style="color: #339933;">=</span> UserTable<span style="color: #339933;">::</span><span style="color: #004000;">getById</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$userB_id</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
    <span style="color: #000088;">$userA</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">money</span> <span style="color: #339933;">-=</span> <span style="color: #cc66cc;">20</span><span style="color: #339933;">;</span>
    <span style="color: #000088;">$userA</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>
&nbsp;
    <span style="color: #000088;">$userB</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">money</span> <span style="color: #339933;">+=</span> <span style="color: #cc66cc;">20</span><span style="color: #339933;">;</span>
    <span style="color: #000088;">$userB</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>
&nbsp;
    <span style="color: #000088;">$conn</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">commit</span><span style="color: #009900;">&#40;</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>Exception <span style="color: #000088;">$e</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#123;</span>
    <span style="color: #000088;">$conn</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">rollBack</span><span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
    throw <span style="color: #000088;">$e</span><span style="color: #339933;">;</span>
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>Si las dos operaciones se realizan con éxito, quedará reflejado en la base de datos. Si por el contrario cualquiera de las dos consultas fallará, se desharán los cambios (rollBack) y no se guardarán en la base de datos (mostramos el error y deberemos tratarlo según nuestros intereses).</p>
]]></content:encoded>
			<wfw:commentRss>http://jonsegador.com/2010/11/transacciones-mysql-con-doctrine-y-symfony/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Instalar NetBeans con soporte svn+ssh y theme de colores oscuros</title>
		<link>http://jonsegador.com/2010/10/instalar-netbeans-con-soporte-svnssh-y-theme-de-colores-oscuros/</link>
		<comments>http://jonsegador.com/2010/10/instalar-netbeans-con-soporte-svnssh-y-theme-de-colores-oscuros/#comments</comments>
		<pubDate>Sat, 09 Oct 2010 11:19:55 +0000</pubDate>
		<dc:creator>Jon</dc:creator>
				<category><![CDATA[Desarrollo]]></category>
		<category><![CDATA[Symfony]]></category>
		<category><![CDATA[aptana]]></category>
		<category><![CDATA[ide]]></category>
		<category><![CDATA[netbeans]]></category>
		<category><![CDATA[rsa]]></category>
		<category><![CDATA[ssh]]></category>
		<category><![CDATA[ssh-keygen]]></category>
		<category><![CDATA[svn]]></category>
		<category><![CDATA[theme]]></category>

		<guid isPermaLink="false">http://jonsegador.com/?p=260</guid>
		<description><![CDATA[De entre todos los IDEs que existen, mis favoritos para programar en php son Aptana y NetBeans. Hasta ahora siempre he usado Aptana, su edición directa por FTP y su sistema de sincronización lo hacía casi indispensable. Pero NetBeans tiene una ventaja bastante importante y determinante (al menos para mí): soporte para el framework Symfony [...]]]></description>
			<content:encoded><![CDATA[<p>De entre todos los IDEs que existen, mis favoritos para programar en php son <a href="http://www.aptana.com/">Aptana</a> y <a href="http://netbeans.org/">NetBeans</a>. Hasta ahora siempre he usado Aptana, su edición directa por FTP y su sistema de sincronización lo hacía casi indispensable. Pero NetBeans tiene una ventaja bastante importante y determinante (al menos para mí): soporte para el framework Symfony (y Zend).</p>
<p>Voy a explicar como instalar NetBeans en Ubuntu y empezar un proyecto utilizando svn+ssh.</p>
<p><strong>1) Descargar e instalar NetBeans.</strong><br />
Lo haremos desde su página web oficial: http://netbeans.org/ La última versión a la hora de escribir este post, es la 6.9.1.<br />
Descargaremos la versión PHP. Podemos elegir el idioma del IDE, aunque recomiendo descargarlo en inglés. No es lo mismo hacer un &#8220;checkout&#8221; o &#8220;commit&#8221;, que un &#8220;comprobar&#8221; o &#8220;subir cambios&#8221;. Personalmente, me lío <img src='http://jonsegador.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p>Una vez descargado el instalador, tenemos que darle permisos de ejecución. Pinchamos con el botón derecho / propiedades / permisos / permitir ejecutar el archivo como un programa. Cerramos y hacemos doble click en el archivo y seleccionamos Ejecutar. La instalación empezará en este momento.</p>
<p><strong>2) Soporte svn+ssh</strong><br />
NetBeans ya tiene instalado el plugin de svn. Lo que vamos a hacer es importar un proyecto que tengamos en nuestro servidor de svn, conectándonos mediante svn+ssh. Para ello necesitamos primero crear un par de claves RSA para que podamos conectarnos mediante ssh al servidor svn sin necesidad de tener que introducir la contraseña cada vez.</p>
<p>En local, utilizamos el comando ssh-keygen:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">ssh-keygen</span> <span style="color: #660033;">-t</span> rsa</pre></div></div>

<p>Nos da la opción de introducir una frase para cifrar la clave privada. Cifrar la clave privada nos dará más seguridad en caso de intento de robo de esta clave, pero en este caso no lo vamos a hacer ya que el objetivo es no tener que escribir la contraseña cada vez que nos queramos conectar al servidor (si ciframos la clave privada, habrá que introducir la frase para descifrarla).</p>
<p>Este comano nos crea dos archivos: id_rsa (clave privada) e id_rsa.pub (clave pública). Tenemos que copiar la clave pública al servidor svn.</p>
<p>Podemos copiar el archivo id_rsa.pub mediante ftp o utilizando el comando scp:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">scp</span> id_rsa.pub usuario<span style="color: #000000; font-weight: bold;">@</span>dominio:<span style="color: #000000; font-weight: bold;">/</span>home<span style="color: #000000; font-weight: bold;">/</span>usuario</pre></div></div>

<p>Cuando tengamos la clave pública en el servidor, tenemos que añadirla al fichero authorized_keys que esta en el directorio .ssh de nuestra home. Si no existe el directorio, lo creamos:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">mkdir</span> <span style="color: #007800;">$HOME</span><span style="color: #000000; font-weight: bold;">/</span>.ssh</pre></div></div>

<p>Dentro de este directorio, tenemos que incluir la clave pública en el fichero authorized_keys:</p>

<div class="wp_syntax"><div class="code"><pre class="php" style="font-family:monospace;">cat id_rsa<span style="color: #339933;">.</span>pub <span style="color: #339933;">&gt;&gt;</span> authorized_keys</pre></div></div>

<p>Después de esto, ya no necesitaremos introducir nuestra contraseña cada vez que queramos conectarnos al servidor (desde nuestro ordenador local, claro).</p>
<p><strong>3) Importar proyecto svn</strong><br />
Ya estamos preparados para importar un proyecto svn a NetBeans utilizando svn+ssh.<br />
En Netbeans, vamos al menú Team>Subversion>Checkout. Se nos abrirá una ventana en la que tenemos que introducir la URL del repositorio (Repository URL) y el túnel SSH (Tunnel Command).<br />
En el primer campo escribimos la ruta a nuestro repositorio, por ejemplo:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">svn</span>+<span style="color: #c20cb9; font-weight: bold;">ssh</span>:<span style="color: #000000; font-weight: bold;">//</span>midominio.com<span style="color: #000000; font-weight: bold;">/</span>miproyecto</pre></div></div>

<p>Y en Tunnel Command, introducimos:</p>

<div class="wp_syntax"><div class="code"><pre class="bash" style="font-family:monospace;"><span style="color: #c20cb9; font-weight: bold;">ssh</span> <span style="color: #660033;">-q</span> <span style="color: #660033;">-l</span> USUARIO <span style="color: #660033;">-i</span> <span style="color: #000000; font-weight: bold;">/</span>home<span style="color: #000000; font-weight: bold;">/</span>USUARIO<span style="color: #000000; font-weight: bold;">/</span>.ssh<span style="color: #000000; font-weight: bold;">/</span>id_rsa</pre></div></div>

<p>Vemos como en el comando anterior hacemos uso del archivo de clave privada id_rsa, así no tendremos que escribir la contraseña cada vez.</p>
<p>La siguiente ventana esta dividida en dos partes. En la de arriba seleccionaremos la parte del repositorio que queremos importar (checkout). Por defecto nos descargaremos todo (podemos seleccionar la rama Trunk si la hubiera). En parte de abajo de la ventana, seleccionamos donde queremos descargar el proyecto en local.</p>
<p>En el siguiente paso nos preguntará si queremos crear un proyecto en local. Le decimos que sí. Creamos un PHP Application (la primera opción). Lo ideal es que el directorio del proyecto que estamos creando sea el mismo que el de sincronización con svn. Así, trabajamos y hacemos cambios en los archivos descargados de svn directamente, por lo que es más fácil después subir los cambios al servidor. Recomiendo separar los metadata del proyecto Netbeans a otra carpeta, para que no se añadan al proyecto y se suban la próxima vez al servidor svn (aunque se podría hacer un ignore).</p>
<p>Como vemos en la captura, el proyecto desde svn lo descargo en trunk, mientras que los metadata del proyecto (archivos de configuración de NetBeans) lo dejo en la carpeta MiProyecto:</p>
<p><a href="http://jonsegador.com/wp-content/uploads/netbeans.png"><img src="http://jonsegador.com/wp-content/uploads/netbeans-300x185.png" alt="netbeans" title="netbeans" width="300" height="185" class="aligncenter size-medium wp-image-262" /></a></p>
<p>Y ya lo tendremos! Podemos activar la barra de svn para hacernos el trabajo más sencillo (Window / Versioning / Subversion) a la hora de subir los cambios al servidor.</p>
<p><strong>4) Theme con colores oscuros</strong><br />
Si pasamos la mayor parte del día programando, es mejor para la vista tener colores oscuros de fondo. El color blanco (por defecto en la mayoría de IDEs) cansa mucho la vista y a la larga puede ser perjudicial para los ojos. Así que vamos a instalar un theme con colores oscuros.</p>
<p>El mejor que he encontrado es este: <a href="http://net.tutsplus.com/freebies/themes/netbeans-twilight-theme/">http://net.tutsplus.com/freebies/themes/netbeans-twilight-theme/</a> y lo podemos descargar desde <a href="http://d2o0t5hpnwv4c1.cloudfront.net/338_netbeansFreebie/Netbeans_Twilight_Theme.zip">aquí</a> o <a href="http://jonsegador.com/wp-content/uploads/Netbeans_Twilight_Theme.zip">aquí</a> (mirror en mi servidor).</p>
<p>Para importarlo en NetBeans, vamos a Tools / Options y pulsamos en el botón Import. Buscamos el archivo .zip (importante, no hay que descomprimirlo!), seleccionamos que queremos importar todas las opciones y pulsamos en aceptar. Después de reiniciar NetBeans, vamos a Tools / Options y en la pestaña Fonts and Colors seleccionamos el Profile Netbeans_Twilight. Ya tendremos nuestro entorno con colores oscuros.</p>
<p>Para mi gusto, el tamaño de letra de este theme es demasiado pequeño. Yo, en Fonts and Colors (una vez activado el theme) selecciono el tipo de fuente &#8220;Monospaced&#8221;, estilo &#8220;Plain&#8221; y tamaño &#8220;13&#8243;.</p>
<p>Con estos pasos tenemos nuestro entorno de desarrollo listo para empezar.</p>
]]></content:encoded>
			<wfw:commentRss>http://jonsegador.com/2010/10/instalar-netbeans-con-soporte-svnssh-y-theme-de-colores-oscuros/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Logs manuales y personalizados en Symfony</title>
		<link>http://jonsegador.com/2010/07/logs-manuales-personalizados-en-symfony/</link>
		<comments>http://jonsegador.com/2010/07/logs-manuales-personalizados-en-symfony/#comments</comments>
		<pubDate>Wed, 07 Jul 2010 07:17:39 +0000</pubDate>
		<dc:creator>Jon</dc:creator>
				<category><![CDATA[Desarrollo]]></category>
		<category><![CDATA[Symfony]]></category>
		<category><![CDATA[logs]]></category>

		<guid isPermaLink="false">http://jonsegador.com/?p=247</guid>
		<description><![CDATA[Suele ser una buena práctica tener un archivo de logs con las últimas acciones más importantes que se han hecho en nuestro sitio web: nuevo usuario registrado, se ha escrito un nuevo comentario, se ha editado o borrado un artículo, etc. Symfony tiene un sistema de logs bastante decente, que nos informa de todo lo [...]]]></description>
			<content:encoded><![CDATA[<p>Suele ser una buena práctica tener un archivo de logs con las últimas acciones más importantes que se han hecho en nuestro sitio web: nuevo usuario registrado, se ha escrito un nuevo comentario, se ha editado o borrado un artículo, etc.</p>
<p>Symfony tiene un sistema de logs bastante decente, que nos informa de todo lo que ocurre cada vez que cargamos una nueva página. Vamos a hacer algo sencillo: <strong>vamos a escribir nuestros propios mensajes de log personalizados y los escribiremos manualmente</strong> en el momento que consideremos oportuno y deseamos tener un control. Además, <strong>escribiremos estos logs en un archivo aparte</strong> del que utiliza Symfony por defecto. Así podremos leer directamente ese archivo sin tener otros logs mezclados con los que realmente nos interesa.</p>
<p>Primero, vamos a crear un nuevo archivo llamado CustomLog.class.php en la carpeta /lib/:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #000000; font-weight: bold;">&lt;?php</span>
&nbsp;
<span style="color: #000000; font-weight: bold;">class</span> CustomLog<span style="color: #009900;">&#123;</span>
  static <span style="color: #000000; font-weight: bold;">public</span> <span style="color: #000000; font-weight: bold;">function</span> newLog<span style="color: #009900;">&#40;</span><span style="color: #000088;">$message</span><span style="color: #009900;">&#41;</span> <span style="color: #009900;">&#123;</span>
&nbsp;
        <span style="color: #000088;">$logFile</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;">'sf_log_dir'</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">.</span><span style="color: #0000ff;">'/custom_logs.log'</span><span style="color: #339933;">;</span>
        <span style="color: #000088;">$custom_log</span> <span style="color: #339933;">=</span> <span style="color: #000000; font-weight: bold;">new</span> sfFileLogger<span style="color: #009900;">&#40;</span><span style="color: #000000; font-weight: bold;">new</span> sfEventDispatcher<span style="color: #009900;">&#40;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">,</span> <span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'file'</span> <span style="color: #339933;">=&gt;</span> <span style="color: #000088;">$logFile</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
        <span style="color: #000088;">$custom_log</span><span style="color: #339933;">-&gt;</span><span style="color: #004000;">info</span><span style="color: #009900;">&#40;</span><span style="color: #000088;">$message</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span>
&nbsp;
  <span style="color: #009900;">&#125;</span>  
<span style="color: #009900;">&#125;</span></pre></td></tr></table></div>

<p>El archivo donde guardaremos nuestros logs personalizados, lo encontraremos en &#8220;/log/custom_logs.log&#8221;.</p>
<p>Para escribir un nuevo log desde cualquier parte del código, simplemente deberemos hacer:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">CustomLog<span style="color: #339933;">::</span><span style="color: #004000;">newLog</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">&quot;Escribimos un nuevo log&quot;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p>Si abrimos nuestro archivo de logs personalizados, encontraremos algo como esto:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">Jul <span style="color: #208080;">05</span> <span style="color: #cc66cc;">22</span><span style="color: #339933;">:</span><span style="color: #cc66cc;">31</span><span style="color: #339933;">:</span><span style="color: #cc66cc;">41</span> symfony <span style="color: #009900;">&#91;</span>info<span style="color: #009900;">&#93;</span> Escribimos un nuevo <span style="color: #990000;">log</span></pre></td></tr></table></div>

<p>Así podremos llevar un control de lo que ocurre en nuestra web.</p>
<p>Quizás haya una forma mejor de hacerlo. Si es así, no dudes en dejar tu propuesta en los comentarios. A lo mejor también sería conveniente escribir esas 3 lineas dentro de un try.. catch, por lo que pudiera pasar.</p>
]]></content:encoded>
			<wfw:commentRss>http://jonsegador.com/2010/07/logs-manuales-personalizados-en-symfony/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Symfony: Migrar de Propel a Doctrine</title>
		<link>http://jonsegador.com/2010/06/symfony-migrar-de-propel-a-doctrine/</link>
		<comments>http://jonsegador.com/2010/06/symfony-migrar-de-propel-a-doctrine/#comments</comments>
		<pubDate>Fri, 18 Jun 2010 23:10:43 +0000</pubDate>
		<dc:creator>Jon</dc:creator>
				<category><![CDATA[Desarrollo]]></category>
		<category><![CDATA[Symfony]]></category>

		<guid isPermaLink="false">http://jonsegador.com/?p=208</guid>
		<description><![CDATA[Desde que empecé con Symfony siempre he preferido utilizar Propel como ORM de mis proyectos. Me sentía cómodo utilizándolo excepto en esas ocasiones en las que se complicaba demasiado la consulta y había que tirar de &#8216;criteriones&#8217; (al final optaba por construir la sql a mano). Había leído sobre Doctrine pero nunca me había parado [...]]]></description>
			<content:encoded><![CDATA[<p>Desde que empecé con Symfony siempre he preferido utilizar Propel como ORM de mis proyectos. Me sentía cómodo utilizándolo excepto en esas ocasiones en las que se complicaba demasiado la consulta y había que tirar de <em>&#8216;criteriones&#8217;</em> (al final optaba por construir la sql a mano). Había leído sobre Doctrine pero nunca me había parado a probarlo y utilizarlo ya que, como digo, me sentía muy cómodo con Propel y ni siquiera me planteaba cambiar.</p>
<p>En la nueva empresa donde trabajo (<a href="http://blackslot.com/">BlackSlot</a>) he empezado a utilizar Doctrine y, ante mi sorpresa, me ha encantado. Me he dado cuenta de que si sabes sql es muy fácil aprender Doctrine y con resultados muy buenos. Con Propel, aunque sepas sql, tienes que aprender a usarlo y pensar las conversiones desde sql a Propel. Es un lenguaje nuevo.</p>
<p>Ante este escenario y como tengo un proyecto recién empezado, me decidí a migrarlo de Propel a Doctrine.</p>
<p>Tengo que destacar que <strong>la migración es realmente costosa</strong>. Si no fuese por que acabo de empezar el proyecto y no está muy avanzado, hubiese tenido que seguir con Propel. Personalmente, lo que más cuesta es transformar todo el modelo a Doctrine (todo depende de cuanto lleves hecho). Si es un proyecto acabado y bastante elaborado, te puede llevar días. Al modelo hay que añadir el modificar el schema.yml con el formato apropiado para Doctrine.</p>
<p><strong>Otro quebradero de cabeza son los plugins</strong> en Propel que has utilizado en tu proyecto. El más típico es el sfGuardPlugin para llevar las cuentas de usuario. Tendrás que instalar el plugin sfDoctrineGuardPlugin que es el equivalente para Doctrine.</p>
<p>Si aún después de haber leído esto, sigues queriendo migrar de Propel a Doctrine un proyecto empezado, estos son los pasos que tienes que seguir:</p>
<p><strong>¡No te olvides de hacer un backup de todo primero!</strong></p>
<p><strong>1)</strong> Editamos el fichero config/ProjectConfiguration.class.php y añadimos esta línea con la que cargamos todos los plugins excepto el de Propel.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td 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;">enableAllPluginsExcept</span><span style="color: #009900;">&#40;</span><span style="color: #990000;">array</span><span style="color: #009900;">&#40;</span><span style="color: #0000ff;">'sfPropelPlugin'</span><span style="color: #009900;">&#41;</span><span style="color: #009900;">&#41;</span><span style="color: #339933;">;</span></pre></td></tr></table></div>

<p><strong>2)</strong> Borrar directorio plugins/sfGuardPlugin si es que lo tenemos instalado.</p>
<p><strong>3)</strong> Borramos el actual schema de base de datos config/databases.yml<br />
y reconfiguramos el proyecto para utilizarlo con Doctrine</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">php symfony configure<span style="color: #339933;">:</span>database <span style="color: #339933;">--</span>name<span style="color: #339933;">=</span>doctrine <span style="color: #339933;">--</span><span style="color: #000000; font-weight: bold;">class</span><span style="color: #339933;">=</span>sfDoctrineDatabase <span style="color: #0000ff;">&quot;mysql:host=localhost;dbname=nombre_base_de_datos&quot;</span> usuario contraseña</pre></td></tr></table></div>

<p><strong>4)</strong> Ejecutamos:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">php symfony plugin<span style="color: #339933;">:</span>publish<span style="color: #339933;">-</span>assets</pre></td></tr></table></div>

<p>para crear un enlace a sfDoctrinePlugin en el directorio web.</p>
<p><strong>5)</strong> Borramos unos ficheros propios de Propel</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">rm web<span style="color: #339933;">/</span>sfPropelPlugin
rm config<span style="color: #339933;">/</span>propel<span style="color: #339933;">.</span>ini</pre></td></tr></table></div>

<p><strong>6)</strong> Como es un proyecto empezado, supongo que tienes una base de datos ya creada.</p>
<p>Creamos el directorio donde alojamos el schema.yml para Doctrine:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;"><span style="color: #990000;">mkdir</span> config<span style="color: #339933;">/</span>doctrine</pre></td></tr></table></div>

<p>Y con el siguiente comando, recreamos el schema a partir de la base de datos existente:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">php symfony doctrine<span style="color: #339933;">:</span>build<span style="color: #339933;">-</span>schema</pre></td></tr></table></div>

<p>No te olvides revisarlo, sobre todo las relaciones entre tablas.</p>
<p><strong>7)</strong>  Borramos el modelo anterior</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">rm <span style="color: #339933;">-</span>rf lib<span style="color: #339933;">/</span>model<span style="color: #666666; font-style: italic;">/*</span></pre></td></tr></table></div>

<p>Y lo volvemos a generar a partir del nuevo archivo schema.yml</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="php" style="font-family:monospace;">symfony doctrine<span style="color: #339933;">:</span>build<span style="color: #339933;">-</span>model
symfony doctrine<span style="color: #339933;">:</span>build<span style="color: #339933;">-</span>forms
symfony doctrine<span style="color: #339933;">:</span>build<span style="color: #339933;">-</span>filters</pre></td></tr></table></div>

<p>A partir de aquí viene el trabajo duro: reescribir el modelo que teníamos en Propel y adaptarlo a Doctrine en las clases adecuadas del modelo.</p>
<p>También deberás instalar el plugin sfDoctrineGuardPlugin si lo estimas necesario (<a href="http://www.symfony-project.org/plugins/sfDoctrineGuardPlugin">http://www.symfony-project.org/plugins/sfDoctrineGuardPlugin</a>)</p>
<p>Espero que le pueda servir a alguien.</p>
]]></content:encoded>
			<wfw:commentRss>http://jonsegador.com/2010/06/symfony-migrar-de-propel-a-doctrine/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

