<?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/"
	xmlns:georss="http://www.georss.org/georss" xmlns:geo="http://www.w3.org/2003/01/geo/wgs84_pos#" xmlns:media="http://search.yahoo.com/mrss/"
	>

<channel>
	<title>Gonzalo Ayuso &#124; Web Architect</title>
	<atom:link href="http://gonzalo123.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://gonzalo123.com</link>
	<description></description>
	<lastBuildDate>Wed, 22 May 2013 12:07:06 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.com/</generator>
<cloud domain='gonzalo123.com' port='80' path='/?rsscloud=notify' registerProcedure='' protocol='http-post' />
<image>
		<url>http://1.gravatar.com/blavatar/36e61d26ff749c3064487f5bc33ff092?s=96&#038;d=http%3A%2F%2Fs2.wp.com%2Fi%2Fbuttonw-com.png</url>
		<title>Gonzalo Ayuso &#124; Web Architect</title>
		<link>http://gonzalo123.com</link>
	</image>
	<atom:link rel="search" type="application/opensearchdescription+xml" href="http://gonzalo123.com/osd.xml" title="Gonzalo Ayuso &#124; Web Architect" />
	<atom:link rel='hub' href='http://gonzalo123.com/?pushpress=hub'/>
		<item>
		<title>Google App Engine, PHP and Silex. Setting up a Login Provider</title>
		<link>http://gonzalo123.com/2013/05/20/google-app-engine-php-and-silex-setting-up-a-login-provider/</link>
		<comments>http://gonzalo123.com/2013/05/20/google-app-engine-php-and-silex-setting-up-a-login-provider/#comments</comments>
		<pubDate>Mon, 20 May 2013 11:59:45 +0000</pubDate>
		<dc:creator>Gonzalo Ayuso</dc:creator>
				<category><![CDATA[Google App Engine]]></category>
		<category><![CDATA[silex]]></category>
		<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[gae]]></category>

		<guid isPermaLink="false">http://gonzalo123.com/?p=1688</guid>
		<description><![CDATA[How to use Google App Engine with Silex and create one Login Provider<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.com&#038;blog=6282145&#038;post=1688&#038;subd=gonzalo123&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Last week Google <a href="http://googlecloudplatform.blogspot.com.es/2013/05/ushering-in-next-generation-of.html">announced</a> the PHP support for Google App Engine (GAE). PHPStorm, the great IDE for PHP development, also <a href="http://blog.jetbrains.com/phpstorm/2013/05/support-for-google-app-engine-php-in-phpstorm/">announced</a> support for Google App Engine PHP. Because of that now is time to hack a little bit with this new toy. </p>
<p>I&#8217;ve worked in a couple of projects with Google App Engine in the past (with Python). With PHP the process is almost the same. First we need to define our application in the app.yaml file. In our example we are going to redirect all requests to main.php, where our Silex application is defined.</p>
<pre class="brush: bash; title: ; notranslate">
application: silexgae
version: 1
runtime: php
api_version: 1
threadsafe: true

handlers:
- url: .*
  script: main.php
</pre>
<p>To build a simple Silex application over Google App Engine is pretty straightforward (more info <a href="https://developers.google.com/appengine/downloads?hl=en#Google_App_Engine_SDK_for_PHP">here</a>). Because of that we&#8217;re going to go a little further. We are going to use the log-in framework provided by GAE to log-in with our Goggle account within our Silex application. In fact we can use the standard OAuth authentication process but Google provides a simple <a href="https://developers.google.com/appengine/docs/php/users/loginurls">way</a> to use our gmail account. </p>
<p>Now we&#8217;re going to build a LoginProvider to make this process simpler. Our base Silex application will be the following one:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
require_once __DIR__ . '/vendor/autoload.php';

use Silex\Application;
use Gae\LoginProvider;
use Gae\Auth;

$app = new Application();
$app-&gt;register(new LoginProvider(), array(
    'auth.onlogin.callback.url' =&gt; '/private',
    'auth.onlogout.callback.url' =&gt; '/loggedOut',
));

/** @var Auth $auth */
$auth = $app['gae.auth']();

$app-&gt;get('/', function () use ($app, $auth) {
    return $auth-&gt;isLogged() ?
        $app-&gt;redirect(&quot;/private&quot;) :
        &quot;&lt;a href='&quot; . $auth-&gt;getLoginUrl() . &quot;'&gt;login&lt;/a&gt;&quot;;
});

$app-&gt;get('/private', function () use ($app, $auth) {
    return $auth-&gt;isLogged() ?
        &quot;Hello &quot; . $auth-&gt;getUser()-&gt;getNickname() . 
          &quot; &lt;a href='&quot; . $auth-&gt;getLogoutUrl() . &quot;'&gt;logout&lt;/a&gt;&quot; :
        $auth-&gt;getRedirectToLogin();
});

$app-&gt;get('/loggedOut', function () use ($app) {
    return &quot;Thank you!&quot;;
});

$app-&gt;run();
</pre>
<p>Our LoginProvider is a simple Class that implements Silex\ServiceProviderInterface</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
namespace Gae;

require_once 'google/appengine/api/users/UserService.php';

use google\appengine\api\users\UserService;
use Gae\Auth;
use Silex\Application;
use Silex\ServiceProviderInterface;

class LoginProvider implements ServiceProviderInterface
{
    public function register(Application $app)
    {
        $app['gae.auth'] = $app-&gt;protect(function () use ($app) {
            return new Auth($app, UserService::getCurrentUser());
        });
    }

    public function boot(Application $app)
    {
    }
}
</pre>
<p>As you can see our Provider class proviedes us an instance of Gae\Auth class</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
namespace Gae;

require_once 'google/appengine/api/users/UserService.php';

use google\appengine\api\users\User;
use google\appengine\api\users\UserService;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Silex\Application;

class Auth
{
    private $user = null;
    private $loginUrl;
    private $logoutUrl;
    private $logged;

    public function __construct(Application $app, User $user=null)
    {
        $this-&gt;user = $user;

        if (is_null($user)) {
            $this-&gt;loginUrl = UserService::createLoginUrl($app['auth.onlogin.callback.url']);
            $this-&gt;logged = false;
        } else {
            $this-&gt;logged = true;
            $this-&gt;logoutUrl = UserService::createLogoutUrl($app['auth.onlogout.callback.url']);
        }
    }

    /**
     * @return RedirectResponse
     */
    public function getRedirectToLogin()
    {
        return new RedirectResponse($this-&gt;getLoginUrl());
    }
    /**
     * @return boolean
     */
    public function isLogged()
    {
        return $this-&gt;logged;
    }

    /**
     * @return string
     */
    public function getLoginUrl()
    {
        return $this-&gt;loginUrl;
    }

    /**
     * @return string
     */
    public function getLogoutUrl()
    {
        return $this-&gt;logoutUrl;
    }

    /**
     * @return \google\appengine\api\users\User|null
     */
    public function getUser()
    {
        return $this-&gt;user;
    }
}
</pre>
<p>And that&#8217;s all. Full code is available in my <a href="https://github.com/gonzalo123/silex-gae-login-provider">github</a> account and you can also use <a href="https://packagist.org/packages/gonzalo123/silex-gae-login-provider">composer</a> to include this provider within your projects.</p>
<span class='embed-youtube' style='text-align:center; display: block;'><iframe class='youtube-player' type='text/html' width='604' height='370' src='http://www.youtube.com/embed/hkW-xiSYiak?version=3&#038;rel=1&#038;fs=1&#038;showsearch=0&#038;showinfo=1&#038;iv_load_policy=1&#038;wmode=transparent' frameborder='0'></iframe></span>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gonzalo123.wordpress.com/1688/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gonzalo123.wordpress.com/1688/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.com&#038;blog=6282145&#038;post=1688&#038;subd=gonzalo123&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gonzalo123.com/2013/05/20/google-app-engine-php-and-silex-setting-up-a-login-provider/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6aa6fe484173856751a24135b4dd4586?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gonzalo123</media:title>
		</media:content>
	</item>
		<item>
		<title>Enqueue Symfony&#8217;s process components with PHP and ZeroMQ</title>
		<link>http://gonzalo123.com/2013/04/08/building-a-zeromq-enqueue-with-php/</link>
		<comments>http://gonzalo123.com/2013/04/08/building-a-zeromq-enqueue-with-php/#comments</comments>
		<pubDate>Mon, 08 Apr 2013 12:20:17 +0000</pubDate>
		<dc:creator>Gonzalo Ayuso</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[process]]></category>
		<category><![CDATA[reactor pattern]]></category>
		<category><![CDATA[sysfony]]></category>
		<category><![CDATA[ZeroMQ]]></category>

		<guid isPermaLink="false">http://gonzalo123.com/?p=1650</guid>
		<description><![CDATA[Small example playing with ZeroMQ and PHP. A simple LIFO to enqueue processes with Symfony's process component<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.com&#038;blog=6282145&#038;post=1650&#038;subd=gonzalo123&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Today I&#8217;d like to play with <a href="http://www.zeromq.org/">ZeroMQ</a>. ZeroMQ is a great tool to work with sockets. I will show you the problem that I want to solve: One web application needs to execute background processes but I need to execute those processes in order. Two users cannot execute one process at the same time. OK, if we face to this problem we can use Gearman. I&#8217;ve written  various posts about Gearman (<a href="http://gonzalo123.com/2011/03/07/watermarks-in-our-images-with-php-and-gearman/" title="Watermarks in our images with PHP and Gearman">here</a> and <a href="http://gonzalo123.com/2010/11/01/database-connection-pooling-with-php-and-gearman/" title="Database connection pooling with PHP and gearman">here</a> for example). But today I want to play with ZeroMQ.</p>
<p>I&#8217;m going to use one great library called <a href="http://reactphp.org/">React</a>. With react (reactor pattern implementation in PHP) we can do various thing. One of them are <a href="https://github.com/reactphp/zmq">ZeroMQ</a> bindings.</p>
<p>In this simple example we are going to build a simple server and client. The client will send to the server one string that the server will enqueue and executes using the Symfony&#8217;s Process component.</p>
<p>Here is the client:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
include __DIR__ . '/../vendor/autoload.php';

use Zmqlifo\Client;

$queue = Client::factory('tcp://127.0.0.1:4444');
echo $queue-&gt;run(&quot;ls -latr&quot;)-&gt;getOutput();
echo $queue-&gt;run(&quot;pwd&quot;)-&gt;getOutput();
</pre>
<p>And finally the server:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
include __DIR__ . '/../vendor/autoload.php';

use Symfony\Component\Process\Process;
use Zmqlifo\Server;

$server = Server::factory('tcp://127.0.0.1:4444');
$server-&gt;registerOnMessageCallback(function ($msg) {
    $process = new Process($msg);
    $process-&gt;setTimeout(3600);
    $process-&gt;run();
    return $process-&gt;getOutput();
});

$server-&gt;run();
</pre>
<p>You can see the working example here:<br />
<span class='embed-youtube' style='text-align:center; display: block;'><iframe class='youtube-player' type='text/html' width='604' height='370' src='http://www.youtube.com/embed/Vmyr5H4eIHc?version=3&#038;rel=1&#038;fs=1&#038;showsearch=0&#038;showinfo=1&#038;iv_load_policy=1&#038;wmode=transparent' frameborder='0'></iframe></span></p>
<p>you can check the full code of the library in <a href="https://github.com/gonzalo123/zmqlifo">github</a> and <a href="https://packagist.org/packages/gonzalo123/zmqlifo">Packagist</a>.</p>
<p><strong>UPDATE</strong><br />
As Igor Wiedler <a href="https://github.com/gonzalo123/zmqlifo/pull/1">said</a> React is not necessary here. </p>
<blockquote><p>ZMQ is used for blocking sends<br />
and blocking tasks, having an event loop does not really make much sense.</p></blockquote>
<p>github repository updated (thanks!).</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gonzalo123.wordpress.com/1650/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gonzalo123.wordpress.com/1650/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.com&#038;blog=6282145&#038;post=1650&#038;subd=gonzalo123&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gonzalo123.com/2013/04/08/building-a-zeromq-enqueue-with-php/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6aa6fe484173856751a24135b4dd4586?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gonzalo123</media:title>
		</media:content>
	</item>
		<item>
		<title>Sign-in with Twitter in a Silex application.</title>
		<link>http://gonzalo123.com/2013/03/18/sign-in-with-twitter-in-a-silex-application/</link>
		<comments>http://gonzalo123.com/2013/03/18/sign-in-with-twitter-in-a-silex-application/#comments</comments>
		<pubDate>Mon, 18 Mar 2013 12:56:50 +0000</pubDate>
		<dc:creator>Gonzalo Ayuso</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[silex]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[guzzle]]></category>
		<category><![CDATA[OAuth]]></category>
		<category><![CDATA[Twitter]]></category>

		<guid isPermaLink="false">http://gonzalo123.com/?p=1664</guid>
		<description><![CDATA[Implementing a Sign-in with Twitter in a Silex application. <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.com&#038;blog=6282145&#038;post=1664&#038;subd=gonzalo123&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I&#8217;ve working in a pet-project with Silex and I wanted to perform a Sign-in with Twitter. Implementing Sign in with Twitter is pretty straightforward and it&#8217;s also well explained in the Twitter&#8217;s developers <a href="https://dev.twitter.com/docs/auth/implementing-sign-twitter">site</a>. Now we only need to implement those HTTP client requests within PHP. We can create the REST client with <a href="http://php.net/manual/book.curl.php">curl</a> but nowadays I prefer to use the great library called <a href="http://guzzlephp.org/">Guzzle</a> to perform those kind of opperations. So let&#8217;s start.</p>
<p>The idea is to create something reusable. I don&#8217;t want to spend too much time including the Sign-in with Twitter in my proyects, so my first idea was to create a class with all the needed code and mount this class as group of Silex controllers (as it&#8217;s defined <a href="http://silex.sensiolabs.org/doc/organizing_controllers.html">here</a>). I also want to keep the class as standard as possible and avoiding the usage of any other external dependencies (except Guzzle).. </p>
<p>Imagine a simple Silex application:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
// www/index.php
include __DIR__ . &quot;/../vendor/autoload.php&quot;;

$app = new Silex\Application();
$app-&gt;get('/', function () {
    return 'Hello';
});

$app-&gt;run();
</pre>
<p>Now I want to use a Sign-in with Twitter, so I will change the application to:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
include __DIR__ . &quot;/../vendor/autoload.php&quot;;

$app = new Silex\Application();
$app-&gt;register(new Silex\Provider\SessionServiceProvider());

$consumerKey    = &quot;***&quot;;
$consumerSecret = &quot;***&quot;;

$twitterLoggin = new SilexTwitterLogin($app, 'twitter');
$twitterLoggin-&gt;setConsumerKey($consumerKey);
$twitterLoggin-&gt;setConsumerSecret($consumerSecret);
$twitterLoggin-&gt;registerOnLoggin(function () use ($app, $twitterLoggin) {
    $app['session']-&gt;set($twitterLoggin-&gt;getSessionId(), [
        'user_id'            =&gt; $twitterLoggin-&gt;getUserId(),
        'screen_name'        =&gt; $twitterLoggin-&gt;getScreenName(),
        'oauth_token'        =&gt; $twitterLoggin-&gt;getOauthToken(),
        'oauth_token_secret' =&gt; $twitterLoggin-&gt;getOauthTokenSecret()
    ]);
});

$twitterLoggin-&gt;mountOn('/login', function () {
    return '&lt;a href=&quot;/login/requestToken&quot;&gt;login&lt;/a&gt;';
});

$app-&gt;get('/', function () use ($app){
    return 'Hello ' . $app['session']-&gt;get('twitter')['screen_name'];
});

$app-&gt;run();
</pre>
<p>The application will redirects all requests (without the correct session) to the route <strong>&#8220;/login&#8221;</strong>. The login page has a simple link to the route: <strong>&#8220;/login/requestToken&#8221;</strong> (we can create a fancy template with Twig if we want, indeed). This route redirects the request to Twitter’s login page and after a successful login it will redirects back to the route that we have defined within our Twitter application. The library assumes that this callback&#8217;s url is <strong>&#8220;/login/callbackUrl&#8221;</strong>. All this default routes can be defined by the user using the proper setters of the class. </p>
<p>When the sign-in is finished the application will trigger the callback defined in <strong>registerOnLoggin</strong> function and will redirects to the route &#8220;/&#8221;. This route (called internally <strong>&#8220;redirectOnSuccess&#8221;</strong>) is also customizable with a setter.</p>
<p>And that&#8217;s all. Library available at <a href="https://github.com/gonzalo123/SilexTwitterLogin">github</a> and <a href="https://packagist.org/packages/gonzalo123/silex-twitter-login">packagist</a></p>
<pre class="brush: bash; title: ; notranslate">
{
    &quot;require&quot;: {
        &quot;gonzalo123/silex-twitter-login&quot;: &quot;dev-master&quot;
    }
}
</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gonzalo123.wordpress.com/1664/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gonzalo123.wordpress.com/1664/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.com&#038;blog=6282145&#038;post=1664&#038;subd=gonzalo123&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gonzalo123.com/2013/03/18/sign-in-with-twitter-in-a-silex-application/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6aa6fe484173856751a24135b4dd4586?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gonzalo123</media:title>
		</media:content>
	</item>
		<item>
		<title>Scaling Silex applications (part II). Using RouteCollection</title>
		<link>http://gonzalo123.com/2013/03/04/scaling-silex-applications-part-ii-using-routecollection/</link>
		<comments>http://gonzalo123.com/2013/03/04/scaling-silex-applications-part-ii-using-routecollection/#comments</comments>
		<pubDate>Mon, 04 Mar 2013 13:15:38 +0000</pubDate>
		<dc:creator>Gonzalo Ayuso</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[silex]]></category>
		<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Technology]]></category>

		<guid isPermaLink="false">http://gonzalo123.com/?p=1654</guid>
		<description><![CDATA[How to scale Silex applications using RouteCollection and YAML<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.com&#038;blog=6282145&#038;post=1654&#038;subd=gonzalo123&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>In the post <a href="http://gonzalo123.com/2013/02/11/scaling-silex-applications/" title="Scaling Silex&nbsp;applications">Scaling Silex applications</a> I wanted to organize a one Silex application. In one <a href="http://gonzalo123.com/2013/02/11/scaling-silex-applications/#comment-3834">comment</a> Igor Wiedler recommended us to use RouteCollections instead of define the routes with a Symfony&#8217;s Dependency Injection Container. Because of that I started to hack a little bit about it and here I show you my outcomes:</p>
<p>I want to build an imaginary application with silex. This application has also one Api and one little blog. I want to organize those parts. Our index.php file</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
// www/index.php
require_once __DIR__ . '/../vendor/autoload.php';

use Symfony\Component\Config\FileLocator;
use Symfony\Component\Routing\Loader\YamlFileLoader;
use Symfony\Component\Routing\RouteCollection;
use Silex\Application;

$app = new Application();

$app['routes'] = $app-&gt;extend('routes', function (RouteCollection $routes, Application $app) {
    $loader     = new YamlFileLoader(new FileLocator(__DIR__ . '/../config'));
    $collection = $loader-&gt;load('routes.yml');
    $routes-&gt;addCollection($collection);

    return $routes;
});

$app-&gt;run();
</pre>
<p>Now our routes.yml file:</p>
<pre class="brush: bash; title: ; notranslate">
# config/routes.yml

home:
  path: /
  defaults: { _controller: 'Gonzalo123\AppController::homeAction' }

hello:
  path: /hello/{name}
  defaults: { _controller: 'Gonzalo123\AppController::helloAction' }

api:
  prefix: /api
  resource: api.yml

blog:
  prefix: /blog
  resource: blog.yml
</pre>
<p>As we can see we have separated the main routing file into different files: api.yml (for the Api) and blog.yml (for the blog)</p>
<pre class="brush: bash; title: ; notranslate">
# config/api.yml

api.list:
  path:     /list
  defaults: { _controller: 'Gonzalo123\ApiController::listAction' }
</pre>
<pre class="brush: bash; title: ; notranslate">
# blog.yml

blog.home:
  path:     /
  defaults: { _controller: 'Gonzalo123\BlogController::homeAction' }
</pre>
<p>And now we can create our controllers:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
// lib/Gonzalo123/AppController.php

namespace Gonzalo123;

use Symfony\Component\HttpFoundation\Response;
use Silex\Application;

class AppController
{
    public function homeAction()
    {
        return new Response(&quot;AppController::homeAction&quot;);
    }

    public function helloAction(Application $app, $name)
    {
        return new Response(&quot;Hello&quot; . $app-&gt;escape($name));
    }
}
</pre>
<pre class="brush: php; title: ; notranslate">
&lt;?php
// lib/Gonzalo123/ApiController.php

namespace Gonzalo123;

use Symfony\Component\HttpFoundation\Response;

class ApiController
{
    public function listAction()
    {
        return new Response(&quot;AppController::listAction&quot;);
    }
}
</pre>
<pre class="brush: php; title: ; notranslate">
&lt;?php
// lib/Gonzalo123/BlogController.php

namespace Gonzalo123;

use Symfony\Component\HttpFoundation\Response;

class BlogController
{
    public function homeAction()
    {
        return new Response(&quot;BlogController::homeAction&quot;);
    }
}
</pre>
<p>And that&#8217;s all. Here also the needed dependencies within our composer.json file</p>
<pre class="brush: bash; title: ; notranslate">
{
    &quot;require&quot;:{
        &quot;silex/silex&quot;:&quot;1.0.*@dev&quot;,
        &quot;symfony/yaml&quot;:&quot;v2.2.0&quot;,
        &quot;symfony/config&quot;:&quot;v2.2.0&quot;
    },
    &quot;autoload&quot;:{
        &quot;psr-0&quot;:{
            &quot;&quot;:&quot;lib/&quot;
        }
    }
}
</pre>
<p>source code at <a href="https://github.com/gonzalo123/silexRouteCollection">github</a>.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gonzalo123.wordpress.com/1654/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gonzalo123.wordpress.com/1654/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.com&#038;blog=6282145&#038;post=1654&#038;subd=gonzalo123&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gonzalo123.com/2013/03/04/scaling-silex-applications-part-ii-using-routecollection/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6aa6fe484173856751a24135b4dd4586?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gonzalo123</media:title>
		</media:content>
	</item>
		<item>
		<title>Scaling Silex applications</title>
		<link>http://gonzalo123.com/2013/02/11/scaling-silex-applications/</link>
		<comments>http://gonzalo123.com/2013/02/11/scaling-silex-applications/#comments</comments>
		<pubDate>Mon, 11 Feb 2013 13:30:08 +0000</pubDate>
		<dc:creator>Gonzalo Ayuso</dc:creator>
				<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Symfony]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[DIC]]></category>
		<category><![CDATA[language php]]></category>
		<category><![CDATA[silex]]></category>

		<guid isPermaLink="false">http://gonzalo123.com/?p=1636</guid>
		<description><![CDATA[One Idea to scale Silex applications using Symfony's DIC to store the routes<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.com&#038;blog=6282145&#038;post=1636&#038;subd=gonzalo123&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>In my humble opinion <a href="http://silex.sensiolabs.org/">Silex</a> is great. It&#8217;s perfect to create prototypes, but when our application grows up it turns into a mess. That was what I thought until the last month, when I attended to a great <a href="http://www.slideshare.net/javier.eguiluz/silex-desarrollo-web-gil-y-profesional-con-php">talk</a> about Silex with Javier Eguiluz. OK. Scaling Silex it&#8217;s not the same than with a Symfony application, but it&#8217;s possible. </p>
<p>It&#8217;s pretty straightforward to create a Silex application with composer:</p>
<pre class="brush: bash; title: ; notranslate">
{
    &quot;require&quot;: {
        &quot;silex/silex&quot;: &quot;1.0.*&quot;
    },
    &quot;minimum-stability&quot;: &quot;dev&quot;
}
</pre>
<p>But there&#8217;s a better way. We can use the Fabien Potencier&#8217;s <a href="https://github.com/fabpot/Silex-Skeleton">skeleton</a>. With this skeleton we can organize our code better. </p>
<p>We also can use classes as controllers instead of using a closure with all the code. Igor Wiedler has a great post about this. You can read it <a href="https://igor.io/2012/11/09/scaling-silex.html">here</a>. </p>
<p>Today I&#8217;m playing with Silex and I want to show you something. Let&#8217;s start:</p>
<p>Probably you know that I&#8217;m a big fan of Symfony&#8217;s Dependency Injection Container (you can read about it <a href="http://gonzalo123.com/2012/09/03/dependency-injection-containers-with-php-when-pimple-is-not-enough/">here</a> and <a href="http://gonzalo123.com/2013/01/07/handling-several-pdo-database-connections-in-symfony2-through-the-dependency-injection-container-with-php/">here</a>), but Silex uses Pimple. In fact the Silex application extends Pimple Class. My idea is the following one:</p>
<p>In the Igor&#8217;s post we can see how to use things like that:</p>
<pre class="brush: php; title: ; notranslate">
$app-&gt;match('/video/{id}', 'Gonzalo123\ApiController::indexAction')-&gt;method('GET')-&gt;bind('video_info');
</pre>
<p>My idea is to store this information within a Service Container (we will use Symfony&#8217;s DIC). For example here we can see our routes.yml:</p>
<pre class="brush: bash; title: ; notranslate">
routes:
  video_info:
    pattern:  /video/{id}
    controller: Gonzalo123\ApiController::initAction
    requirements:
      _method:  GET
</pre>
<p>As we can see we need to implement one Extension for the alias &#8220;routes&#8221;. We only will implement the needed functions for YAML files in this example.</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

use Symfony\Component\DependencyInjection\Extension\ExtensionInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class SilexRouteExtension implements ExtensionInterface
{
    /**
     * Loads a specific configuration.
     *
     * @param array            $config    An array of configuration values
     * @param ContainerBuilder $container A ContainerBuilder instance
     *
     * @throws InvalidArgumentException When provided tag is not defined in this extension
     *
     * @api
     */
    public function load(array $config, ContainerBuilder $container)
    {

    }

    /**
     * Returns the namespace to be used for this extension (XML namespace).
     *
     * @return string The XML namespace
     *
     * @api
     */
    public function getNamespace()
    {

    }

    /**
     * Returns the base path for the XSD files.
     *
     * @return string The XSD base path
     *
     * @api
     */
    public function getXsdValidationBasePath()
    {

    }

    /**
     * Returns the recommended alias to use in XML.
     *
     * This alias is also the mandatory prefix to use when using YAML.
     *
     * @return string The alias
     *
     * @api
     */
    public function getAlias()
    {
        return &quot;routes&quot;;

    }
}
</pre>
<p>And now we only need to prepare the DIC. According to Fabien&#8217;s recommendation in his Silex skeleton, we only need to change the src/controllers.php</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;

// Set up container
$container = new ContainerBuilder();
$container-&gt;registerExtension(new SilexRouteExtension);
$loader = new YamlFileLoader($container, new FileLocator(__DIR__ . '/../config/'));
// load configuration
$loader-&gt;load('routes.yml');
$app['container'] = $container;

$app-&gt;mount('/api', include 'controllers/myApp.php');

$container-&gt;compile();

$app-&gt;error(function (\Exception $e, $code) use ($app) {
    if ($app['debug']) {
        return;
    }

    $page = 404 == $code ? '404.html' : '500.html';

    return new Response($app['twig']-&gt;render($page, array('code' =&gt; $code)), $code);
});
</pre>
<p>and now we define the config/routes.yml</p>
<pre class="brush: bash; title: ; notranslate">
routes:
  video_info:
    pattern:  /video/{videoId}
    controller: Gonzalo123\ApiController::initAction
    requirements:
      _method:  GET
</pre>
<p>And finally the magic in our controllers/myApp.php:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

$myApp = $app['controllers_factory'];

foreach ($container-&gt;getExtensionConfig('routes')[0] as $name =&gt; $route) {
    $controller = $myApp-&gt;match($route['pattern'], $route['controller']);
    $controller-&gt;method($route['requirements']['_method']);
    $controller-&gt;bind($name);
}
return $myApp;
</pre>
<p>The class for this example is: src/Gonzalo123/ApiController.php</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

namespace Gonzalo123;

use Silex\Application;
use Symfony\Component\HttpFoundation\Request;

use Symfony\Component\HttpFoundation\JsonResponse;

class ApiController
{
    public function initAction(Request $request, Application $app)
    {
        return new JsonResponse(array(1, 1, $request-&gt;get('id')));
    }
}
</pre>
<p>As you can see the idea is to use classes as controllers, define them within the service container and build the silex needed code iterating over the configuration. What do you think?</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gonzalo123.wordpress.com/1636/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gonzalo123.wordpress.com/1636/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.com&#038;blog=6282145&#038;post=1636&#038;subd=gonzalo123&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gonzalo123.com/2013/02/11/scaling-silex-applications/feed/</wfw:commentRss>
		<slash:comments>17</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6aa6fe484173856751a24135b4dd4586?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gonzalo123</media:title>
		</media:content>
	</item>
		<item>
		<title>How to configure Symfony&#8217;s Service Container to use Twitter API</title>
		<link>http://gonzalo123.com/2013/02/04/how-to-configure-symfonys-service-container-to-use-twitter-api/</link>
		<comments>http://gonzalo123.com/2013/02/04/how-to-configure-symfonys-service-container-to-use-twitter-api/#comments</comments>
		<pubDate>Mon, 04 Feb 2013 13:30:35 +0000</pubDate>
		<dc:creator>Gonzalo Ayuso</dc:creator>
				<category><![CDATA[Dependency Injection]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Symfony2]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[DIC]]></category>
		<category><![CDATA[guzzle]]></category>
		<category><![CDATA[software]]></category>
		<category><![CDATA[Symfony]]></category>
		<category><![CDATA[technology]]></category>
		<category><![CDATA[Twitter]]></category>

		<guid isPermaLink="false">http://gonzalo123.com/?p=1618</guid>
		<description><![CDATA[Using Symfony's Dependency injection container to handle Twitter API.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.com&#038;blog=6282145&#038;post=1618&#038;subd=gonzalo123&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Keeping on with the series about Symfony&#8217;s Services container (another posts <a href="http://gonzalo123.com/2012/09/03/dependency-injection-containers-with-php-when-pimple-is-not-enough/">here</a> and <a href="http://gonzalo123.com/2013/01/14/handling-several-dbal-database-connections-in-symfony2-through-the-dependency-injection-container-with-php/">here</a>), now we will use the service container to use Twitter API from a service.</p>
<p>To use Twitter API we need to handle http requests. I&#8217;ve written several post about http request with PHP (<a href="http://gonzalo123.com/2011/08/01/building-a-client-for-a-rest-api-with-php/" title="Building a client for a REST API with&nbsp;PHP.">example1</a>, <a href="http://gonzalo123.com/2010/02/06/building-a-rest-client-with-asynchronous-calls-using-php-and-curl/" title="Building a REST client with asynchronous calls using PHP and&nbsp;curl">example2</a>), but today we will use one amazing library to build clients: <a href="http://guzzlephp.org/" title="Guzzle">Guzzle</a>. Guzzle is amazing. We can easily build a Twitter client with it. There&#8217;s one example is its landing page:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
$client = new Client('https://api.twitter.com/{version}', array('version' =&gt; '1.1'));
$oauth  = new OauthPlugin(array(
    'consumer_key'    =&gt; '***',
    'consumer_secret' =&gt; '***',
    'token'           =&gt; '***',
    'token_secret'    =&gt; '***'
));
$client-&gt;addSubscriber($oauth);

echo $client-&gt;get('/statuses/user_timeline.json')-&gt;send()-&gt;getBody();
</pre>
<p>If we are working within a Symfony2 application or a PHP application that uses the Symfony&#8217;s Dependency injection container component you can easily integrate this simple script in the service container. I will show you the way that I use to do it. Let&#8217;s start:</p>
<p>The idea is simple. First we include guzzle within our composer.json and execute composer update:</p>
<pre class="brush: bash; title: ; notranslate">
    &quot;require&quot;: {
        &quot;guzzle/guzzle&quot;:&quot;dev-master&quot;
    }
</pre>
<p>Then we will create two files, one to store our Twitter credentials and another one to configure the service container:</p>
<pre class="brush: bash; title: ; notranslate">
# twitter.conf.yml
parameters:
  twitter.baseurl: https://api.twitter.com/1.1

  twitter.config:
    consumer_key: ***
    consumer_secret: ***
    token: ***
    token_secret: ***
</pre>
<pre class="brush: bash; title: ; notranslate">
# twitter.yml
parameters:
  class.guzzle.response: Guzzle\Http\Message\Response
  class.guzzle.client: Guzzle\Http\Client
  class.guzzle.oauthplugin: Guzzle\Plugin\Oauth\OauthPlugin

services:
  guzzle.twitter.client:
    class: %class.guzzle.client%
    arguments: [%twitter.baseurl%]
    calls:
      - [addSubscriber, [@guzzle.twitter.oauthplugin]]

  guzzle.twitter.oauthplugin:
    class: %class.guzzle.oauthplugin%
    arguments: [%twitter.config%]
</pre>
<p>And finally we include those files in our services.yml:</p>
<pre class="brush: bash; title: ; notranslate">
# services.yml
imports:
- { resource: twitter.conf.yml }
- { resource: twitter.yml }
</pre>
<p>And that&#8217;s all. Now we can use the service without problems:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

namespace Gonzalo123\AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function indexAction($name)
    {
        $twitterClient = $this-&gt;container-&gt;get('guzzle.twitter.client');
        $status = $twitterClient-&gt;get('statuses/user_timeline.json')
             -&gt;send()-&gt;getBody();

        return $this-&gt;render('AppBundle:Default:index.html.twig', array(
            'status' =&gt; $status
        ));
    }
}
</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gonzalo123.wordpress.com/1618/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gonzalo123.wordpress.com/1618/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.com&#038;blog=6282145&#038;post=1618&#038;subd=gonzalo123&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gonzalo123.com/2013/02/04/how-to-configure-symfonys-service-container-to-use-twitter-api/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6aa6fe484173856751a24135b4dd4586?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gonzalo123</media:title>
		</media:content>
	</item>
		<item>
		<title>Handling several DBAL Database connections in Symfony2 through the Dependency Injection Container with PHP</title>
		<link>http://gonzalo123.com/2013/01/14/handling-several-dbal-database-connections-in-symfony2-through-the-dependency-injection-container-with-php/</link>
		<comments>http://gonzalo123.com/2013/01/14/handling-several-dbal-database-connections-in-symfony2-through-the-dependency-injection-container-with-php/#comments</comments>
		<pubDate>Mon, 14 Jan 2013 12:58:28 +0000</pubDate>
		<dc:creator>Gonzalo Ayuso</dc:creator>
				<category><![CDATA[databases]]></category>
		<category><![CDATA[DBAL]]></category>
		<category><![CDATA[PDO]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Symfony2]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[dbal]]></category>
		<category><![CDATA[DIC]]></category>
		<category><![CDATA[pdo]]></category>
		<category><![CDATA[Symfony]]></category>

		<guid isPermaLink="false">http://gonzalo123.com/?p=1615</guid>
		<description><![CDATA[How to use several DBAL Database connections with Symfony2 service container.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.com&#038;blog=6282145&#038;post=1615&#038;subd=gonzalo123&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>(This post is the second part of my previous post: Handling several PDO Database connections in Symfony2 through the Dependency Injection Container with PHP. You can read it <a href="http://gonzalo123.com/2013/01/07/handling-several-pdo-database-connections-in-symfony2-through-the-dependency-injection-container-with-php/">here</a>)</p>
<p>OK. We can handle PDOs connections inside a Symfony2 application, but what happens if we prefer <a href="http://www.doctrine-project.org/projects/dbal.html">DBAL</a>. As we know <a href="http://gonzalo123.com/2011/07/11/database-abstraction-layers-in-php-pdo-versus-dbal/" title="Database abstraction layers in PHP. PDO versus DBAL">DBAL</a> is built over PDO and adds a set of &#8220;extra&#8221; features to our database connection. It&#8217;s something like PDO with steroids.</p>
<p>If we read the documentation, we will see how to use DBAL:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
$config = new \Doctrine\DBAL\Configuration();
//..
$connectionParams = array(
    'dbname' =&gt; 'mydb',
    'user' =&gt; 'user',
    'password' =&gt; 'secret',
    'host' =&gt; 'localhost',
    'driver' =&gt; 'pdo_mysql',
);
$conn = DriverManager::getConnection($connectionParams, $config);
</pre>
<p>As we can see to obtain a DBAL connection we use a factory method in DriverManager class. We can easily implements it in our service container:</p>
<pre class="brush: bash; title: ; notranslate">
# databases.yml
parameters:
  doctrine.dbal.configuration: Doctrine\DBAL\Configuration
  doctrine.dbal.drivermanager: Doctrine\DBAL\DriverManager

  database.db1:
    driver: pdo_sqlite
    memory: true
  database.db2:
    driver: pdo_pgsql
    dbname: testdb
    user: username
    password: password
    host: 127.0.0.1

services:
  dbal_configuartion:
    class: %doctrine.dbal.configuration%
  db1:
    factory_class: %doctrine.dbal.drivermanager%
    factory_method: getConnection
    arguments: [%database.db1%]
  db2:
      factory_class: %doctrine.dbal.drivermanager%
      factory_method: getConnection
      arguments: [%database.db2%]
</pre>
<p>But if we run again our example Symfony will throws us one error:</p>
<blockquote><p>RuntimeException: Please add the class to service &#8220;db1&#8243; even if it is constructed by a factory since we might need to add method calls based on compile-time checks.</p></blockquote>
<p>If we use this service container configuration outside Symfony2 application it works (remember we can use Symfony&#8217;s Dependency Injection Container outside Symfony application as a component. Example <a href="http://gonzalo123.com/2012/09/03/dependency-injection-containers-with-php-when-pimple-is-not-enough/" title="Dependency Injection Containers with PHP. When Pimple is not enough.">here</a>). But if we want to use it with Symfony2 we need to set the &#8220;class&#8221;, even here when we only need the static constructor, so we change it to:</p>
<pre class="brush: bash; title: ; notranslate">
# databases.yml
parameters:
  doctrine.dbal.configuration: Doctrine\DBAL\Configuration
  doctrine.dbal.drivermanager: Doctrine\DBAL\DriverManager

  database.db1:
    driver: pdo_sqlite
    memory: true
  database.db2:
    driver: pdo_pgsql
    dbname: testdb
    user: username
    password: password
    host: 127.0.0.1

services:
  dbal_configuartion:
    class: %doctrine.dbal.configuration%
  db1:
    class: %doctrine.dbal.drivermanager%
    factory_class: %doctrine.dbal.drivermanager%
    factory_method: getConnection
    arguments: [%database.db1%]
  db2:
    class: %doctrine.dbal.drivermanager%
    factory_class: %doctrine.dbal.drivermanager%
    factory_method: getConnection
    arguments: [%database.db2%]
</pre>
<p>And that&#8217;s all. We can use DBAL instead of PDO in our database connections. </p>
<p><strong>UPDATE:</strong></p>
<p>After publishing this post someone comment me Doctrine allows us to do it &#8220;out of the box&#8221; within Symfony with its DoctrineBundle:</p>
<p><a href="https://github.com/doctrine/DoctrineBundle/blob/master/Resources/doc/configuration.rst#doctrine-dbal-configuration" rel="nofollow">https://github.com/doctrine/DoctrineBundle/blob/master/Resources/doc/configuration.rst#doctrine-dbal-configuration</a></p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gonzalo123.wordpress.com/1615/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gonzalo123.wordpress.com/1615/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.com&#038;blog=6282145&#038;post=1615&#038;subd=gonzalo123&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gonzalo123.com/2013/01/14/handling-several-dbal-database-connections-in-symfony2-through-the-dependency-injection-container-with-php/feed/</wfw:commentRss>
		<slash:comments>5</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6aa6fe484173856751a24135b4dd4586?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gonzalo123</media:title>
		</media:content>
	</item>
		<item>
		<title>Handling several PDO Database connections in Symfony2 through the Dependency Injection Container with PHP</title>
		<link>http://gonzalo123.com/2013/01/07/handling-several-pdo-database-connections-in-symfony2-through-the-dependency-injection-container-with-php/</link>
		<comments>http://gonzalo123.com/2013/01/07/handling-several-pdo-database-connections-in-symfony2-through-the-dependency-injection-container-with-php/#comments</comments>
		<pubDate>Mon, 07 Jan 2013 14:13:24 +0000</pubDate>
		<dc:creator>Gonzalo Ayuso</dc:creator>
				<category><![CDATA[PDO]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[Symfony2]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[DIC]]></category>
		<category><![CDATA[pdo]]></category>
		<category><![CDATA[php project]]></category>
		<category><![CDATA[Symfony]]></category>

		<guid isPermaLink="false">http://gonzalo123.com/?p=1604</guid>
		<description><![CDATA[How to manage several PDO Database connections through Symfony2 service container.<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.com&#038;blog=6282145&#038;post=1604&#038;subd=gonzalo123&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>I&#8217;m not a big fan of ORMs, especially in PHP world when all dies at the end of each request. Plain SQL is easy to understand and very powerful. Anyway in PHP we have Doctrine. Doctrine is a amazing project, probably (with permission of Symfony2) the most advanced PHP project, but I normally prefer to work with SQL instead of Doctrine. </p>
<p>Symfony framework is closely coupled to Doctrine and it&#8217;s very easy to use the ORM from our applications. But as I said before I prefer not to use it. By the other hand I have another problem. Due to my daily work I need to connect to different databases (not only one) in my applications. In Symfony2 we normally configure the default database in our <strong>parameters.yml</strong> file:</p>
<pre class="brush: bash; title: ; notranslate">
# parameters.yml
parameters:
    database_driver: pdo_pgsql
    database_host: localhost
    database_port: 5432
    database_name: symfony
    database_user: username
    database_password: password
</pre>
<p>Ok. If we want to use PDO objects with different databases, we can use something like that:</p>
<pre class="brush: bash; title: ; notranslate">
# parameters.yml
parameters:
  database.db1.dsn: sqlite::memory:
  database.db1.username: username
  database.db1.password: password

  database.db2.dsn: pgsql:host=127.0.0.1;port=5432;dbname=testdb
  database.db2.username: username
  database.db2.password: password
</pre>
<p>And now create the PDO objects within our code with new \PDO():</p>
<pre class="brush: php; title: ; notranslate">
$dsn      = $this-&gt;container-&gt;getParameter('database.db1.dsn');
$username = $this-&gt;container-&gt;getParameter('database.db1.username');
$password = $this-&gt;container-&gt;getParameter('database.db1.password')

$pdo = new \PDO($dsn, $username, $password);
</pre>
<p>It works, but it&#8217;s awful. We store the database credentials in the service container but we aren&#8217;t using the service container properly. So we can do one small improvement. We will create a new configuration file called <strong>databases.yml</strong> and we will include this new file within the <strong>services.yml</strong>:</p>
<pre class="brush: bash; title: ; notranslate">
# services.yml
imports:
- { resource: databases.yml }
</pre>
<p>And create our databases.yml:</p>
<pre class="brush: bash; title: ; notranslate">
# databases.yml
parameters:
  db.class: Gonzalo123\AppBundle\Db\Db

  database.db1.dsn: sqlite::memory:
  database.db1.username: username
  database.db1.password: password

  database.db2.dsn: pgsql:host=127.0.0.1;port=5432;dbname=testdb
  database.db2.username: username
  database.db2.password: password

services:
  db1:
    class: %db.class%
    calls:
      - [setDsn, [%database.db1.dsn%]]
      - [setUsername, [%database.db1.username%]]
      - [setPassword, [%database.db1.password%]]
  db2:
    class: %db.class%
    calls:
      - [setDsn, [%database.db2.dsn%]]
      - [setUsername, [%database.db2.username%]]
      - [setPassword, [%database.db2.password%]]
</pre>
<p>As we can see we have created two new services in the dependency injection container called db1 (sqlite in memory) and db2 (one postgreSql database) that use the same class (in this case &#8216;Gonzalo123\AppBundle\Db\Db&#8217;). So we need to create our Db class:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

namespace Gonzalo123\AppBundle\Db;

class Db
{
    private $dsn;
    private $username;
    private $password;

    public function setDsn($dsn)
    {
        $this-&gt;dsn = $dsn;
    }

    public function setPassword($password)
    {
        $this-&gt;password = $password;
    }

    public function setUsername($username)
    {
        $this-&gt;username = $username;
    }

    /** @return \PDO */
    public function getPDO()
    {
        $options = array(\PDO::ATTR_ERRMODE =&gt; \PDO::ERRMODE_EXCEPTION);
        return new \PDO($this-&gt;dsn, $this-&gt;username, $this-&gt;password, $options);
    }
}
</pre>
<p>And that&#8217;s all. Now we can get a new PDO object from our service container with:</p>
<pre class="brush: php; title: ; notranslate">
$this-&gt;container-&gt;get('db1')-&gt;getPDO();
</pre>
<p>Better, isn&#8217;t it? But it&#8217;s still ugly. We need one extra class (Gonzalo123\AppBundle\Db\Db) and this class creates a new instance of PDO object (with getPDO()). Do we really need this class? the answer is no. We can change our service container to:</p>
<pre class="brush: bash; title: ; notranslate">
# databases.yml
parameters:
  pdo.class: PDO
  pdo.attr_errmode: 3
  pdo.erromode_exception: 2
  pdo.options:
    %pdo.attr_errmode%: %pdo.erromode_exception%

  database.db1.dsn: sqlite::memory:
  database.db1.username: username
  database.db1.password: password

  database.db2.dsn: pgsql:host=127.0.0.1;port=5432;dbname=testdb
  database.db2.username: username
  database.db2.password: password

services:
  db1:
    class: %pdo.class%
    arguments:
      - %database.db1.dsn%
      - %database.db1.username%
      - %database.db1.password%
      - %pdo.options%
  db2:
    class: %pdo.class%
    arguments:
      - %database.db2.dsn%
      - %database.db2.username%
      - %database.db2.password%
      - %pdo.options%
</pre>
<p>Now we don&#8217;t need getPDO() and we can get the PDO object directly from service container with:</p>
<pre class="brush: php; title: ; notranslate">
$this-&gt;container-&gt;get('db1');
</pre>
<p>And we can use something like this within our controllers (or maybe better in models):</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php

namespace Gonzalo123\AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class DefaultController extends Controller
{
    public function indexAction($name)
    {
        // this code should be out from controller, in a model object.
        // It is only an example
        $pdo = $this-&gt;container-&gt;get('db1');
        $pdo-&gt;exec(&quot;CREATE TABLE IF NOT EXISTS messages (id INTEGER PRIMARY KEY, title TEXT, message TEXT)&quot;);
        $pdo-&gt;exec(&quot;INSERT INTO messages(id, title, message) VALUES (1, 'title', 'message')&quot;);
        $data = $pdo-&gt;query(&quot;SELECT * FROM messages&quot;)-&gt;fetchAll();
        //

        return $this-&gt;render('AppBundle:Default:index.html.twig', array('usuario' =&gt; $data));
    }
}
</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gonzalo123.wordpress.com/1604/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gonzalo123.wordpress.com/1604/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.com&#038;blog=6282145&#038;post=1604&#038;subd=gonzalo123&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gonzalo123.com/2013/01/07/handling-several-pdo-database-connections-in-symfony2-through-the-dependency-injection-container-with-php/feed/</wfw:commentRss>
		<slash:comments>6</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6aa6fe484173856751a24135b4dd4586?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gonzalo123</media:title>
		</media:content>
	</item>
		<item>
		<title>Multiple inheritance with PHP and Traits</title>
		<link>http://gonzalo123.com/2012/12/17/multiple-inheritance-with-php-and-traits/</link>
		<comments>http://gonzalo123.com/2012/12/17/multiple-inheritance-with-php-and-traits/#comments</comments>
		<pubDate>Mon, 17 Dec 2012 13:27:05 +0000</pubDate>
		<dc:creator>Gonzalo Ayuso</dc:creator>
				<category><![CDATA[php]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[Multiple inheritance]]></category>
		<category><![CDATA[traits]]></category>

		<guid isPermaLink="false">http://gonzalo123.com/?p=1591</guid>
		<description><![CDATA[How to emulate multiple  inheritance with PHP and Traits<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.com&#038;blog=6282145&#038;post=1591&#038;subd=gonzalo123&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Multiple inheritance isn&#8217;t allowed in PHP. With Python we can do things like that:</p>
<pre class="brush: python; title: ; notranslate">
class ClassName(Base1, Base2):
    ....
</pre>
<p>That&#8217;s no possible with PHP (in Java is not possible either), but today we can do something similar (is not the exactly the same) with <strong>Traits</strong>. Let me explain that: Instead of classes we can create Traits:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
trait Base1
{
    public function hello1($name)
    {
        return &quot;Hello1 {$name}&quot;;
    }
} 

trait Base2
{
    public function hello2($name)
    {
        return &quot;Hello2 {$name}&quot;;
    }
} 
</pre>
<p>And now we can use those traits (instead of to extend multiple classes)</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
class ClassName
{
    use Base1, Base2;
} 
</pre>
<p>The main reason because multiple inheritance isn&#8217;t allowed in PHP, Java and another languages is is due to the collisions. If we extends from two classes with the same method, which is the good one?<br />
Python solves this problem with a easy solution: The first one is the good one:</p>
<pre class="brush: python; title: ; notranslate">
class Base1:
    def hello1(self, name):
        return &quot;Hello1 &quot; + name

class Base2:
    def hello1(self, name):
        return &quot;Hello2 &quot; + name

class ClassName(Base1, Base2):
    pass
c = ClassName()
print c.hello1(&quot;Gonzalo&quot;)
</pre>
<p>Will output &#8220;Hello1 Gonzalo&#8221; but if change the inheritance order to:</p>
<pre class="brush: python; title: ; notranslate">
class ClassName(Base2, Base1):
    pass
</pre>
<p>The output will be &#8220;Hello2 Gonzalo&#8221;</p>
<p>Traits in PHP doesn&#8217;t solve the problem &#8220;out of the box&#8221;. If we use the following script:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
trait Base1
{
    public function hello1($name)
    {
        return &quot;Hello1 {$name}&quot;;
    }
}

trait Base2
{
    public function hello1($name)
    {
        return &quot;Hello2 {$name}&quot;;
    }
}

class ClassName
{
    use Base1, Base2;
}

$class = new ClassName();
echo $class-&gt;hello1(&quot;Gonzalo&quot;);

</pre>
<p>Our script will throw a Fatal error:</p>
<p><em>PHP Fatal error: Trait method hello1 has not been applied, because there are collisions with other trait methods on ClassName on line 23</em></p>
<p>If we want to avoid collisions, we need to describe explicitly what function we will use. It&#8217;s not difficult:</p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
trait Base1
{
    public function hello1($name)
    {
        return &quot;Hello1 {$name}&quot;;
    }
}

trait Base2
{
    public function hello1($name)
    {
        return &quot;Hello2 {$name}&quot;;
    }
}

class ClassName
{
    use Base1, Base2 {
        Base1::hello1 insteadof Base2;
    }
}

$class = new ClassName();
echo $class-&gt;hello1(&quot;Gonzalo&quot;);
</pre>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gonzalo123.wordpress.com/1591/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gonzalo123.wordpress.com/1591/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.com&#038;blog=6282145&#038;post=1591&#038;subd=gonzalo123&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gonzalo123.com/2012/12/17/multiple-inheritance-with-php-and-traits/feed/</wfw:commentRss>
		<slash:comments>8</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6aa6fe484173856751a24135b4dd4586?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gonzalo123</media:title>
		</media:content>
	</item>
		<item>
		<title>Sending sockets from PostgreSQL triggers with Python</title>
		<link>http://gonzalo123.com/2012/11/26/sending-sockets-from-postgresql-triggers-with-python/</link>
		<comments>http://gonzalo123.com/2012/11/26/sending-sockets-from-postgresql-triggers-with-python/#comments</comments>
		<pubDate>Mon, 26 Nov 2012 13:01:13 +0000</pubDate>
		<dc:creator>Gonzalo Ayuso</dc:creator>
				<category><![CDATA[node.js]]></category>
		<category><![CDATA[php]]></category>
		<category><![CDATA[PostgreSQL]]></category>
		<category><![CDATA[Python]]></category>
		<category><![CDATA[Technology]]></category>
		<category><![CDATA[nodejs]]></category>
		<category><![CDATA[postgresql]]></category>

		<guid isPermaLink="false">http://gonzalo123.com/?p=1564</guid>
		<description><![CDATA[How to send sockets from PostgreSQL database triggers with Python<img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.com&#038;blog=6282145&#038;post=1564&#038;subd=gonzalo123&#038;ref=&#038;feed=1" width="1" height="1" />]]></description>
				<content:encoded><![CDATA[<p>Picture this: We want to notify to one external service each time that one record is inserted in the database. We can find the place where the insert statement is done and create a TCP client there, but: What happens if the application that inserts the data within the database is a legacy application?, or maybe it is too hard to do?. If your database is PostgreSQL it&#8217;s pretty straightforward. With the &#8220;<a href="http://www.postgresql.org/docs/9.2/static/plpgsql.html">default</a>&#8221; procedural language of PostgreSQL (<strong>pgplsql</strong>) we cannot do it, but PostgreSQL allows us to use more procedural languages than plpgsql, for example <a href="http://www.postgresql.org/docs/9.2/static/plpython.html">Python</a>. With <strong>plpython</strong> we can use sockets in the same way than we use it within Python scripts. It&#8217;s very simple. Let me show you how to do it.</p>
<p>First we need to create one plpython with our TCP client</p>
<pre class="brush: python; title: ; notranslate">
CREATE OR REPLACE FUNCTION dummy.sendsocket(msg character varying, host character varying, port integer)
  RETURNS integer AS
$BODY$
  import _socket
  try:
    s = _socket.socket(_socket.AF_INET, _socket.SOCK_STREAM)
    s.connect((host, port))
    s.sendall(msg)
    s.close()
    return 1
  except:
    return 0
$BODY$
  LANGUAGE plpython VOLATILE
  COST 100;
ALTER FUNCTION dummy.sendsocket(character varying, character varying, integer)
  OWNER TO username;
</pre>
<p>Now we create the trigger that use our socket client.</p>
<pre class="brush: python; title: ; notranslate">
CREATE OR REPLACE FUNCTION dummy.myTriggerToSendSockets()
RETURNS trigger AS
$BODY$
   import json
   stmt = plpy.prepare(&quot;select dummy.sendSocket($1, $2, $3)&quot;, [&quot;text&quot;, &quot;text&quot;, &quot;int&quot;])
   rv = plpy.execute(stmt, [json.dumps(TD), &quot;host&quot;, 26200])
$BODY$
LANGUAGE plpython VOLATILE
COST 100;
</pre>
<p>As you can see in my example we are sending all the record as a JSON string in the socket body.</p>
<p>And finally we attach the trigger to one table (or maybe we need to do it to more than one table) </p>
<pre class="brush: sql; title: ; notranslate">
CREATE TRIGGER myTrigger
  AFTER INSERT OR UPDATE OR DELETE
  ON dummy.myTable
  FOR EACH ROW
  EXECUTE PROCEDURE dummy.myTriggerToSendSockets();
</pre>
<p>And that&#8217;s all. Now we can use one simple TCP socket server to handle those requests. Let me show you different examples of TCP servers with different languages. As we can see all are different implementations of <a href="http://en.wikipedia.org/wiki/Reactor_pattern">Reactor</a> pattern. We can use, for example:</p>
<p><strong>node.js:</strong></p>
<pre class="brush: jscript; title: ; notranslate">
var net = require('net');

var host = 'localhost';
var port = 26200;

var server = net.createServer(function (socket) {
    socket.on('data', function(buffer) {
        // do whatever that we want with buffer
    });
});

server.listen(port, host);
</pre>
<p><strong>python (with <a href="http://twistedmatrix.com/trac/">Twisted</a>):</strong></p>
<pre class="brush: python; title: ; notranslate">
from twisted.internet import reactor, protocol

HOST = 'localhost'
PORT = 26200

class MyServer(protocol.Protocol):
    def dataReceived(self, data):
        # do whatever that we want with data
        pass

class MyServerFactory(protocol.Factory):
    def buildProtocol(self, addr):
        return MyServer()

reactor.listenTCP(PORT, MyServerFactory(), interface=HOST)
reactor.run()
</pre>
<p>(I know that we can create the Python&#8217;s TCP server without Twisted, but if don&#8217;t use it maybe someone will angry with me. Probably he is angry right now because I put the node.js example first <img src='http://s0.wp.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> )</p>
<p><strong>php (with <a href="https://github.com/reactphp/react">react</a>): </strong></p>
<pre class="brush: php; title: ; notranslate">
&lt;?php
include __DIR__ . '/vendor/autoload.php';

$host = 'localhost';
$port = 26200;

$loop   = React\EventLoop\Factory::create();
$socket = new React\Socket\Server($loop);

$socket-&gt;on('connection', function ($conn) {
    $conn-&gt;on('data', function ($data) {
        // do whatever we want with data
        }
    );
});

$socket-&gt;listen($port, $host);
$loop-&gt;run();
</pre>
<p>You also can use <a href="http://gonzalo123.com/2010/05/23/building-network-services-with-php-and-xinetd/" title="Building network services with PHP and xinetd">xinet.d</a> to handle the TCP inbound connections.</p>
<br />  <a rel="nofollow" href="http://feeds.wordpress.com/1.0/gocomments/gonzalo123.wordpress.com/1564/"><img alt="" border="0" src="http://feeds.wordpress.com/1.0/comments/gonzalo123.wordpress.com/1564/" /></a> <img alt="" border="0" src="http://stats.wordpress.com/b.gif?host=gonzalo123.com&#038;blog=6282145&#038;post=1564&#038;subd=gonzalo123&#038;ref=&#038;feed=1" width="1" height="1" />]]></content:encoded>
			<wfw:commentRss>http://gonzalo123.com/2012/11/26/sending-sockets-from-postgresql-triggers-with-python/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
	
		<media:content url="http://0.gravatar.com/avatar/6aa6fe484173856751a24135b4dd4586?s=96&#38;d=identicon&#38;r=G" medium="image">
			<media:title type="html">gonzalo123</media:title>
		</media:content>
	</item>
	</channel>
</rss>
