<?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>Swarm of XeBees &#187; Ram Sharma</title>
	<atom:link href="http://xebee.xebia.in/author/ramsharma/feed/" rel="self" type="application/rss+xml" />
	<link>http://xebee.xebia.in</link>
	<description>powered by Xebia India</description>
	<lastBuildDate>Sun, 13 May 2012 08:53:51 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.2</generator>
		<item>
		<title>Multitasking aka Multi-Processing in PHP</title>
		<link>http://xebee.xebia.in/2011/10/16/implementing-multithreading-in-php/</link>
		<comments>http://xebee.xebia.in/2011/10/16/implementing-multithreading-in-php/#comments</comments>
		<pubDate>Sun, 16 Oct 2011 08:52:19 +0000</pubDate>
		<dc:creator>Ram Sharma</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Advance PHP]]></category>
		<category><![CDATA[Concurrency]]></category>
		<category><![CDATA[Multithreading]]></category>

		<guid isPermaLink="false">http://xebee.xebia.in/?p=9938</guid>
		<description><![CDATA[PHP is now quite old in industry and has been used widely in web based applications. PHP has also evolved much more as enterprise web application language. But PHP still lacks a lot many features, which are very commonly and heavily used in Java, .Net or any other enterprise language. One of those lacking features [...]]]></description>
			<content:encoded><![CDATA[<p>PHP is now quite old in industry and has been used widely in web based applications. PHP has also evolved much more as enterprise web application language. But PHP still lacks a lot many features, which are very commonly and heavily used in Java, .Net or any other enterprise language. One of those lacking features in PHP is 'Multi-tasking' or support for concurrent processing.</p>
<p>To implement multi-tasking in PHP, people have found a couple of ways like by using pcntl_fork(), exec() and curl. You can Google out those solutions easily.</p>
<p>Today, I am going to explain you one more way to  implement 'Multi-tasking' using Gearman library and Gearman server. To implement Gearman solution for PHP, you first have to install Gearman server to your machine. You can find more details about Gearman and its installation here: <a title="Gearman" href="http://gearman.org" target="_blank">http://gearman.org/</a></p>
<p>Gearman server comes in 3 flavours C, Java and Perl.</p>
<p><span id="more-9938"></span></p>
<p>I am using Gearman C implementation 'gearmand' as Gearman server in this blog. You can download &amp; install gearmand from here <a title="download gearman" href="http://gearman.org/index.php?id=getting_started" target="_blank">http://gearman.org/index.php?id=getting_started</a>. After installing it you will have to start the server by running this command:</p>
<pre class="brush: php; title: ; notranslate">
$ /usr/local/sbin gearmand -d
#or
$ gearmand -d
</pre>
<p>If you are using windows or Mac, I would suggest you to use Java version of Gearman server. I have not tried that but I think Java version can easily be installed and run on Windows/Mac.</p>
<p>Now when you have Gearman server in place and running you can install any of the PHP client to work with Gearman server. There are two solutions available officially to use Gearman for PHP:</p>
<ol>
<li> 1. PHP extension (currently only supported on Linux but you can try to compile the library on Windows by using Cygwin)</li>
<li> 2. Net_Gearman - pure PHP implementation, a pear module</li>
</ol>
<p>I am using PHP extension on my Ubuntu machine to run examples to explain Multi-tasking. Once you installed extension on your machine (see here for help: http://docs.php.net/manual/en/book.gearman.php), do the following steps:</p>
<p>Create worker php file worker.php or gearman-worker.php. A gearman worker is thread running as worker to perform a specific task requested by clients. Like in this example we are going to use string reverse method as worker task. Here is the code for worker:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
// following example code is taken from : http://www.php.net/manual/en/gearman.examples-reverse.php
echo &quot;Starting\n&quot;;

# Create our worker object.
$gmworker= new GearmanWorker();

# Add default server (localhost).
$gmclient-&gt;addServer();

# Register function &quot;reverse&quot; with the server. Change the worker function to
# &quot;reverse_fn_fast&quot; for a faster worker with no output.
$gmworker-&gt;addFunction(&quot;reverse&quot;, &quot;reverse_fn&quot;);

print &quot;Waiting for job...\n&quot;;
while($gmworker-&gt;work())
{
  if ($gmworker-&gt;returnCode() != GEARMAN_SUCCESS)
  {
    echo &quot;return_code: &quot; . $gmworker-&gt;returnCode() . &quot;\n&quot;;
    break;
  }
}

function reverse_fn($job)
{
  echo &quot;Received job: &quot; . $job-&gt;handle() . &quot;\n&quot;;

  $workload = $job-&gt;workload();
  $workload_size = $job-&gt;workloadSize();

  echo &quot;Workload: $workload ($workload_size)\n&quot;;

  # This status loop is not needed, just showing how it works
  for ($x= 0; $x &lt; $workload_size; $x++)   {     echo &quot;Sending status: &quot; . ($x + 1) . &quot;/$workload_size complete\n&quot;;     $job-&gt;sendStatus($x, $workload_size);
    sleep(1);
  }

  $result= strrev($workload);
  echo &quot;Result: $result\n&quot;;

  # Return what we want to send back to the client.
  return $result;
}
</pre>
<p>The above code is creating a GearmanWorker and attaching it to the default Gearman server (local gearmand server process, you can pass server ip and port if your gearman server running on different machine)</p>
<p>To see if the above worker is running properly and producing expected results, you have to run the worker by using the following command:</p>
<pre class="brush: bash; title: ; notranslate">
$ php gearman-worker.php
</pre>
<p>Now create a client to create Job for the worker. Here is the code for the client.php or gearman-client.php:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
// following example code is taken from : http://www.php.net/manual/en/gearman.examples-reverse.php

# Create our client object.
$gmclient= new GearmanClient();

# Add default server (localhost).
$gmclient-&gt;addServer();

echo &quot;Sending job\n&quot;;

# Send reverse job
do
{
  $result = $gmclient-&gt;do(&quot;reverse&quot;, &quot;Hello!&quot;);

  # Check for various return packets and errors.
  switch($gmclient-&gt;returnCode())
  {
    case GEARMAN_WORK_DATA:
      echo &quot;Data: $result\n&quot;;
      break;
    case GEARMAN_WORK_STATUS:
      list($numerator, $denominator)= $gmclient-&gt;doStatus();
      echo &quot;Status: $numerator/$denominator complete\n&quot;;
      break;
    case GEARMAN_WORK_FAIL:
      echo &quot;Failed\n&quot;;
      exit;
    case GEARMAN_SUCCESS:
      break;
    default:
      echo &quot;RET: &quot; . $gmclient-&gt;returnCode() . &quot;\n&quot;;
      exit;
  }
}
while($gmclient-&gt;returnCode() != GEARMAN_SUCCESS);

?&gt;
</pre>
<p>Now when you run the above code by:</p>
<pre class="brush: bash; title: ; notranslate">
$ php gearman-client.php
</pre>
<p>It will generate a JOB for gearman worker(s) available on server (in our case, we created only one worker but you can run multiple workers for the same JOB).<br />
The above code is not running the reverse job in background or you can say not running in multi-threaded style. Like we have used:</p>
<pre class="brush: php; title: ; notranslate">
  $result = $gmclient-&gt;do(&quot;reverse&quot;, &quot;Hello!&quot;);
</pre>
<p>Which will hold the code execution of the client until it gets the result or response from worker. To make it multi-threaded you have to modify your code a bit. For example see below:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
//http://docs.php.net/manual/en/gearman.examples-reverse-bg.php
# create our client object
$gmclient= new GearmanClient();

# add the default server (localhost)
$gmclient-&gt;addServer();

# run reverse client in the background
$job_handle = $gmclient-&gt;doBackground(&quot;reverse&quot;, &quot;this is a test&quot;);

if ($gmclient-&gt;returnCode() != GEARMAN_SUCCESS)
{
  echo &quot;bad return code\n&quot;;
  exit;
}

echo &quot;done!\n&quot;;

?&gt;
</pre>
<p>Now just by making the call to worker as:</p>
<pre class="brush: php; title: ; notranslate">
$job_handle = $gmclient-&gt;doBackground(&quot;reverse&quot;, &quot;this is a test&quot;);
</pre>
<p>The code execution will not halt. doBackground() method is the method which is being used for creating a separate thread to perform a specific JOB. The above program will do:</p>
<pre class="brush: php; title: ; notranslate">
echo &quot;done!\n&quot;;
</pre>
<p>and finish the execution as soon as the Job is sent to worker (as it has nothing more to do, you can make some more logic and then check the client status and response)</p>
<p><strong>Conclusion</strong>: Multi-taskingin PHP is not supported in PHP natively, but you have several ways to achieve the same. Gearman server and client libraries is one of the ways you can choose to implement multi-processing in PHP very easily. You can user Gearman library for processing heavy application like: image processing, resizing or do bulk data manipulation, sending emails in bulk etc.</p>
]]></content:encoded>
			<wfw:commentRss>http://xebee.xebia.in/2011/10/16/implementing-multithreading-in-php/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Symfony Functional Testing &#8211; Form POST and AJAX Request Testing</title>
		<link>http://xebee.xebia.in/2011/07/29/symfony-functional-testing-form-post-and-ajax-request-testing/</link>
		<comments>http://xebee.xebia.in/2011/07/29/symfony-functional-testing-form-post-and-ajax-request-testing/#comments</comments>
		<pubDate>Fri, 29 Jul 2011 07:11:16 +0000</pubDate>
		<dc:creator>Ram Sharma</dc:creator>
				<category><![CDATA[PHP]]></category>
		<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Testing]]></category>
		<category><![CDATA[Functional Testing]]></category>

		<guid isPermaLink="false">http://xebee.xebia.in/?p=9493</guid>
		<description><![CDATA[Symfony is a one of the best open-source PHP web application frameworks with a huge and comprehensive documentation. Symfony comes with default inbuilt testing framework for functional and unit testing. I recently started working on Symfony functional test cases. I personally found the testing framework very strong and useful. When I was writing functional test [...]]]></description>
			<content:encoded><![CDATA[<p>Symfony is a one of the best open-source PHP web application frameworks with a huge and comprehensive documentation. Symfony comes with default inbuilt testing framework for functional and unit testing. I recently started working on Symfony functional test cases. I personally found the testing framework very strong and useful.</p>
<p>When I was writing functional test cases for my recent application, I came across with various scenarios where Symfony's documentation lacks or very limited information available on web directly. Here, I am sharing my experiences and solutions for the various scenarios of functional testing.</p>
<p>Testing post request with forms:<br />
Let's take an example if you have any user registration feature and you want to test it (here is a simple code that I used to test):</p>
<p>Assuming that you have registration functionality working with Symfony framework and its URL is http://www.xyz.com/register and it shows a form:</p>
<pre class="brush: xml; title: ; notranslate">
&lt;form action=&quot;/register&quot; method=&quot;post&quot; &gt;
 &lt;tr&gt;
   &lt;th&gt;&lt;label for=&quot;signup_username&quot;&gt;User Name&lt;/label&gt;&lt;/th&gt;
   &lt;td&gt;&lt;input type=&quot;text&quot; name=&quot;signup[username]&quot; id=&quot;signup_username&quot; /&gt;&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
   &lt;th&gt;&lt;label for=&quot;signup_email&quot;&gt;Email&lt;/label&gt;&lt;/th&gt;
   &lt;td&gt;&lt;input type=&quot;text&quot; name=&quot;signup[email]&quot; id=&quot;signup_email&quot; /&gt;&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
   &lt;th&gt;&lt;label for=&quot;signup_password&quot;&gt;Password&lt;/label&gt;&lt;/th&gt;
   &lt;td&gt;&lt;input type=&quot;password&quot; name=&quot;signup[password]&quot; id=&quot;signup_password&quot; /&gt;&lt;/td&gt;
 &lt;/tr&gt;
 &lt;tr&gt;
   &lt;th&gt;&lt;label for=&quot;signup_password_confirmation&quot;&gt;Confirm Password&lt;/label&gt;&lt;/th&gt;
   &lt;td&gt;&lt;input type=&quot;password&quot; name=&quot;signup[password_confirmation]&quot; id=&quot;signup_password_confirmation&quot; /&gt;&lt;/td&gt;
 &lt;/tr&gt;
 &lt;/form&gt;
&lt;pre&gt;</pre>
<p><span id="more-9493"></span></pre>
<p>I am assuming you have a fair idea of writing functional test cases in Symfony. Now to create a functional test case. Create a test file RegisterTest.php in your project's test/functional directory, you can do it manually or if you have used Symfony CLI to generate your module, it will automatically generate the test file and it will look like the following by default:</p>
<pre class="brush: php; title: ; notranslate">
 include(dirname(__FILE__).'/../../bootstrap/functional.php');

 $browser = new sfTestFunctional(new sfBrowser());

 $browser-&gt;
   get('/register')-&gt;
   with('request')-&gt;begin()-&gt;
     isParameter('module', 'UserRegistration')-&gt;
     isParameter('action', 'index')-&gt;
   end()-&gt;
   with('response')-&gt;begin()-&gt;
     isStatusCode(200)-&gt;
     checkElement('body', '!/This is a temporary page/')-&gt;
  end();
 </pre>
<p>To test general success of the registration page, if it  is properly loaded in the browser, update the above code with the following:</p>
<pre class="brush: php; title: ; notranslate">
 $browser-&gt;
   get('/register')-&gt;
   with('request')-&gt;begin()-&gt;
     isParameter('module', 'UserRegistration')-&gt;
     isParameter('action', 'index')-&gt;
   end()-&gt;
   with('response')-&gt;begin()-&gt;
     isStatusCode(200)-&gt;
     checkElement('form input[type=&quot;text&quot;][name=&quot;signin[username]&quot;]',true)-&gt;
     checkElement('form input[type=&quot;text&quot;][name=&quot;signin[password]&quot;]',true)-&gt;
 end();
 </pre>
<p>I am just checking only 2 fields of the form but you can check as many fields as you want. The above code will make a GET request to '/register' through a mock browser object '$browser' and check the response if the form have those required elements in it.</p>
<pre class="brush: php; title: ; notranslate">
 input[type=&quot;text&quot;][name=&quot;signin[username]&quot;] ~ &lt;input type=&quot;text&quot; name=&quot;signup[username]&quot; id=&quot;signup_username&quot; /&gt;
 </pre>
<p>When you run the above test case via Symfony command line tool:</p>
<pre class="brush: bash; title: ; notranslate">
 symfony test:functional yourapp RegisterTest
 </pre>
<p>it will give you a result something like:</p>
<pre class="brush: php; title: ; notranslate">
 # get /register
 ok 1 - status code is 200
 ok 2 - response selector form input[type=text][name=signin[username]] exists
 ok 2 - response selector form input[type=text][name=signin[password]] exists
 </pre>
<p>Now to extend the test case to test the functionality for actually registering the user with the form, use the code below:</p>
<pre class="brush: php; title: ; notranslate">
 $browser-&gt;
   get('/register')-&gt;
   with('request')-&gt;begin()-&gt;
     isParameter('module', 'UserRegistration')-&gt;
     isParameter('action', 'index')-&gt;
   end()-&gt;
   with('response')-&gt;begin()-&gt;
     isStatusCode(200)-&gt;
     checkElement('form input[type=&quot;text&quot;][name=&quot;signin[username]&quot;]',true)-&gt;
     checkElement('form input[type=&quot;text&quot;][name=&quot;signin[password]&quot;]',true)-&gt;
   end()-&gt;
   with('form')-&gt;begin()-&gt;
     setField('signup[username]', 'abc')-&gt;
     setField('signup[email_address]', 'abc@xyz.com')-&gt;
     setField('signup[password]', 'xyz')-&gt;
     setField('signup[password_confirmation]', 'xyz')-&gt;
   click('save')-&gt;
 end();
 </pre>
<p>Assuming the code redirects the user to some other page after successfully registration:</p>
<pre class="brush: php; title: ; notranslate">
 with('form')-&gt;begin()-&gt;
   setField('signup[username]', 'abc')-&gt;
   setField('signup[email_address]', 'abc@xyz.com')-&gt;
   setField('signup[password]', 'xyz')-&gt;
   setField('signup[password_confirmation]', 'xyz')-&gt;
   click('save')-&gt;
 end()-&gt;
 with('response')-&gt;begin()-&gt;
   isRedirected()-&gt;
   isStatusCode(302)-&gt;
   followRedirect()-&gt;
 end();
 </pre>
<p>Now there is a case in which the form had some errors while submitting, it will fail your test:</p>
<pre class="brush: php; title: ; notranslate">
 isRedirected()-&gt;
 isStatusCode(302)-&gt;
 </pre>
<p>and you have no clue why it is failing? What was the error on the form? or if the form had an error while submitting the request. Use the following code to check that:</p>
<pre class="brush: php; title: ; notranslate">
 with('form')-&gt;begin()-&gt;
   setField('signup[username]', 'abc')-&gt;
   setField('signup[email_address]', 'abc@xyz.com')-&gt;
   setField('signup[password]', 'xyz')-&gt;
   setField('signup[password_confirmation]', 'xyz')-&gt;
   click('save')-&gt;
 end()-&gt;
 with('form')-&gt;begin()-&gt;
   hasErrors(false)-&gt;
 end()-&gt;
 with('response')-&gt;begin()-&gt;
   isRedirected()-&gt;
   isStatusCode(302)-&gt;
   followRedirect()-&gt;
 end();
 </pre>
<p>By using the above code at-least you can now know that the form had errors and you can use debug method of the $browser object to debug that error:</p>
<pre class="brush: php; title: ; notranslate">
 with('form')-&gt;begin()-&gt;
   hasErrors(false)-&gt;
   debug()-&gt;
 end()-&gt;
 </pre>
<p>This is how you can write and debug test cases for Form POST request testing scenarios.</p>
<p>There is another interesting scenario I came across for AJAX request testing in Symfony application. You will hardly find information on the web directly, which talks about AJAX requests testing, except a small paragraph on <a title="Symfony AJAX Request Testing" href="http://www.symfony-project.org/jobeet/1_4/Doctrine/en/18" target="_blank">http://www.symfony-project.org/jobeet/1_4/Doctrine/en/18</a></p>
<p>The following simple test case includes both the scenarios: AJAX GET and AJAX POST request testing:</p>
<p>This is a simple scenario to add a new book in the books list in a library management system with AJAX. In this scenario we are testing that AJAX GET request should take a Book form in response with some basic fields and after putting the data in the form the page posts the data back to the server, if the book is added successfully it will send a redirection with Status code 302.</p>
<pre class="brush: php; title: ; notranslate">
 $browser-&gt;setHttpHeader('X-Requested-With', 'XMLHttpRequest')-&gt;
   get('/book/add')-&gt;
   with('request')-&gt;begin()-&gt;
     isParameter('module', 'Book')-&gt;
     isParameter('action', 'add')-&gt;
   end()-&gt;
   with('response')-&gt;begin()-&gt;
     isStatusCode(200)-&gt;
     checkElement('form input[type=&quot;text&quot;][name=&quot;book[book_name]&quot;]',true)-&gt;
     checkElement('form input[type=&quot;text&quot;][name=&quot;book[book_author]&quot;]',true)-&gt;
   end()-&gt;
   with('form')-&gt;begin()-&gt;
     setHttpHeader('X-Requested-With', 'XMLHttpRequest')-&gt;
     setField('book[book_name]', 'Symfony Testing')-&gt;
     setField('book[book_author]', 'Ram Sharma')-&gt;
     click('Save')-&gt;
   end()-&gt;
   with('form')-&gt;begin()-&gt;
     hasErrors(false)-&gt;
   end()-&gt;
   with('response')-&gt;begin()-&gt;
     isRedirected()-&gt;
     isStatusCode(302)-&gt;
    followRedirect()-&gt;
 end();
 </pre>
<p>In the above two cases, If you have the features only for Authenticated users, so you would not be able to PASS your test cases. For that you have to do mock login in your test case, like the code below:<br />
Assuming you have a login form like this:</p>
<pre class="brush: xml; title: ; notranslate">
 &lt;form action=&quot;/register&quot; method=&quot;post&quot; &gt;
   &lt;tr&gt;
     &lt;th&gt;&lt;label for=&quot;signin_username&quot;&gt;User Name&lt;/label&gt;&lt;/th&gt;
     &lt;td&gt;&lt;input type=&quot;text&quot; name=&quot;signin[username]&quot; id=&quot;signin_username&quot; /&gt;&lt;/td&gt;
   &lt;/tr&gt;
   &lt;tr&gt;
     &lt;th&gt;&lt;label for=&quot;signin_password&quot;&gt;Password&lt;/label&gt;&lt;/th&gt;
     &lt;td&gt;&lt;input type=&quot;password&quot; name=&quot;signin[password]&quot; id=&quot;signin_password&quot; /&gt;&lt;/td&gt;
   &lt;/tr&gt;
 &lt;/form&gt;
 </pre>
<p>so, your test case will look like this:</p>
<pre class="brush: php; title: ; notranslate">
 $browser-&gt;get('/login')-&gt;
   with('response')-&gt;begin()-&gt;
     isStatusCode(200)-&gt;
     checkElement('form input[type=&quot;text&quot;][name=&quot;signin[username]&quot;]',true)-&gt;
     setField('signin[username]', 'ram')-&gt;
     setField('signin[password]', 'test123')-&gt;
     click('Signin')-&gt;
 end()-&gt;
 /*
 * every method like end(), debug(), begin() or assert methods
 * returns back the $browser object
 */
 setHttpHeader('X-Requested-With', 'XMLHttpRequest')-&gt;
 get('/book/add')-&gt;
   with('request')-&gt;begin()-&gt;
     isParameter('module', 'Book')-&gt;
     isParameter('action', 'add')-&gt;
   end()-&gt;
 with('response')-&gt;begin()-&gt;
   isStatusCode(200)-&gt;
   checkElement('form input[type=&quot;text&quot;][name=&quot;book[book_name]&quot;]',true)-&gt;
   checkElement('form input[type=&quot;text&quot;][name=&quot;book[book_author]&quot;]',true)-&gt;
 end()-&gt;
 with('form')-&gt;begin()-&gt;
   setHttpHeader('X-Requested-With', 'XMLHttpRequest')-&gt;
   setField('book[book_name]', 'Symfony Testing')-&gt;
   setField('book[book_author]', 'Ram Sharma')-&gt;
   click('Save')-&gt;
 end()-&gt;
 with('form')-&gt;begin()-&gt;
   hasErrors(false)-&gt;
 end()-&gt;
 with('response')-&gt;begin()-&gt;
   isRedirected()-&gt;
   isStatusCode(302)-&gt;
   followRedirect()-&gt;
 end();
 </pre>
<p>Now you are able to test Form POST request, AJAX GET/POST and functional test cases for authenticated user features with Symfony's inbuilt test framework. In the end I just want to tell you that Symfony's testing framework is a very powerful tool but at times you may not find the appropriate help. So use debug() it will help you a-lot.</p>
<p>In case if you have any specific queries or problems, please let me know.</p>
]]></content:encoded>
			<wfw:commentRss>http://xebee.xebia.in/2011/07/29/symfony-functional-testing-form-post-and-ajax-request-testing/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

