How to Install Symfony2 in a VPS (2.0 and 2.1)

ServerGrove likes the phpperu.org community. We were able to make it to symfonyLive in San Francisco and met with them too. Here is a how-to on how to deploy symfony2 applications into a VPS and can be of course adapted to fit any other VPS.

I am thankful to the Lord Jesus Christ for all these opportunities to meet with a lot of people on the past weeks and also pondered my time in San Francisco. San Francisco had a stark contrast, very big in IT and focused in business, but at the same time there were people starving of meaningful and lasting relationships and too busy to realize life is more than just business. The needy could be the lonely billionaire going to a wild party just because there is nothing else to do, or the poor on the streets whose life in a too high tech city is too lonely to stay sane. I am very glad to see in this midst the church community open and reaching out to everybody in love and with the Gospel of grace to them. I hope anyone would ponder life in all its aspects and also would give the time to ponder the great Gospel of grace.

Without further ado, let’s install our symfony 2.0 and 2.1 default app into a VPS100.

Log into your cpanel `https://control.servergrove.com/login` with your email and password provided:

After we click on the link for the shown server we will be redirected to our server panel or be prompted to build our server if we have not done it already. There is also a tab to rebuild the server with different OS options as shown:

I was advised to go for the `Ubuntu 11.04 x86_64 – PHP 5.3.x – 64Bit (recommended)` option which had already php installed on it and had my favorite stable system built for 64 bit architecture. I could then upgrade to php 5.4 with this base since that is the configuration I was after. Your shiny dashboard would now look like the following:

Up to here we have setup the server, it has default services ready for you like `apache, cron, mysql, php, ssh, and a syslog`. All of these services come ready running and preconfigured with defaults. Should you need to enable them to start by default on-boot just tick the checkbox next to its description.

For the ssh service we can see that we have to connect through port `22123` and with our IP address (for me 69.195.222.35) from the dashboard previous screen we can start configuring how we are going to connect to our box to setup our first symfony2 app. So to that now we turn. If you forgot the root password like me then just head to the dashboard website, click on *System Users* tab on the left, then click on *edit* root user and provide new root password. It is blazing fast to change the root password of the box. Now do:

ssh root@69.195.222.35 -p 22123

First of all we need a domain and we can easily create this from the Server Groove’s Control Panel by going under “Domains >> Add Domain”. We can type an example domain like ‘phpperu.org’ or similar to test our first deploy. There will always be a preview link so you don’t have to worry at this time about registering this domain if you have not done that yet.

After creation we notice the control panel has created for us a virtual host and is already enabled:

// /etc/apache2/sites-enabled/phpperu.org
### File generated automatically by ServerGrove Control Panel. Do not edit manually as changes will be overwritten.
### If you need to enter custom directives do it below between the lines defined specially for this.
### If you want to avoid ServerGrove Control Panel writing to this file, change the following setting to 0 or remove the line completely.
### sgcontrol.enabled=1

 
<VirtualHost *:80>
        CustomLog /var/log/apache2/phpperu.org-access.log combined
        DocumentRoot /var/www/vhosts/phpperu.org/httpdocs
        ServerName phpperu.org
        ServerAlias www.phpperu.org phpperu.org.35.69-195-222.groveurl.com
        DirectoryIndex index.php
 
 
### sgcontrol.custom.config.start

### sgcontrol.custom.config.end
</VirtualHost>

Notice we can customize our vhost further but we need to switch the value `sgcontrol.enabled` to 0 to prevent the control panel from overwriting this file.

Here we will start installing our symfony2 app:

// go to folder the control panel generated and remove it
cd /var/www/vhosts/
rm -rf phpperu.org/
 
// create project from Symfony2 Standard Edition
composer create-project symfony/framework-standard-edition phpperu.org/
 
// here modify app/config/parameters.yml | parameters.ini
 
// run symfony commands to create database
php app/console doctrine:database:create
 
// switch ownership to apache2 web user
sudo chown -R www-data:www-data * .*
 
// grant access to cache and logs
sudo chmod -R 777 app/cache app/logs

Then go again back to the Control Panel and under `services / server.phpperu.org / domains / phpperu.org / web hosting` page look for the tab `General` and row `Domain`. There should be a `settings` button towards the right side. Clicking on it will allow you to set a new document root directory. Just change it from `/var/www/vhosts/phpperu.org/httpdocs` to `/var/www/vhosts/phpperu.org/web` as we are dealing with a symfony2 project which serves pages through the front controller app.php or index.php under `web` folder. Notice: Because you have removed the old folder `httpdocs` in the previous steps the information on the form to change the directory could take a little longer to load but the information will load if you want a bit longer.
If we now go to the url provided on the control panel to test (for me is `http://phpperu.org.35.69-195-222.groveurl.com/` + `app_dev.php`) then we should have on our browser:

Now in order to demo a functioning site we comment out the app_dev.php lines that prevent from running the kernel:

// edit it with: root@server:/var/www/vhosts/phpperu.org# nano web/app_dev.php
/*if (isset($_SERVER['HTTP_CLIENT_IP'])
    || isset($_SERVER['HTTP_X_FORWARDED_FOR'])
    || !in_array(@$_SERVER['REMOTE_ADDR'], array(
        '127.0.0.1',
        '::1',
    ))
) {
    header('HTTP/1.0 403 Forbidden');
    exit('You are not allowed to access this file. Check '.basename(__FILE__).' for more information.');
}*/

Once commented out we get the default `dev` route:

Warning: You should remove the commenting above and disallow thereby completely the access to app_dev.php as having this accessible online renders your file very vulnerable. Please understand that this is only to demo that the site has been properly installed. If you instead of allowing access to `app_dev.php` want to work with what you have on `app.php` for the symfony-standard version that we have installed then what you need to do to get a quick default working site is the following:

// 1. move `AcmeDemoBundle` from test, dev section to prod section on your app/AppKernel.php
            new Acme\DemoBundle\AcmeDemoBundle(),
// 2. add routing entries to app/config/routing.yml
_welcome:
    pattern:  /
    defaults: { _controller: AcmeDemoBundle:Welcome:index }
 
_demo_secured:
    resource: "@AcmeDemoBundle/Controller/SecuredController.php"
    type:     annotation
 
_demo:
    resource: "@AcmeDemoBundle/Controller/DemoController.php"
    type:     annotation
    prefix:   /demo
// 3. hard flush your cache
rm -rf app/cache/*
// 4. retry your browser on just / or `app.php` and it should work. The only difference is that it will not show the second tile for configuration.

For the symfony2.0 case it is as easy as the 2.1 version depicted above. The only difference is that instead of `symfony-standard` we will install the `knplabs/symfony-with-composer` through cloning as follows:

cd /var/www/vhosts/
git clone git://github.com/cordoval/symfony-with-composer.git phpperu.org/
cd phpperu.org/
git checkout bugfix/minimumStability
php bin/vendors install

Test Symfony2 GUI Apps in Windows7 with IE8 and IE9 The Right Way!

Ever wanted to browse your symfony2 apps from the point of view of those old stiff corporates that don’t know how to install better programs?
Fasten your seat belts!

Update: The right way ended up being https://github.com/xdissent/ievms (thanks @helios_ag)

Go first and download the legal images from this link: http://www.microsoft.com/en-us/download/details.aspx?id=11575
To aid you in your selection just download all 3 by 3 because i am sure you will have corruption problems. If the exe fails when you run it on your ubuntu just remove the files and download the again and again until you get them to work. Don’t be discouraged just try it and defeat it.

Once you grab your images and run the exe for each of the IE7, IE8, IE9 that you want to install (shame on you if IE6), you should get two files for each set, namely a Win7_IE8.vmc and a Win7_IE8.vhd for the IE8 version for instance. I will assume you have installed the latest virtualbox software from the ubuntu software center in your ubuntu. Run that and create a box and init the box with your already existent disk image, yes the vhd file.

After your box is all set and running you would ask yourself how to see my symfony2 app from the virtual box guest browser (yes this is the windows 7 with IE8 or IE9, etc). First follow and make sure the pinging works between the guest browsing the app and the host serving the app through apache or other.
Troubleshot tips, pinging from guest box to the host and from host to guest box:

// from guest windows box
ping 192.168.1.34 // IP address of the ubuntu host
// from ubuntu box
ping 192.168.1.36 // IP address of the virtual box

Step1: Edit your hosts on your windows box to include an entry pointing to your Ubuntu’s IP address (mine is 192.168.1.34) the one running apache and serving the symfony2 app:

// 127.0.0.1   localhost
129.168.1.34   myapp.local

Step2: Set your virtualbox network settings of the windows guest to Bridge and set it to allow on the select box to ALL VMS and what not.
Step3: Drop your defense iptables to allow for the guest to access pages served by the host:

// this works:
~ sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT
// thanks to @helios_ag who recommended these:
~ ufw allow http
~ ufw allow 80

Then open your browser on your windows guest virtual box and type:

http://myapp.local/app_dev.php

And of course you will get the one line warning. But from here on you know what to do if you are a symfony2 guy.
If you get errors make sure you troubleshoot and drop your firewalls allowing for the access with iptable settings as above.

I hope this has helped you. I thank God for having such good friends in the community.
Also I make sure to mention that all of this is undeserved because I cannot repay God’s grace.
Lastly, if you would like to see me at SymfonyLive in San Francisco and would like to contribute towards my air ticket 1800$ ($100 already raised) please follow this link: http://bit.ly/9xbyzM. The flight is very expensive but I am so eager to go and thanks for all that are already supporting me, we will have so much learning there. Looking forward to meet the community you!

Getting your Symfony2 Team On Board With Git Line Endings!

Lately I ran into this help page from github here.
The main problem that this solves and the one I ran into was that I made some modifications to a file in a git repository and to my surprise I was met by an ugly scenario when doing `git diff` showing strange characters `^M` which were showing red and ugly:

I tried in vain to get rid of these windows format line endings. Then was redirected to the link above but just initially set my .gitconfig to no effect.
In order to solve this there were two options: (1) waiting until project manager would make a transition from an unclean repo to a reformatted one, or (2) just cope with it and either run a nice utility called `dos2unix` (you can install it by `sudo apt-get install dos2unix on ubuntu) to filter those characters, stash my changes, then commit the whole file changes after the dos2unix command, yes this command changes all the file, then apply my stashed changes, then commit again. The latter solution is not very nice as there is an ugly bump in history as to who change what in the file. So I just went ahead and made my changes and accept for one only time to see those weird characters on my `git diff`. The reason why those characters were there was that for that particular repository on some version at some point the file got edited in Microsoft products by someone using Windows OS.

The morale of the story is that in order to avoid these problems with strange end of line characters we could just make our project totally independent of what the OS of the team’s developers use. The `.gitattributes` file accomplishes this by telling git what to do or how to behave when checking out these files. Following is a `.gitattributes` I wrote in order to accomplish this for a symfony2 generic project. It is my hope that people would contribute to it and would improve it. Here is the https://github.com/cordoval/symfony2-gitattributes to fork and PR and following is a excerpt:

# Set default behaviour, in case users don't have core.autocrlf set.
* text=auto
 
# Explicitly declare text files we want to always be normalized and converted 
# to native line endings on checkout.
*.php text
*.txt text
*.ini text
//...
*.js text
*.css text
*.cache text
*.meta text
*.phar text
app/console text
console text
vendors text
.gitignore text
// ...
 
# Denote all files that are truly binary and should not be modified.
*.png binary
*.gif binary
*.jpg binary
*.db binary
*.jar binary
*.ico binary
.gitkeep binary

It has inline comments that explain what each section does. Please from now on make sure you include this file in your symfony2 project.
If you liked this and want to support me going to symfonyLive in San Francisco please donate.

Interview To PHPPeru

Republish from source:

En la última edición del programa ‘Web Inc.’, que conducen Germán Martinez y Antonio Ognio por La MulaTV, estuvimos con Luis Córdova, experto desarrollador que lidera la comunidad PHP Perú.

Desde mediados de los noventas, PHP es una de las tecnologías más populares para la construcción de sitios web del lado del servidor.

La comunidad PHP Perú cuenta actualmente con más de 50 miembros que participan de reuniones presenciales y virtuales. Sus integrantes discuten, no solo de PHP, sino del conjunto de otras habilidades esenciales para los desarrolladores tales como: patrones de diseño, testing, control de versiones, paquetes entre otros.

Luis Córdova señaló que, entre las opciones de los programadores, también está la participación en comunidad, ayudando a otros y aprendiendo de los que saben más que uno. “Existe la necesidad de que el peruano se abra y participe con el exterior. El desarrollo va de la mano con la comunidad”, afirmó.

Posteriormente se conversó sobre Symfony 2, un framework full stack para PHP de última generación. Este sofware se construye sobre la base de un gran número de componentes, que están siendo usados como piezas fundacionales por los sistemas de manejo de contenido (SMC) más recientes como Drupal 8. Esto facilita la inter- operatividad con otras soluciones y el re-uso del código.

Finalmente, Córdova animó a que los programadores entren en la comunidad para aprender a contribuir con código a proyectos como Symfony 2 y otros. De esta manera serían partícipes de una comunidad global de programadores a través de internet y en eventos especializados. La comunidad pretende la participación enfocada el desarrollo: “Mejor hacer las herramientas que usarlas. Es importante la participación en development más que modificar o tomar algo ya hecho”, concretó .

Para más información:

Web: www.phpperu.org
Twitter: @php_peru
Facebook: http://www.facebook.com/pages/PHP-Per%C3%BA/92445137292
Grupo de google: https://groups.google.com/forum/?fromgroups#!forum/phpperu

I give thanks to the Lord for the undeserved grace and opportunity to get to talk on php and the community here.
Thanks for all the friends that make this possible.