<?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>devexp &#187; Van de Voorde Toni</title>
	<atom:link href="http://www.devexp.eu/author/admin/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.devexp.eu</link>
	<description>DEVelopment EXPerience, shared with the world!</description>
	<lastBuildDate>Fri, 28 Oct 2011 12:07:45 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.3.1</generator>
		<item>
		<title>How to use a symfony 1 layout from a different directory</title>
		<link>http://www.devexp.eu/2011/10/28/how-to-use-a-symfony-1-layout-from-a-different-directory/</link>
		<comments>http://www.devexp.eu/2011/10/28/how-to-use-a-symfony-1-layout-from-a-different-directory/#comments</comments>
		<pubDate>Fri, 28 Oct 2011 11:48:36 +0000</pubDate>
		<dc:creator>Van de Voorde Toni</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[Layout]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Tips and Tricks]]></category>
		<category><![CDATA[plugin]]></category>
		<category><![CDATA[Symfony]]></category>

		<guid isPermaLink="false">http://www.devexp.eu/?p=1042</guid>
		<description><![CDATA[In symfony 1 it is possible to have different layouts for an application. But they all have to be put into the directory &#8216;myproject/apps/frontend/templates/&#8217;. But what if you want to use a layout from another location? Assume you make a &#8230; <a href="http://www.devexp.eu/2011/10/28/how-to-use-a-symfony-1-layout-from-a-different-directory/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p><a href="http://www.devexp.eu/wp-content/uploads/2009/04/symfony.jpg"><img src="http://www.devexp.eu/wp-content/uploads/2009/04/symfony.jpg" alt="" title="Symfony" width="127" height="35" class="alignright size-full wp-image-727" /></a>In symfony 1 it is possible to have different layouts for an application. But they all have to be put into the directory &#8216;myproject/apps/frontend/templates/&#8217;. But what if you want to use a layout from another location? </p>
<p>Assume you make a plugin with a specific layout, it would be nice to load the layout from the plugin directory, and not to have to copy the file to the global directory.</p>
<p>Here is how you can achieve this:</p>
<pre class="brush: php; title: ; notranslate">
$template = $this-&gt;getContext()-&gt;getConfiguration()-&gt;getTemplateDir('MODULE', 'LAYOUT_FILE.php');
$this-&gt;setLayout($template . '/LAYOUT_FILE');
</pre>
<p>Let&#8217;s say you have the following:</p>
<pre class="brush: plain; title: ; notranslate">
my_project/
  plugins/
    my_plugin/
      modules/
        MyUser/
          actions/
            actions.php
          templates/
            indexSuccess.php
            MyUserLayout.php
</pre>
<p>The actions.php class could be something like this:</p>
<pre class="brush: php; title: ; notranslate">
class MyUserAction extends sfActions {

  public function preExecute() {
    $template = $this-&gt;getContext()-&gt;getConfiguration()-&gt;getTemplateDir('MyUser', 'MyUserLayout.php');

    $this-&gt;setLayout($template . '/MyUserLayout');
  }

  public function executeIndex() {

  }
}
</pre>
<p>Have fun!</p>
<div class="shr-publisher-1042"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://www.devexp.eu/2011/10/28/how-to-use-a-symfony-1-layout-from-a-different-directory/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>How to force symfony colors on windows with PuttyCyg?</title>
		<link>http://www.devexp.eu/2009/09/22/how-to-force-symfony-colors-on-windows-with-cygwinputtycyg/</link>
		<comments>http://www.devexp.eu/2009/09/22/how-to-force-symfony-colors-on-windows-with-cygwinputtycyg/#comments</comments>
		<pubDate>Tue, 22 Sep 2009 13:18:14 +0000</pubDate>
		<dc:creator>Van de Voorde Toni</dc:creator>
				<category><![CDATA[Framework]]></category>
		<category><![CDATA[General]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Symfony]]></category>
		<category><![CDATA[framework]]></category>
		<category><![CDATA[tips]]></category>

		<guid isPermaLink="false">http://www.devexp.eu/?p=936</guid>
		<description><![CDATA[Those of you who’re developing with symfony under windows will have noticed that, when running tasks in the command prompt, no colors are used. This is because the windows command prompt isn’t compatible with the color notation. Most of you &#8230; <a href="http://www.devexp.eu/2009/09/22/how-to-force-symfony-colors-on-windows-with-cygwinputtycyg/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>Those of you who’re developing with symfony under windows will have noticed that, when running tasks in the command prompt, no colors are used. This is because the windows command prompt isn’t compatible with the color notation.<br />
Most of you also have <a href="http://www.cygwin.com/">cygwin</a> installed (shame on you if you didn’t :p). But even if you run the tasks through “<a href="http://code.google.com/p/puttycyg/">PuttyCyg</a>”, which is fully compatible with the color notation, you will not benefit from the colors. </p>
<p>Why?</p>
<p><span id="more-936"></span><br />
The problem resides in the symfony class “sfAnsiColorFormatter” in the method “supportsColors($stream)”:</p>
<pre class="brush: php; title: ; notranslate">
  /**
   * Returns true if the stream supports colorization.
   *
   * Colorization is disabled if not supported by the stream:
   *
   *  -  windows
   *  -  non tty consoles
   *
   * @param mixed $stream A stream
   *
   * @return Boolean true if the stream supports colorization, false otherwise
   */
  public function supportsColors($stream)
  {
    return DIRECTORY_SEPARATOR != '\\' &amp;&amp; function_exists('posix_isatty') &amp;&amp; @posix_isatty($stream);
  }
</pre>
<p>The method supportsColors($stream) decides whether or not colors are supported. And as you can see, one of the checks is the directory separator which in our case will always return false because we are on a windows operating system. So even if you run tasks through puttycyg the directory separator will remain the same.</p>
<p><strong>Possibility 1</strong></p>
<p>If you always work through the puttycyg you could simply set the method to always return true, but in a command prompt it will look like this:<br />
<div id="attachment_946" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.devexp.eu/wp-content/uploads/2009/09/command_output.png"><img src="http://www.devexp.eu/wp-content/uploads/2009/09/command_output-300x236.png" alt="Dos Command Output" title="Dos Command Output" width="300" height="236" class="size-medium wp-image-946" /></a><p class="wp-caption-text">Dos Command Output</p></div></p>
<p><strong>Possibility 2</strong></p>
<p>Detect if cygwin is used. This way when you use the dos command the output will work and when cygwin is used you&#8217;ll have the colors <img src='http://www.devexp.eu/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
<p>I checked the $_SERVER array to find something that could help me to distinguish the cygwin prompt with the dos prompt, and I found that the &#8216;PWD&#8217; key is only available on *nix shells. And when I print the value of $_SERVER['PWD'] in the cygwin prompt it gives me &#8220;/cygdrive/f/sandbox/adlogix/branch-3.2/frontend&#8221;. </p>
<p>Knowing that, here is how we can change the supportsColors method:</p>
<pre class="brush: php; title: ; notranslate">
  /**
   * Returns true if the stream supports colorization.
   *
   * Colorization is disabled if not supported by the stream:
   *
   *  -  windows
   *  -  non tty consoles
   *
   * @param mixed $stream A stream
   *
   * @return Boolean true if the stream supports colorization, false otherwise
   */
  public function supportsColors($stream)
  {
    $supported = DIRECTORY_SEPARATOR != '\\' &amp;&amp; function_exists('posix_isatty') &amp;&amp; @posix_isatty($stream);

    return $supported ? true : !is_bool(strpos(@$_SERVER['PWD'], &quot;/cygdrive&quot;));
  }
</pre>
<p>What I did, is still using the check symfony used, but when it returns false I do a second check to see if the $_SERVER['PWD'] exists and that it contains the String &#8220;/cygdrive&#8221;.</p>
<p>Now when I run the taks through cygwin I get the colors and when I run it in dos it displays correctly.<br />
<div id="attachment_950" class="wp-caption aligncenter" style="width: 310px"><a href="http://www.devexp.eu/wp-content/uploads/2009/09/puttycyg-versus-dos.png"><img src="http://www.devexp.eu/wp-content/uploads/2009/09/puttycyg-versus-dos-300x187.png" alt="PuttyCyg versus Dos" title="PuttyCyg versus Dos" width="300" height="187" class="size-medium wp-image-950" /></a><p class="wp-caption-text">PuttyCyg versus Dos</p></div></p>
<p>I only tested it on my machine, so if you have troubles or a better way to do it, please let me know <img src='http://www.devexp.eu/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
<p><strong>Update:</strong> This is only tested with symfony 1.2 and as from sf 1.3 there will be an option &#8211;color to force the colors.</p>
<p><strong>Update:</strong> For some reason it does not work in the cygwin bash shell. When I set the message manually (echo -e &#8220;\033[31mHello World\033[0m&#8221;) in the command the colors appear, but through symfony not.  I suspect that the cygwin bash shell miss interprets the returns of php, but I have no idea why it does work on puttyCyg (which only launches the cygwin shell) &#8230; probably some startup configuration of the bash ?!</p>
<div class="shr-publisher-936"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://www.devexp.eu/2009/09/22/how-to-force-symfony-colors-on-windows-with-cygwinputtycyg/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>Tech Support Cheat Sheet</title>
		<link>http://www.devexp.eu/2009/08/27/tech-support-cheat-sheet/</link>
		<comments>http://www.devexp.eu/2009/08/27/tech-support-cheat-sheet/#comments</comments>
		<pubDate>Thu, 27 Aug 2009 08:13:24 +0000</pubDate>
		<dc:creator>Van de Voorde Toni</dc:creator>
				<category><![CDATA[General]]></category>

		<guid isPermaLink="false">http://www.devexp.eu/?p=884</guid>
		<description><![CDATA[Oh so true &#8230; From xkcd]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>Oh so true &#8230;</p>
<p><a href="http://xkcd.com/627/"><img alt="" src="http://imgs.xkcd.com/comics/tech_support_cheat_sheet.png" title="tech_support_cheat_sheet" class="aligncenter" width="732" height="823" /></a></p>
<p><em>From <a target="_blank" href="http://xkcd.com/627/">xkcd</a></em></p>
<div class="shr-publisher-884"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://www.devexp.eu/2009/08/27/tech-support-cheat-sheet/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Quartz: test a cron expression</title>
		<link>http://www.devexp.eu/2009/08/18/quartz-test-a-cron-expression/</link>
		<comments>http://www.devexp.eu/2009/08/18/quartz-test-a-cron-expression/#comments</comments>
		<pubDate>Tue, 18 Aug 2009 11:25:27 +0000</pubDate>
		<dc:creator>Van de Voorde Toni</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[quartz]]></category>

		<guid isPermaLink="false">http://www.devexp.eu/?p=871</guid>
		<description><![CDATA[Cron expressions in quartz can sometimes be difficult to test, especially when the cron is programmed to trigger after hours or days. Unless you want to wait that time, here is some snippet code you can use to test a &#8230; <a href="http://www.devexp.eu/2009/08/18/quartz-test-a-cron-expression/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p><div class="wp-caption alignright" style="width: 131px"><img alt="quartz logo" src="http://www.opensymphony.com/quartz/images/quartzEJS.jpg" title="quartz logo" width="121" height="58" /><p class="wp-caption-text">quartz logo</p></div>Cron expressions in quartz can sometimes be difficult to test, especially when the cron is programmed to trigger after hours or days. Unless you want to wait that time, here is some snippet code you can use to test a cron.</p>
<pre class="brush: java; title: ; notranslate">import java.text.ParseException;
import java.util.Date;

import org.quartz.CronExpression;

public class CronTester {

	public static void main(String[] args) throws ParseException {
		final String expression = &quot;0 0 * * * ?&quot;;
        final CronExpression cronExpression = new CronExpression(expression);

        final Date nextValidDate1 = cronExpression.getNextValidTimeAfter(new Date());
        final Date nextValidDate2 = cronExpression.getNextValidTimeAfter(nextValidDate1);

        System.out.println(nextValidDate1);
        System.out.println(nextValidDate2);

	}
}</pre>
<p>Outputs:</p>
<pre class="brush: plain; title: ; notranslate">Tue Aug 18 14:00:00 CEST 2009
Tue Aug 18 15:00:00 CEST 2009</pre>
<div class="shr-publisher-871"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://www.devexp.eu/2009/08/18/quartz-test-a-cron-expression/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
		</item>
		<item>
		<title>Symfony Form: unsetAllFieldsExcept()</title>
		<link>http://www.devexp.eu/2009/04/27/symfony-form-unsetallfieldsexcept/</link>
		<comments>http://www.devexp.eu/2009/04/27/symfony-form-unsetallfieldsexcept/#comments</comments>
		<pubDate>Mon, 27 Apr 2009 12:37:31 +0000</pubDate>
		<dc:creator>Van de Voorde Toni</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Symfony]]></category>
		<category><![CDATA[form]]></category>

		<guid isPermaLink="false">http://www.devexp.eu/?p=706</guid>
		<description><![CDATA[When creating forms in symfony which extends from a Base (ORM) class, you sometimes do not need all fields that Propel/Doctrine generates for you. If you want to remove them you have several ways to do so. 1. Unset the &#8230; <a href="http://www.devexp.eu/2009/04/27/symfony-form-unsetallfieldsexcept/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>When creating forms in symfony which extends from a Base (ORM) class, you sometimes do not need all fields that Propel/Doctrine generates for you. If you want to remove them you have several ways to do so.</p>
<p><b>1. Unset the fiels you don&#8217;t need.</b></p>
<pre class="brush: php; title: ; notranslate">
public function configure() {
  unset($this['field1'], $this['field2'], ... );
}
</pre>
<p>Simple way to remove the fields you don&#8217;t want, but if you change something in your database, which has an impact on that form (new column, foreignkey, etc ), it will be added in the (generated) super class. And if you don&#8217;t update the unset function with that extra field, it will be expected in the form. Unless you have unit tests for all your forms this could brake it without knowing it.</p>
<p><b>2. Override the setup function.</b></p>
<pre class="brush: php; title: ; notranslate">
/**
 * @override
 */
public function setup()
  {
    parent::setup();

    $this-&gt;setWidgets(...);

    $this-&gt;setValidators(...);
  }
</pre>
<p>Another way is to override the setup function and do your own widgets and validators initialization. This is a good way to only intialize the fields you really need, but you&#8217;ll have to do what your ORM generated for you.</p>
<p><b>3. Use a function which unsets all fields except the one you need (like the enableAllPluginsExcept function).</b></p>
<pre class="brush: php; title: ; notranslate">
$this-&gt;unsetAllFieldsExcept(array(
      'field1',
      'field2',
      'field3',
      ...));
</pre>
<p>This would be usefull, because it will remove all fields you do not want to use, and even if new fields are added it will not use them. The drawback is that if you have 20 fields and only need to unset one of them, you&#8217;ll have more type work <img src='http://www.devexp.eu/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> .<br />
Since it does not exist in symfony, I quickly created our own function. This function should be added in the class <u><em>BaseFormPropel.class</em></u>:</p>
<pre class="brush: php; title: ; notranslate">
abstract class BaseFormPropel extends sfFormPropel
{
  public function setup() {
  }

  protected function unsetAllFieldsExcept($fields = array()) {

    $unsetFields = array_diff(array_keys($this-&gt;getWidgetSchema()-&gt;getFields()), $fields);

    foreach($unsetFields as $value) {
      unset($this[$value]);
    }
  }
}
</pre>
<p><b>Which one to use ?</b><br />
None of them are better. But if you need to reset a majority of the fields the ORM has generated then I would go for the method 2. If you only need to unset the fields you do not want to use then I would use the function unsetAllFieldsExcept().</p>
<p>Which method do/would you use ?</p>
<div class="shr-publisher-706"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://www.devexp.eu/2009/04/27/symfony-form-unsetallfieldsexcept/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
		</item>
		<item>
		<title>sfWidgetFormInputCheckbox unchecked bug</title>
		<link>http://www.devexp.eu/2009/04/23/sfwidgetforminputcheckbox-unchecked-bug/</link>
		<comments>http://www.devexp.eu/2009/04/23/sfwidgetforminputcheckbox-unchecked-bug/#comments</comments>
		<pubDate>Thu, 23 Apr 2009 12:33:37 +0000</pubDate>
		<dc:creator>Van de Voorde Toni</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Symfony]]></category>
		<category><![CDATA[form]]></category>
		<category><![CDATA[sfWidgetFormInputCheckbox]]></category>

		<guid isPermaLink="false">http://www.devexp.eu/?p=681</guid>
		<description><![CDATA[Ever tried to create a Symfony form with a check box input field, which by default should be unchecked ? No ? Well read on because it&#8217;s not that easy . This would be the code to print a check &#8230; <a href="http://www.devexp.eu/2009/04/23/sfwidgetforminputcheckbox-unchecked-bug/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>Ever tried to create a Symfony form with a check box input field, which by default should be unchecked ? No ? Well read on because it&#8217;s not that easy <img src='http://www.devexp.eu/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
<p>This would be the code to print a check box input field in a Symfony form:</p>
<pre class="brush: php; title: ; notranslate">
class CheckboxForm extends BaseCheckboxForm {
 public function configure() {
 $this-&gt;widgetSchema['field'] = new sfWidgetFormInputCheckbox();
 }
}
</pre>
<p>When you use the form to create something then by default the check box should be unchecked. And when you use this form for editing, then the check box should be checked if the object you try to edit has already been checked in the past.</p>
<p>If you try this code, you&#8217;ll see that the check box will always be checked. Even if you display this form to create a new object. Strange no ?</p>
<p><span id="more-681"></span></p>
<p>The problem is due to a bug in the Symfony sfWidgetFormInputCheckbox class. Even worse, this bug has been reported the first time 10 months ago (<a href="http://trac.symfony-project.org/ticket/3917" target="_blank">trac #3917</a>) and 1 month later (<a href="http://trac.symfony-project.org/ticket/3996" target="_blank">trac #3996</a>) and it&#8217;s still not fixed ! (grrrrr)</p>
<p>Until Symfony bug fixes this issue, there are 2 work a rounds you can use.</p>
<p><strong>1. Edit the sfWidgetFormInputCheckbox class and patch it:</strong></p>
<p><em>actual</em></p>
<pre class="brush: php; title: ; notranslate">
class sfWidgetFormInputCheckbox extends sfWidgetFormInput
{
 ...
 public function render($name, $value = null, $attributes = array(), $errors = array())
 {
 if (!is_null($value) &amp;&amp; $value !== false)
 {
 $attributes['checked'] = 'checked';
 }
 ...
 }
}
</pre>
<p><em>patched</em></p>
<pre class="brush: php; title: ; notranslate">
class sfWidgetFormInputCheckbox extends sfWidgetFormInput
{
 ...
 public function render($name, $value = null, $attributes = array(), $errors = array())
 {
 if (!is_null($value) &amp;&amp; $value !== false &amp;&amp; $value != 0)
 {
 $attributes['checked'] = 'checked';
 }
 ...
 }
}
</pre>
<p>I would not recommend this, because if like us, you have more than one Symfony environment, there is a chance that you could forget to patch it. And worse if Symfony releases a new version without the bug fix you&#8217;ll have to remember to re patch the file.</p>
<p><strong>2. Extend the sfWidgetFormInputCheckbox class and override the render method:</strong></p>
<p><em>Edit: Put this class in the lib folder and call it myOwnWidgetFormInputCheckbox.class.php. After that run symfony cc.</em></p>
<pre class="brush: php; title: ; notranslate">
/**
 * FIXME: This class can be removed if the sfWidgetFormInputCheckbox bug
 * has been resolved in symfony.
 */
class myOwnWidgetFormInputCheckbox extends sfWidgetFormInputCheckbox
{
 /**
 * Override render method due to symfony bug (http://trac.symfony-project.org/ticket/3917)
 */
 public function render($name, $value = null, $attributes = array(), $errors = array())
 {
 if (!is_null($value) &amp;&amp; $value !== false &amp;&amp; $value != 0)
 {
 $attributes['checked'] = 'checked';
 } 

 if (!isset($attributes['value']) &amp;&amp; !is_null($this-&gt;getOption('value_attribute_value'))) {
 $attributes['value'] = $this-&gt;getOption('value_attribute_value');
 }

 return parent::render($name, null, $attributes, $errors);
 }
}
</pre>
<p>Your form class should then be changed to:</p>
<pre class="brush: php; title: ; notranslate">
class CheckboxForm extends BaseCheckboxForm {
 public function configure() {
 $this-&gt;widgetSchema['field'] = new myOwnWidgetFormInputCheckbox();
 }
}
</pre>
<p>This was very easy to solve, but we lost a lot of time in finding the reason why this stupido check box was always checked. And why the hell is this bug still not solved in Symfony ?</p>
<p>In the mean time patch your symfony or create your own checkbox widget <img src='http://www.devexp.eu/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
<div class="shr-publisher-681"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://www.devexp.eu/2009/04/23/sfwidgetforminputcheckbox-unchecked-bug/feed/</wfw:commentRss>
		<slash:comments>13</slash:comments>
		</item>
		<item>
		<title>PHP DOMDocument: Convert Array to Xml</title>
		<link>http://www.devexp.eu/2009/04/11/php-domdocument-convert-array-to-xml/</link>
		<comments>http://www.devexp.eu/2009/04/11/php-domdocument-convert-array-to-xml/#comments</comments>
		<pubDate>Sat, 11 Apr 2009 08:56:42 +0000</pubDate>
		<dc:creator>Van de Voorde Toni</dc:creator>
				<category><![CDATA[General]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[DOMDocument]]></category>
		<category><![CDATA[xml]]></category>

		<guid isPermaLink="false">http://www.devexp.eu/?p=605</guid>
		<description><![CDATA[Recently I start working on an export module to invoice applications. One of them uses a very simple xml structure (simple nodes without attributes etc.) and therefore I wanted to create this xml also in a very simple way: from &#8230; <a href="http://www.devexp.eu/2009/04/11/php-domdocument-convert-array-to-xml/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p><img src="http://www.devexp.eu/wp-content/uploads/2009/04/elephant-elephant-php-logo1.png" alt="php" title="php" width="146" height="110" class="alignright size-full wp-image-611" />Recently I start working on an export module to invoice applications. One of them uses a very simple xml structure (simple nodes without attributes etc.) and therefore I wanted to create this xml also in a very simple way: from an array.</p>
<p>I decided the use DOM, and not e.g. SimpleXML, because I need to validate my xml with a schema.</p>
<p>After a quick search on the internet I found several snippets that could do the trick until I had to set the same element tag name on the same level:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;nodes&gt;
	&lt;node&gt;text&lt;/node&gt;
	&lt;node&gt;text&lt;/node&gt;
&lt;/nodes&gt;
</pre>
<p>The snippets I found use the index of an array to create the name of the element and the value for the text part. Only everyone knows that you cannot set 2 keys with the same name in an array. </p>
<p>So what could we do to improve this ?</p>
<p><span id="more-605"></span><br />
I changed a snippet so it can generate the example above. The array should now look like this:</p>
<pre class="brush: php; title: ; notranslate">
array (
	“nodes” =&gt; array (
		“node” =&gt; array (
			0 =&gt; “text”
			1 =&gt; “text”
		)
	)
)
</pre>
<p>Since you cannot set integers as element tags, it checks if the index is an integer and if it is it loops the array to recreate the same element tag name with the new value.</p>
<p>I added the function in a class which extends the DOMDocument class (<a href='http://www.devexp.eu/wp-content/uploads/2009/04/xmldomconstructclassphp.gz'>XmlDomConstruct</a>):</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
/**
 * Extends the DOMDocument to implement personal (utility) methods.
 *
 * @author Toni Van de Voorde
 */
class XmlDomConstruct extends DOMDocument {

	/**
	 * Constructs elements and texts from an array or string.
	 * The array can contain an element's name in the index part
	 * and an element's text in the value part.
	 *
	 * It can also creates an xml with the same element tagName on the same
	 * level.
	 *
	 * ex:
	 * &lt;nodes&gt;
	 *   &lt;node&gt;text&lt;/node&gt;
	 *   &lt;node&gt;
	 *     &lt;field&gt;hello&lt;/field&gt;
	 *     &lt;field&gt;world&lt;/field&gt;
	 *   &lt;/node&gt;
	 * &lt;/nodes&gt;
	 *
	 * Array should then look like:
	 *
	 * Array (
	 *   &quot;nodes&quot; =&gt; Array (
	 *     &quot;node&quot; =&gt; Array (
	 *       0 =&gt; &quot;text&quot;
	 *       1 =&gt; Array (
	 *         &quot;field&quot; =&gt; Array (
	 *           0 =&gt; &quot;hello&quot;
	 *           1 =&gt; &quot;world&quot;
	 *         )
	 *       )
	 *     )
	 *   )
	 * )
	 *
	 * @param mixed $mixed An array or string.
	 *
	 * @param DOMElement[optional] $domElement Then element
	 * from where the array will be construct to.
	 *
	 */
	public function fromMixed($mixed, DOMElement $domElement = null) {

		$domElement = is_null($domElement) ? $this : $domElement;

		if (is_array($mixed)) {
			foreach( $mixed as $index =&gt; $mixedElement ) {

				if ( is_int($index) ) {
					if ( $index == 0 ) {
						$node = $domElement;
					} else {
						$node = $this-&gt;createElement($domElement-&gt;tagName);
						$domElement-&gt;parentNode-&gt;appendChild($node);
					}
				} 

				else {
					$node = $this-&gt;createElement($index);
					$domElement-&gt;appendChild($node);
				}

				$this-&gt;fromMixed($mixedElement, $node);

			}
		} else {
			$domElement-&gt;appendChild($this-&gt;createTextNode($mixed));
		}

	}

}
?&gt;
</pre>
<p>And here is a very simple example on how you can use this class:</p>
<pre class="brush: php; title: ; notranslate">
$array = array(
  &quot;nodes&quot; =&gt; array(
    &quot;node&quot; =&gt; array(
      0 =&gt; &quot;text&quot;,
      1 =&gt; &quot;text&quot;
)));

$this-&gt;dom = new XmlDomConstruct('1.0', 'utf-8');
$this-&gt;dom-&gt;fromMixed($array);

echo $this-&gt;dom-&gt;saveXML();
</pre>
<p>Isn&#8217;t that wonderful? You don&#8217;t even have to know how to construct xmls with the DOMDocument object. Of course this will only work for simple xmls.</p>
<p>Maybe, if I have the time, I’ll try to add the possibility to insert attributes to elements.</p>
<div class="shr-publisher-605"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://www.devexp.eu/2009/04/11/php-domdocument-convert-array-to-xml/feed/</wfw:commentRss>
		<slash:comments>16</slash:comments>
		</item>
		<item>
		<title>Symfony Forms Framework: Merge 2 forms</title>
		<link>http://www.devexp.eu/2009/03/19/symfony-forms-framework-merge-2-forms/</link>
		<comments>http://www.devexp.eu/2009/03/19/symfony-forms-framework-merge-2-forms/#comments</comments>
		<pubDate>Thu, 19 Mar 2009 11:02:22 +0000</pubDate>
		<dc:creator>Van de Voorde Toni</dc:creator>
				<category><![CDATA[Framework]]></category>
		<category><![CDATA[Languages]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Symfony]]></category>
		<category><![CDATA[form]]></category>
		<category><![CDATA[framework]]></category>

		<guid isPermaLink="false">http://www.devexp.eu/?p=462</guid>
		<description><![CDATA[Recently I had to create a form to create/update users in our system. Some time ago we decided to save are users in 2 tables. The first table would contain all login information and the second his personal information. This &#8230; <a href="http://www.devexp.eu/2009/03/19/symfony-forms-framework-merge-2-forms/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>Recently I had to create a form to create/update users in our system. Some time ago we decided to save are users in 2 tables. The first table would contain all login information and the second his personal information. This is a simple example of the DB design:</p>
<div id="attachment_463" class="wp-caption aligncenter" style="width: 498px"><img class="size-full wp-image-463" title="User db design" src="http://www.devexp.eu/wp-content/uploads/2009/03/dbdesign.png" alt="User db design" width="488" height="168" /><p class="wp-caption-text">User db design</p></div>
<p>I would not recommend doing this for so little fields. But in our system we have a lot more fields, and it helps us to optimize our queries.</p>
<p>Wouldn&#8217;t it be better if we could merge the 2 forms? The answer is yes. And it&#8217;s pretty easy to do so in Symfony &#8230; too bad that it’s not documented on the Symfony website.</p>
<p><span id="more-462"></span></p>
<p>When you generate the forms with Symfony, you’ll get a UserForm and a UserInfoForm.</p>
<pre class="brush: php; title: ; notranslate">/**
* User form.
*
* @package    form
*/
class UserForm extends BaseUserForm {

public function configure() {

}

}

/**
* UserInfo form.
*
* @package    form
*/
class UserInfoForm extends BaseUserInfoForm {

public function configure() {

}

}</pre>
<p>The idea is to display one form to insert/update those 2 tables. If you are familiar to creating forms with Symfony you know that you could achieve it by instantiating the 2 forms in an action and send them to the templates:</p>
<pre class="brush: php; title: ; notranslate">
/**
* Action Class
*/
class userActions extends sfActions
{
public function executeCreate($request) {
$this-&gt;userForm = new UserForm();
$this-&gt;userInfoForm = new UserInfoForm();
$this-&gt;setTemplate('edit');
}

public function executeEdit($request) {
$this-&gt;userForm = new UserForm(UserPeer::retrieveByPK($request-&gt;getParameter('id')));
$this-&gt;userInfoForm = new UserInfoForm(UserInfoPeer::retrieveByPK($request-&gt;getParameter('id')));
}

public function executeUpdate($request) {
$this-&gt;userForm = new UserForm(UserPeer::retrieveByPK($request-&gt;getParameter('id')));
$this-&gt;userInfoForm = new UserInfoForm(UserInfoPeer::retrieveByPK($request-&gt;getParameter('id')));

$this-&gt;userForm-&gt;bind($request-&gt;getParameter($this-&gt;userForm-&gt;getName()));
$this-&gt;userInfoForm-&gt;bind($request-&gt;getParameter($this-&gt;userInfoForm-&gt;getName()));

// etc ...
}
}

// Template code editSuccess.php
&lt;?php $user = $userForm-&gt;getObject(); ?&gt;

&lt;form action=&quot;&lt;?php echo url_for('user/update'.(!$user-&gt;isNew() ? '?id='.$user-&gt;getId() : '')) ?&gt;&quot; method=&quot;post&quot;&gt;
&lt;table&gt;
&lt;tfoot&gt;
&lt;tr&gt;
&lt;td colspan=&quot;2&quot;&gt;
&lt;input type=&quot;submit&quot; value=&quot;Save&quot; /&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/tfoot&gt;
&lt;tbody&gt;
&lt;?php echo $userForm ?&gt;
&lt;?php echo $userInfoForm ?&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;/form&gt;
</pre>
<p>This is really annoying to work this way. You always have to instance 2 forms in the action and the templates. Wouldn&#8217;t it be better if we could merge the 2 forms? The answer is yes. And it&#8217;s pretty easy to do so in Symfony &#8230; too bad that it’s not documented on the Symfony website.</p>
<p>Here is how you do it:</p>
<p><span style="text-decoration: underline;"><strong>1. UserForm.class.php</strong></span></p>
<pre class="brush: php; title: ; notranslate">/**
* User form.
*
* @package    form
*/
class UserForm extends BaseUserForm {

public function configure() {
$this-&gt;mergeForm(new UserInfoForm(UserInfoPeer::retrieveByPK($this-&gt;getObject()-&gt;getId())));
}

/**
* Override the save method to save the merged user info form.
*/
public function save($con = null) {
parent::save();

$this-&gt;updateUserInfo();

return $this-&gt;object;
}

/**
* Updates the user info merged form.
*/
protected function updateUserInfo() {
// update user info
if (!is_null($userInfo = $this-&gt;getUserInfo())) {

$values = $this-&gt;getValues();
if ( $userInfo-&gt;isNew() ) {
$values['user_id'] = $this-&gt;object-&gt;getId();
}

$userInfo-&gt;fromArray($values, BasePeer::TYPE_FIELDNAME);

$userInfo-&gt;save();
}
}

/**
* Returns the user info object. If it does
* not exist return a new instance.
*
* @return UserInfo
*/
protected function getUserInfo() {

if (!$this-&gt;object-&gt;getUserInfo()) {
return new UserInfo();
}

return $this-&gt;object-&gt;getUserInfo();
}
}
</pre>
<p><span style="text-decoration: underline;"><strong>2. actions.class.php</strong></span></p>
<pre class="brush: php; title: ; notranslate">
public function executeCreate($request) {
$this-&gt;form = new UserForm();
$this-&gt;setTemplate('edit');
}

public function executeEdit($request) {
$this-&gt;form = new UserForm(UserPeer::retrieveByPK($request-&gt;getParameter('id')));
}

public function executeUpdate($request) {

$this-&gt;forward404Unless($request-&gt;isMethod('post'));

$this-&gt;form = new UserForm(UserPeer::retrieveByPK($request-&gt;getParameter('id')));

$this-&gt;form-&gt;bind($request-&gt;getParameter($this-&gt;form-&gt;getName()));
if ($this-&gt;form-&gt;isValid()) {
$user = $this-&gt;form-&gt;save();
$this-&gt;redirect('user/edit?id='.$user-&gt;getId());
}

$this-&gt;setTemplate('edit');
}
</pre>
<p><span style="text-decoration: underline;"><strong>3. editSuccess.php</strong></span></p>
<pre class="brush: php; title: ; notranslate">
&lt;?php $user = $userForm-&gt;getObject(); ?&gt;

&lt;form action=&quot;&lt;?php echo url_for('user/update'.(!$user-&gt;isNew() ? '?id='.$user-&gt;getId() : '')) ?&gt;&quot; method=&quot;post&quot;&gt;
&lt;table&gt;
&lt;tfoot&gt;
&lt;tr&gt;
&lt;td colspan=&quot;2&quot;&gt;
&lt;input type=&quot;submit&quot; value=&quot;Save&quot; /&gt;
&lt;/td&gt;
&lt;/tr&gt;
&lt;/tfoot&gt;
&lt;tbody&gt;
&lt;?php echo $userForm ?&gt;
&lt;/tbody&gt;
&lt;/table&gt;
&lt;/form&gt;
</pre>
<p>As you can see, it’s the UserForm that will handle all the business of the UserInfoForm. This is great because the code in the action and template will be much more lightened and if needed it can easily be reused somewhere else.</p>
<p>This was a simple example on how to merge 2 forms, but since it&#8217;s not documented on the symfony website, it took me some time to fully understand on how to make it work. Now you can do much more advanced operations. <img src='http://www.devexp.eu/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<div class="shr-publisher-462"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://www.devexp.eu/2009/03/19/symfony-forms-framework-merge-2-forms/feed/</wfw:commentRss>
		<slash:comments>33</slash:comments>
		</item>
		<item>
		<title>Symfony Forms Framework: Change validators at runtime.</title>
		<link>http://www.devexp.eu/2009/02/15/symfony-forms-framework-change-validators-at-runtime/</link>
		<comments>http://www.devexp.eu/2009/02/15/symfony-forms-framework-change-validators-at-runtime/#comments</comments>
		<pubDate>Sun, 15 Feb 2009 09:34:12 +0000</pubDate>
		<dc:creator>Van de Voorde Toni</dc:creator>
				<category><![CDATA[Framework]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Symfony]]></category>
		<category><![CDATA[form]]></category>

		<guid isPermaLink="false">http://www.devexp.eu/?p=374</guid>
		<description><![CDATA[Let’s say you have to make a user form with password fields. When you create the user you want the password fields to be required, but on an update the password fields should be optional because you don’t want the &#8230; <a href="http://www.devexp.eu/2009/02/15/symfony-forms-framework-change-validators-at-runtime/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>Let’s say you have to make a user form with password fields. When you create the user you want the password fields to be <strong>required</strong>, but on an update the password fields should be <strong>optional</strong> because you don’t want the user the fill in his password on each update.</p>
<p>This is tricky because in the symfony forms Framework you have to predefine your validators. Your form would look like this:</p>
<pre class="brush: php; title: ; notranslate">
class UserForm extends BaseUserForm {

  public function configure() {
    // Widgets
    $this-&gt;widgetSchema['password'] = new sfWidgetFormInputPassword();
    $this-&gt;widgetSchema['password_again'] = new sfWidgetFormInputPassword();

    // Validators
    $this-&gt;validatorSchema['password']-&gt;setOption('required', false);
    $this-&gt;validatorSchema['password_again'] = clone $this-&gt;validatorSchema['password'];

    $this-&gt;widgetSchema-&gt;moveField('password_again', 'after', 'password');

    $this-&gt;mergePostValidator(new sfValidatorSchemaCompare('password', sfValidatorSchemaCompare::EQUAL, 'password_again', array(), array('invalid' =&gt; 'The two passwords must be the same.')));
  }

}
</pre>
<p>In this signature of the form I defined the password and password_again field as optional, which is correct for an update of the user, but incorrect for the creation of the user. How the hell can I change the validator of the password field when I create a user ?</p>
<p>Well thanks to the good and well designed framework of symfony it is very simple <img src='http://www.devexp.eu/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
<pre class="brush: php; title: ; notranslate">
class UserForm extends BaseUserForm {

  public function configure() {
    // Widgets
    $this-&gt;widgetSchema['password'] = new sfWidgetFormInputPassword();
    $this-&gt;widgetSchema['password_again'] = new sfWidgetFormInputPassword();

    // Validators
    $this-&gt;validatorSchema['password']-&gt;setOption('required', false);
    $this-&gt;validatorSchema['password_again'] = clone $this-&gt;validatorSchema['password'];

    $this-&gt;widgetSchema-&gt;moveField('password_again', 'after', 'password');

    $this-&gt;mergePostValidator(new sfValidatorSchemaCompare('password', sfValidatorSchemaCompare::EQUAL, 'password_again', array(), array('invalid' =&gt; 'The two passwords must be the same.')));
  }

  public function bind(array $taintedValues = null, array $taintedFiles = null) {

    if ( $this-&gt;object-&gt;isNew() ) {
      $this-&gt;validatorSchema['password']-&gt;setOption('required', true);
    }

    parent::bind($taintedValues, $taintedFiles);
  }

}
</pre>
<p>What I did is override the function <em>bind</em> and before calling the bind method of the parent, I checked if the user object is new (means that we create a user) and if this is the case set the required option of the password field to true. </p>
<div class="shr-publisher-374"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://www.devexp.eu/2009/02/15/symfony-forms-framework-change-validators-at-runtime/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Storing multiple data in 1 database field with PHP serialize / unserialize</title>
		<link>http://www.devexp.eu/2008/10/08/storing-multiple-data-in-1-database-field-with-php-serialize-unserialize/</link>
		<comments>http://www.devexp.eu/2008/10/08/storing-multiple-data-in-1-database-field-with-php-serialize-unserialize/#comments</comments>
		<pubDate>Wed, 08 Oct 2008 10:45:47 +0000</pubDate>
		<dc:creator>Van de Voorde Toni</dc:creator>
				<category><![CDATA[database]]></category>
		<category><![CDATA[mysql]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[serialize]]></category>

		<guid isPermaLink="false">http://www.devexp.eu/?p=163</guid>
		<description><![CDATA[While the serialize/unserialize functions exists since the early PHP 4 version, I ignored its existence. I discovered it recently doing some research on how to store multiple data in 1 database field. Before continuing, keep in mind that it&#8217;s not &#8230; <a href="http://www.devexp.eu/2008/10/08/storing-multiple-data-in-1-database-field-with-php-serialize-unserialize/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<!-- Start Shareaholic LikeButtonSetTop Automatic --><!-- End Shareaholic LikeButtonSetTop Automatic --><p>While the serialize/unserialize functions exists since the early PHP 4 version, I ignored its existence. I discovered it recently doing some research on how to store multiple data in 1 database field.</p>
<p>Before continuing, keep in mind that it&#8217;s not always recommended to store multiple data in a database field, because it will be very difficult, if not impossible, to create queries using the inserted data. All serialized data will have to be unserialized, which takes time.</p>
<p>But why did I use it ?</p>
<p>The website I work on has a widget system (like netvibes and igoogle). Each widget has default settings that can be altered by a user. Those changes need to be saved in a database, so the next time the user loads the widget it will make use of the new settings.</p>
<p>When I first had to create this, I did not know of serialization in php, so I created the following db structure. (trying to respect DB Normalization).</p>
<div id="attachment_164" class="wp-caption aligncenter" style="width: 510px"><a href="http://www.devexp.eu/wp-content/uploads/2008/10/serialize-widgetsettings.png"><img class="size-full wp-image-164" title="widget and settings" src="http://www.devexp.eu/wp-content/uploads/2008/10/serialize-widgetsettings.png" alt="widget and settings" width="500" height="126" /></a><p class="wp-caption-text">widget and settings</p></div>
<p>You can see that I have a table with a list of widgets and a list of possible settings. Those two tables are connected to a widgetSetting table where the value of a setting to a widget is stored. It worked perfectly but it is not so proficient :</p>
<p>* To retrieve a widget&#8217;s settings, you need to join 2 tables.<br />
* To insert new widget settings, you need to check the settings table if a setting exists or not.<br />
* When updating widget settings, you need to check if a setting is still used or not.</p>
<p>This is a lot of work and database complexity for something that only is used for saving/retrieving settings of a widget. In my case it would be much better if I could save those settings in 1 field in the widget table.</p>
<div id="attachment_165" class="wp-caption aligncenter" style="width: 185px"><a href="http://www.devexp.eu/wp-content/uploads/2008/10/serialize-widget.png"><img class="size-full wp-image-165" title="widget" src="http://www.devexp.eu/wp-content/uploads/2008/10/serialize-widget.png" alt="widget" width="175" height="157" /></a><p class="wp-caption-text">widget</p></div>
<p>This is how I serialize my settings :</p>
<pre class="brush: php; title: ; notranslate">
$settings = array(
'itemsOnPage' =&gt; 30,
'showChart' =&gt; true,
'startDate' =&gt; '01-10-2008',
'endDate' =&gt; '31-10-2008'
);

$serializedSettings = serialize($settings);

/**
* outputs:
*
* a:4:{s:11:&quot;itemsOnPage&quot;;i:30;s:9:&quot;showChart&quot;;b:1;s:9:&quot;startDate&quot;;s:10:&quot;01-10-2008&quot;;s:7:&quot;endDate&quot;;s:10:&quot;31-10-2008&quot;;}
*
*/</pre>
<p>The serialize function will generate a storable representation of my array.<br />
Just save this string in a database field and the job is done. To rebuild the original array from this value you only need to call the unserialize function:</p>
<pre class="brush: php; title: ; notranslate"> $storedRepresentation = 'a:4:{s:11:&quot;itemsOnPage&quot;;i:30;s:9:&quot;showChart&quot;;b:1;s:9:&quot;startDate&quot;;s:10:&quot;01-10-2008&quot;;s:7:&quot;endDate&quot;;s:10:&quot;31-10-2008&quot;;}';
$settings = unserialize($storedRepresentation);

/*
* print_r($settings) would give :
*
* Array
* (
*  [itemsOnPage] =&gt; 30
*  [showChart] =&gt; 1
*  [startDate] =&gt; 01-10-2008
*  [endDate] =&gt; 31-10-2008
* )
*/</pre>
<p>As you can see the unserialize function correctly rebuild the original array.</p>
<p>It is also possible to serialize Objects with the exception of the built-in objects.</p>
<pre class="brush: php; title: ; notranslate">class MySettings {

private
$itemsOnPage = 30,
$showCart = true,
$startDate = '01-10-2008',
$endDate = '31-10-2008';

public function getItemsOnPage() {
return $this-&gt;itemsOnPage;
}
}

$mySettingsSerialized = serialize(new MySettings());

$mySettings = unserialize($mySettingsSerialized);

echo $mySettings-&gt;getItemsOnPage(); // 30</pre>
<p>When serializing objects, PHP will attempt to call the member function __sleep() prior to serialization. This is to allow the object to do any last minute clean-up, etc. prior to being serialized. Likewise, when the object is restored using unserialize() the __wakeup() member function is called.</p>
<pre class="brush: php; title: ; notranslate">class MySettings {

private
$itemsOnPage = 30,
$showCart = true,
$startDate = '01-10-2008',
$endDate = '31-10-2008';

public function getItemsOnPage() {
return $this-&gt;itemsOnPage;
}

public function __wakeup() {
$this-&gt;itemsOnPage *= 10;
}
}

$mySettingsSerialized = serialize(new MySettings());

$mySettings = unserialize($mySettingsSerialized);

echo $mySettings-&gt;getItemsOnPage(); // 300</pre>
<p>So you see it is very simple to use the seriailize/unserialize functions in php. But like I said in the beginning of the post, use it wisely when storing the serialized value in a database. I only use it when I do not need the value for creating sql queries.</p>
<div class="shr-publisher-163"></div><!-- Start Shareaholic LikeButtonSetBottom Automatic --><!-- End Shareaholic LikeButtonSetBottom Automatic -->]]></content:encoded>
			<wfw:commentRss>http://www.devexp.eu/2008/10/08/storing-multiple-data-in-1-database-field-with-php-serialize-unserialize/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

