Archive for 2012

Some ways to get value from request in Symfony2

April 15th, 2012 | admin

In symfony2, if you want to get value from request, you have many ways:

forst, bind request to form, then you can use the entity, official document has details.

If you are using formtype, there is another two ways to get value,

first:

$postData = $request->request->get('slackiss_bundle_qingbundle_registertype');
$name_value = $postData['email'];

second:

$email = = $form["email"]->getData();

or

$defaultData = array('message' => 'Type your message here');
$form = $this->createFormBuilder($defaultData)
->add('name', 'text')
->add('email', 'email')
->add('message', 'textarea')
->getForm();

if ($request->getMethod() == 'POST') {
$form->bindRequest($request);

// data is an array with "name", "email", and "message" keys
$data = $form->getData();
}

If you do not use formtype, I mean, you are not using {{form_widget}}, you can get values:


echo $request->request->get('email');

About $request, the code is like:

public function doAction(Request $request)
{
}

or

$request = $this->getRequest();

Some resource to learn mootools

March 1st, 2012 | admin

First of all, docs.mootools.net

You can not leave this website away: http://www.mootorial.com/

I like the book: http://www.apress.com/9781430209836

Linux System monitor tools

February 22nd, 2012 | admin

#ps -ef|grep http|wc -l

#cat /proc/loadavg

#netstat -ant | grep :80 | wc -l

#top

#pmap

My Big Cat.

February 19th, 2012 | admin

My Cat, much bigger than you know. About 9.11KG at most!

Install PostgreSQL on OpenSuse 12.1

February 6th, 2012 | admin

First,

$sudo zypper install postgresql postgresql-server pgadmin3

Start server

$sudo rcpostgresql start

Change password for postgres user

$sudo postgres -c psql postgres
ALTER USER postgres WITH PASSWORD 'postgres';
\q

Error!

“IDENT authentication failed for user”

Hence, if you do not use IDENT, edit the /var/lib/pgsql/data/pg_hba.conf file and change “ident” to “md5″. Say, for instance, the lines below

local all all ident
host all all 127.0.0.1/32 ident
host all all ::1/128 ident

to

local all all md5
host all all 127.0.0.1/32 md5
host all all ::1/128 md5

Once done,restart postgreSQL as follows:

opensuse:~ # rcpostgresql restart

Create and Delete users

To create an user

opensuse:~ # su postgres

postgresql@opensuse:~> createuser -D

for user with password

postgresql@opensuse:~> createuser -D -p

To delete user

postgresql@opensuse:~> dropuser

Installing Oracle (sun) Java 1.7u2 openSUSE 12.1

February 6th, 2012 | admin

Download the RPM version of Java from www.oracle.com (in my case I downloaded 1.7u1).

The one I downloaded was: jdk-7u2-linux-i586.rpm

Install the jdk with yast2, zypper, or by double clicking the rpm within dolphin or nautilus:

sudo zypper in jdk-7u2-linux-i586.rpm -y

Now you have to setup the alternatives so you can use switch between Iced Tea, which is default, and the Oracle Java.

First install the alternative:

sudo /usr/sbin/update-alternatives --install "/usr/bin/java" "java" "/usr/java/jdk1.7.0_02/bin/java" 40

Now install the alternative for your browser plugin:

sudo /usr/sbin/update-alternatives --install "/usr/lib/browser-plugins/javaplugin.so" "javaplugin" "/usr/java/jdk1.7.0_02/jre/lib/i386/libnpjp2.so" 40

Note: the first quotes are pointing to the path, the the name of the alternative script, and the 3rd is the location to point to. The numbers at the end is the priority in case it was set to automode.

Now you have to configure the alternatives, first we’ll do java:

sudo /usr/sbin/update-alternatives java

Choose the number associated with /usr/java/jdk1.7.0_01/bin/java, in my case it was 1.

Now lets configure javaplugin:

sudo /usr/sbin/update-alternatives javaplugin

Choose the number associated with /usr/java/jdk1.7.0_01/jre/lib/i386/libnpjp2.so, in my case it was 1.

First, for the haters. I do linux for a living on servers, so I’m used to sudo, and that’s why I use it on my laptop.

Second, also for the other haters. Yes, I could have added some super high priority and kept it on auto, but I like doing it manually.

For the rest, you can check to see what you currently have set by running:

/usr/sbin/update-alternatives --query (or --display) java (or javaplugin)

You can test your java at oracles website:

Improve Battery Management for Linux(OpenSuse12.1)

February 4th, 2012 | admin

Thanks to this article:

 

openSUSE 11.3 und höher

Zur Installation von TLP auf openSUSE müssen die folgenden Schritte in einer Root-Shell ausgeführt werden.

Hinzufügen von Repositories:

openSUSE 11.3

zypper ar -f <a href="http://download.opensuse.org/repositories/home:/cdersch:/TLP/openSUSE_11.3/home:cdersch:TLP.repo" rel="nofollow">http://download.opensuse.org/repositories/home:/cdersch:/TLP/openSUSE_11.3/home:cdersch:TLP.repo</a>

Falls Contrib Repo noch nicht aktiv:

zypper ar -f <a href="http://download.opensuse.org/repositories/openSUSE:/11.3:/Contrib/standard/openSUSE:11.3:Contrib.repo" rel="nofollow">http://download.opensuse.org/repositories/openSUSE:/11.3:/Contrib/standard/openSUSE:11.3:Contrib.repo</a>

openSUSE 11.4

zypper ar -f <a href="http://download.opensuse.org/repositories/home:/cdersch:/TLP/openSUSE_11.4/home:cdersch:TLP.repo" rel="nofollow">http://download.opensuse.org/repositories/home:/cdersch:/TLP/openSUSE_11.4/home:cdersch:TLP.repo</a>

Falls Contrib Repo noch nicht aktiv:

zypper ar -f <a href="http://download.opensuse.org/repositories/openSUSE:/11.4:/Contrib/standard/openSUSE:11.4:Contrib.repo" rel="nofollow">http://download.opensuse.org/repositories/openSUSE:/11.4:/Contrib/standard/openSUSE:11.4:Contrib.repo</a>

openSUSE 12.1

zypper ar -f <a href="http://download.opensuse.org/repositories/home:/cdersch:/TLP/openSUSE_12.1/home:cdersch:TLP.repo" rel="nofollow">http://download.opensuse.org/repositories/home:/cdersch:/TLP/openSUSE_12.1/home:cdersch:TLP.repo</a>

Falls Contrib Repo noch nicht aktiv:

zypper ar -f <a href="http://download.opensuse.org/repositories/openSUSE:/Factory:/Contrib/openSUSE_12.1/openSUSE:Factory:Contrib.repo" rel="nofollow">http://download.opensuse.org/repositories/openSUSE:/Factory:/Contrib/openSUSE_12.1/openSUSE:Factory:Contrib.repo</a>

Paketquellen aktualisieren:

zypper ref

Folgende Pakete sind zu installieren:

  • tlp (TLP Repo)
  • tp_smapi-kmp-desktop (Contrib Repo) – optional nur für ThinkPads, ermöglicht das Einstellen der Akkuladeschwellen und erweiterte Statusanzeigen.

Hinweis: Paketname muss ggf. in tp_smapi-kmp-VARIANTE angepaßt werden, die Kernelvariante lässt sich mit uname -r ermitteln.

  • smartmontools (openSUSE Repo) – optional, ermöglicht die Anzeige von SMART-Daten für die Festplatte(n) durch tlp-stat.
  • ethtool (openSUSE Repo)- optional, ermöglicht es Wake On LAN zu deaktivieren.
  • powertop (openSUSE Repo) – optional, zur Messung des Stromverbrauchs.

Die Pakete installiert man im Terminal als root mit folgendem Kommando (tp_smapi-Paketname ist ggf. anzupassen):

zypper in tlp tp_smapi-kmp-desktop smartmontools ethtool powertop

Install Vmware player on opensuse 12.1

January 29th, 2012 | admin

First, download and install it.

Then, do not forget to install gcc and kernel-source via zypper.

The most important:

sudo /usr/bin/vmware-modconfig  --icon="vmware-player" --appname=Vmware --gcc=/usr/bin/gcc --headers=/lib/modules/3.1.0-1.2-default/build/include/ --gcc-ignore-minor

Then it works well for me.

Double the time for laptop running on battery

January 17th, 2012 | admin

Tested under Mandriva&OpenSuse&Slackware, all works well.

$sudo zypper install powertop
$sudo zypper install  laptop-mode-tools
$sudo zypper install cpufrequtils

also check out cpufreq-utils
http://forums.opensuse.org/blogs/jdm…ls-package-40/

Thanks, quota for remark see following:

 

I have written a bash script file designed to work with the cpufrequtils package and the programs cpufreq-info (for reading CPU speed info) and cpufreq-set (to set CPU speed governor and frequency).

This is my third attempt at writing a bash shell to interface with these two packages. After creating a blog on how to use YaST to set your CPU speed with yast-power-management you can read about here: YaST Power Management – Control Your CPU Energy Usage How To & FAQ – Blogs – openSUSE Forums, several forum users indicated they used the cpufreq utilities instead. So, I decided to see if any sort of value added bash script could be put together to work with this program set. Changes made to your CPU speed only last until you reboot your computer, but you may find the information and function it provides to be useful.

Version 1.10 of C.F.U. (works with openSUSE 12.1) Adds new features and bug fixes:

1. New Help Display is included
2. C.F.U. includes menu automation. Type cfu -h for more details
3. Better Detection for the cpufrequtils to work and to be installed
4. Better detection of available speeds usable on your PC

To use the bash script file cfu, you need to download the following text from SUSE Paste (Actual Link is shown below) into a text editor like kwrite:

C.F.U. – CPU Frequency Utility – Version 1.10

Save the text as the file cfu in the /home area bin folder (example is: /home/username/bin, also known as ~/bin). It is possible to directly download cfu from a terminal session (You must delete or rename the old version first):

rm ~/bin/cfu
wget -nc http://paste.opensuse.org/view/download/72458191 -O ~/bin/cfu

This script must be marked executable to be used. Please run the following Terminal command:

chmod +x ~/bin/cfu

It is even possible to string all three of these commands together as one. Copy the following command, open up a terminal session, paste it in and press enter:

rm ~/bin/cfu ; wget -nc http://paste.opensuse.org/view/download/72458191 -O ~/bin/cfu ; chmod +x ~/bin/cfu

To use cfu, open a terminal session and type in:

cfu &lt;OR&gt; cfu -h

If the cpufrequtils package is not installed, you will be prompted to install it. In order to change your governor or CPU speed, you must supply the root user password. Same goes for installing the cpufrequtils package if it is missing. As always, I would love to hear about any comments or problems you might have using cfu.

Thank You,

Free as Wind

January 15th, 2012 | admin

Free as Wind, to be what you are, embrace your dreams.

download.

give me some sunshine

January 14th, 2012 | admin

Saari umar hum
Mar mar ke jee liye
Jeene do
Ek pal to ab humein jeene do
Saari umar hum
Mar mar ke jee liye
Ek pal to ab humein jeene do
Jeene do
Saari umar hum
Mar mar ke jee liye
Ek pal to ab humein jeene do
Jeene do
Na na na….Na na na….Na na na….Na na nana na….
Give me some sunshine
Give me some rain
Give me another chance
I wanna grow up once again
Give me some sunshine
Give me some rain
Give me another chance
I wanna grow up once again
Kandhon ko kitabon
Ke bojh ne jhukaya
Rishvat dena to khud
Papa ne sikhaya
99% marks laaoge to ghadi, varna chhadi
Likh likh kar pada hatheli par
Alpha, beta, gamma ka chaala
Concentrated H2SO4 ne poora
Poora bachpan jalaa daala
Bachpan to gaya
Jawani bhi gayi
Ek pal to ab humein
Jeene do jeene do
Bachpan to gaya
Jawani bhi gayi
Ek pal to ab humein
Jeene do jeene do
~~~music~~~
Saari umar hum
Mar mar ke jee liye
Ek pal to ab humein jeene do
Jeene do
Na na na….Na na na….Na na na….Na na nana na….
Give me some sunshine
Give me some rain
Give me another chance
I wanna grow up once again
Give me some sunshine
Give me some rain
Give me another chance
I wanna grow up once again
Na na na….Na na na….Na na na….Na na nana na….
Na na na….Na na na….Na na na….Na na nana na….
~~~end~~~

I hope you like it, we just have life only one time.

If you can not view online, please download it from here

World is huge, space is enough to do anything

January 13th, 2012 | admin

The world is huge, space is enough to do anything. I want a big office which can support my training application for some juniors, with a big white board, expensive for all meeting rooms in the High Technology Development Zone in Jinan. How to make it work? What about a College?
Let’s find it.Classroom in chollege
You see, it’s big, quiet, clean and FREE.
Why you need to follow the roles in the world? World is huge, space is enough to do anything if you really want to make it work.

Which programming language should you learn in 2012

January 12th, 2012 | admin

Please read the following picture, you can get what you want.
Which Programming Language You Need to Learn in 2012

It’s mine, existed

January 12th, 2012 | admin

Fully isolated tests in Symfony2

January 12th, 2012 | admin

The most important thing you should provide with your re-usable bundles is unit tests set. Lately I solved two major cases which Symfony2 hasn’t got out of the box: testing services, defined in Dependency Injection Container and running model tests with fixtures in fully isolated environment.
Testing services defined in DIC

Since DIC in Symfony2 is one of the most awesome solutions, you probably (so do I) want to reflect creating services in tests in the same manner as in tested code. So you probably wondering how to use container in the tests. For this purpose I created BaseTestCase, which all of my tests cases extends.

<?php

require_once(__DIR__ . "/../../../../app/AppKernel.php");

class BaseTestCase extends \PHPUnit_Framework_TestCase
{
  protected $_container;

  public function __construct()
  {
    $kernel = new \AppKernel("test", true);
    $kernel->boot();
    $this->_container = $kernel->getContainer();
    parent::__construct();
  }

  protected function get($service)
  {
    return $this->_container->get($service);
  }
}

Now you can simply retrieve services as $this->get(“service.name”) and invoke them (for testing purposes) in the same way, as you do it in production code (for example as in controlers)

Fully isolated model tests

Often we deal with testing code which works with database. For this purpose we should use Doctrine Fixtures Bundle and create some fixture classes. But we need to load those fixtures before every test, to make sure, that our tests are running in isolated environement. We can use ModelTestCase, like in the listing below.

<?php

require_once(__DIR__ . "/../../../../app/AppKernel.php");

class ModelTestCase extends \PHPUnit_Framework_TestCase
{
  protected $_application;

  public function setUp()
  {
    $kernel = new \AppKernel("test", true);
    $kernel->boot();
    $this->_application = new \Symfony\Bundle\FrameworkBundle\Console\Application($kernel);
    $this->_application->setAutoExit(false);
    $this->runConsole("doctrine:schema:drop", array("--force" => true));
    $this->runConsole("doctrine:schema:create");
    $this->runConsole("cache:warmup");
    $this->runConsole("doctrine:fixtures:load", array("--fixtures" => __DIR__ . "/../DataFixtures"));
  }

  protected function runConsole($command, Array $options = array())
  {
    $options["-e"] = "test";
    $options["-q"] = null;
    $options = array_merge($options, array('command' => $command));
    return $this->_application->run(new \Symfony\Component\Console\Input\ArrayInput($options));
  }
}

Last thing we need to do, is to setup sqlite in memory database in doctrine config (app/config/config_tes.yml):

doctrine:
    dbal:
        driver:   pdo_sqlite
        path:     :memory:
        memory:   true
    orm:
        auto_generate_proxy_classes: true
        auto_mapping: true

Now before every single test, in test case which extends ModelTestCase, whole database structure will be created into the sqlite memory databse, and all fixtures will be loaded.
This approach allows you to create test suites which can be run not only locally, but also in Continous Integration servers, like Bamboo or Hudson.

Some of concepts used in this post were borrowed from this blog post: http://www.elao.org/developpement/a-la-decouverte-de-symfony-2-tests-unitaires-sur-le-modele-phpunit-et-doctrine-2.html

Thanks to origin author.

Compare dates with Twig

January 12th, 2012 | admin

Here is a trick to compare two dates in Twig. Convert them as string with the date filter, with first the year, then the month and finally the day:

myDate|date('Y-m-d')

Then, you can compare strings because the chronological order is the same than the lexicographical order:

{% if date1|date('Y-m-d') > date2|date('Y-m-d') %}
    {# ... #}
{% endif %}

Tip. If you want to get the current date, you can give the string now to the date filter:

{% if "now"|date('Y-m-d') > date2|date('Y-m-d') %}
    {# ... #}
{% endif %}

Symfony2 Coding Standards

January 12th, 2012 | admin

Remember that the main advantage of standards is that every piece of code looks and feels familiar, it’s not about this or that being more readable.

Since a picture – or some code – is worth a thousand words, here’s a short example containing most features described below:

<!--?php 

/*
 * This file is part of the Symfony package.
 *
 * (c) Fabien Potencier <fabien@symfony.com-->
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

namespace Acme;

class Foo
{
    const SOME_CONST = 42;

    private $foo;

    /**
     * @param string $dummy Some argument description
     */
    public function __construct($dummy)
    {
        $this-&gt;foo = $this-&gt;transform($dummy);
    }

    /**
     * @param string $dummy Some argument description
     * @return string|null Transformed input
     */
    private function transform($dummy)
    {
        if (true === $dummy) {
            return;
        }
        if ('string' === $dummy) {
            $dummy = substr($dummy, 0, 5);
        }

        return $dummy;
    }
}

Structure

  • Never use short tags ( closing tag;
  • Indentation is done by steps of four spaces (tabs are never allowed);
  • Use the linefeed character (0x0A) to end lines;
  • Add a single space after each comma delimiter;
  • Don’t put spaces after an opening parenthesis and before a closing one;
  • Add a single space around operators (==, &&, …);
  • Add a single space before the opening parenthesis of a control keyword (if, else, for, while, …);
  • Add a blank line before return statements, unless the return is alone inside a statement-group (like an if statement);
  • Don’t add trailing spaces at the end of lines;
  • Use braces to indicate control structure body regardless of the number of statements it contains;
  • Put braces on their own line for classes, methods, and functions declaration;
  • Separate the conditional statements (if, else, …) and the opening brace with a single space and no blank line;
  • Declare visibility explicitly for class, methods, and properties (usage of var is prohibited);
  • Use lowercase PHP native typed constants: false, true, and null. The same goes for array();
  • Use uppercase strings for constants with words separated with underscores;
  • Define one class per file;
  • Declare class properties before methods;
  • Declare public methods first, then protected ones and finally private ones.

Naming Conventions

        • Use camelCase, not underscores, for variable, function and method names;
        • Use underscores for option, argument, parameter names;
        • Use namespaces for all classes;
        • Suffix interfaces with Interface;
        • Use alphanumeric characters and underscores for file names;
        • Don’t forget to look at the more verbose Conventions document for more subjective naming considerations.

Documentation

      • Add PHPDoc blocks for all classes, methods, and functions;
      • Omit the @return tag if the method does not return anything;
      • The @package and @subpackage annotations are not used.

Put braces on their own line for classes, methods, and functions declaration;

Unit testing for Symfony2 repositories with PHPUnit

January 12th, 2012 | admin

Here is the workflow I have to add a new function in an entity repository. Let’s say I have a blog and I want to get the most seen posts by counting the visits for each post. Here is the workflow I have:

Write the functions structure in the repository
Write the test structure test class
Write the DQL query with the console
Write the test in the test class
Write the query in the repository

1
The usual way to do add a query in a repository to add a new function that query the database and return the results:

namespace Acme\BlogBundle\Repository;
use Doctrine\ORM\EntityRepository;

class PostRepository extends EntityRepository {
    public function getMostSeen() {
        // query database and return results
    }
}

But this is hard to debug. I prefer to have for each query, two functions: one that build the query (that can easily be tested and debugged) and another one that execute that query and return result:

namespace Acme\BlogBundle\Repository;
use Doctrine\ORM\EntityRepository;

class PostRepository extends EntityRepository {
    public function qbMostSeen() {
        return $this->createQueryBuilder('p')
                    -> // ...
    }

    public function getMostSeen() {
        return $this->qbMostSeen()
                    ->getQuery()
                    ->getResult();
    }
}

2
The test class will be in the Tests directory of the bundle:

namespace Acme\BlogBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class PostRespositoryTest extends WebTestCase {
    // ...
}

But we want to be able to instantiate PostRepository and for that we need the Entity Manager and a kernel (that we don’t have by default). So let’s add setUp() that will be executed before the tests:

namespace Acme\BlogBundle\Tests\Controller;
use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class PostRespositoryTest extends WebTestCase {
    private $repo;

    public function setUp() {
        $kernel = static::createKernel();
        $this->repo = $kernel->boot();
        $this->repo = $kernel->getContainer()
                             ->get('doctrine.orm.entity_manager')
                             ->getRepository('AcmeBlogBundle:Post');
    }
}

We add our tests:
on the query itself: here we compare the query DQL to the DQL we are going to write
on the results: here we check that we have some results

public function testMostSeen()
{
    $this->assertEquals(
        $this->repo->qbMostSeen()->getDql(),
        "..." // the DQL query
    );

    $this->assertNotEquals(0, count($this->repo->getMostSeen()));
}

You can add your tests on either the query or the results.
3
Write the DQL. Let’s write the DQL step by step testing each step with the console. Here, we get all the posts:

app/console doctrine:query:dql --max-result=5 "SELECT p.title FROM Acme\BlogBundle\Entity\Post p"

then we add one by one parts of our query, testing on our database to check the result every time. A left join to get all the visits:

SELECT p.title, v.id
FROM Acme\BlogBundle\Entity\Post p
LEFT JOIN p.visits v

then we add the visit count:

SELECT p.title, COUNT(v) AS visit_count
FROM Acme\BlogBundle\Entity\Post p
LEFT JOIN p.visits v
GROUP BY p.title

and we order by visit count:

SELECT p.title, COUNT(v) AS visit_count
FROM Acme\BlogBundle\Entity\Post p
LEFT JOIN p.visits v
GROUP BY p.title
ORDER BY visit_count DESC

Now that we are happy with the query, we can finish to write our tests.
4
Just insert the DQL in the test:

$this->assertEquals(
    $this->repo->qbMostSeen()->getDql(),
    "SELECT p.title, COUNT(v) AS visit_count FROM Acme\BlogBundle\Entity\Post p LEFT JOIN p.visits v GROUP BY p.title ORDER BY visit_count DESC"
);

5
Finally, write the query until PHPUnit is green!

namespace Acme\BlogBundle\Repository;
use Doctrine\ORM\EntityRepository;

class PostRepository extends EntityRepository {
    public function qbMostSeen() {
        return $this->createQueryBuilder('p')
                    ->select('p.title', 'COUNT(v) AS visit_counts')
                    ->leftJoin('p.visits', 'v')
                    ->orderBy('visit_counts', 'DESC');
    }

    public function getMostSeen() {
        return $this->qbMostSeen()
                    ->getQuery()
                    ->getResult();
    }
}


Pro tip

You might want to add the alias dql to your shell environment (.bash_profile, .zsh/zshaliases or whatever):

alias dql="app/console doctrine:query:dql"

so you can just run in your shell:

dql "SELECT p.title FROM Acme\BlogBundle\Entity\Post p"

Feel free to ask questions right here

Thanks to the origin author here.

Learn more about Unit Test for Symfony2

January 12th, 2012 | admin

First of all, install PHPUnit:


$ pear channel-discover pear.phpunit.de
$ pear channel-discover components.ez.no
$ pear channel-discover pear.symfony-project.com
$ pear install phpunit/PHPUnit

Then you can start to use PHP Unit like:


$phpunit -c app/

If you want to get report on HTML format, add parameter:


$ phpunit -c app/ --coverage-html=cov/

Not everybody has xdebug installed, maybe you will meet some problems like:

The Xdebug extension is not loaded. No code coverage will be generated.

That means you need to install xdebug for your PHP5. If you are using OpenSuse, it has a PHP Extensions repository, you can find more details from the following site:


http://download.opensuse.org/repositories/

and

http://download.opensuse.org/repositories/server:/php:/extensions/openSUSE_12.1/server:php:extensions.repo

You just need to install it simply as:

$sudo zypper ar  http://download.opensuse.org/repositories/server:/php:/extensions/openSUSE_12.1/server:php:extensions.repo

$sudo zypper install php5-xdebug

Now you fix the problem.

Start

OK, Let’s start to mark some tips about unit test for Symfony2.

First, a simple unit test:

// src/Acme/DemoBundle/Tests/Utility/CalculatorTest.php
namespace Acme\DemoBundle\Tests\Utility;

use Acme\DemoBundle\Utility\Calculator;

class CalculatorTest extends \PHPUnit_Framework_TestCase
{
public function testAdd()
{
$calc = new Calculator();
$result = $calc-&gt;add(30, 12);

// assert that our calculator added the numbers correctly!
$this-&gt;assertEquals(42, $result);
}
}

You can run unit test via:

# run all tests in the Utility directory
$ phpunit -c app src/Acme/DemoBundle/Tests/Utility/

# run tests for the Calculator class
$ phpunit -c app src/Acme/DemoBundle/Tests/Utility/CalculatorTest.php

# run all tests for the entire Bundle
$ phpunit -c app src/Acme/DemoBundle/

What about a functional unit test?

// src/Acme/DemoBundle/Tests/Controller/DemoControllerTest.php
namespace Acme\DemoBundle\Tests\Controller;

use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;

class DemoControllerTest extends WebTestCase
{
public function testIndex()
{
$client = static::createClient();

$crawler = $client-&gt;request('GET', '/demo/hello/Fabien');

$this-&gt;assertTrue($crawler-&gt;filter('html:contains("Hello Fabien")')-&gt;count() &gt; 0);
}
}

Something more about links:

$link = $crawler-&gt;filter('a:contains("Greet")')-&gt;eq(1)-&gt;link();

$crawler = $client-&gt;click($link);

And form:


$form = $crawler-&gt;selectButton('submit')-&gt;form();

// set some values
$form['name'] = 'Lucas';
$form['form_name[subject]'] = 'Hey there!';

// submit the form
$crawler = $client-&gt;submit($form);

Now that you can easily navigate through an application, use assertions to test that it actually does what you expect it to. Use the Crawler to make assertions on the DOM:

// Assert that the response matches a given CSS selector.
$this-&gt;assertTrue($crawler-&gt;filter('h1')-&gt;count() &gt; 0);

Or, test against the Response content directly if you just want to assert that the content contains some text, or if the Response is not an XML/HTML document:

$this-&gt;assertRegExp('/Hello Fabien/', $client-&gt;getResponse()-&gt;getContent());

The test Client simulates an HTTP client like a browser and makes requests into your Symfony2 application:

$crawler = $client-&gt;request('GET', '/hello/Fabien');

The request() method takes the HTTP method and a URL as arguments and returns a Crawler instance.

Use the Crawler to find DOM elements in the Response. These elements can then be used to click on links and submit forms:

$link = $crawler-&gt;selectLink('Go elsewhere...')-&gt;link();
$crawler = $client-&gt;click($link);

$form = $crawler-&gt;selectButton('validate')-&gt;form();
$crawler = $client-&gt;submit($form, array('name' =&gt; 'Fabien'));

The click() and submit() methods both return a Crawler object. These methods are the best way to browse your application as it takes care of a lot of things for you, like detecting the HTTP method from a form and giving you a nice API for uploading files.

The request method can also be used to simulate form submissions directly or perform more complex requests:

// Directly submit a form (but using the Crawler is easier!)
$client-&gt;request('POST', '/submit', array('name' =&gt; 'Fabien'));

// Form submission with a file upload
use Symfony\Component\HttpFoundation\File\UploadedFile;

$photo = new UploadedFile(
'/path/to/photo.jpg',
'photo.jpg',
'image/jpeg',
123
);
// or
$photo = array(
'tmp_name' =&gt; '/path/to/photo.jpg',
'name' =&gt; 'photo.jpg',
'type' =&gt; 'image/jpeg',
'size' =&gt; 123,
'error' =&gt; UPLOAD_ERR_OK
);
$client-&gt;request(
'POST',
'/submit',
array('name' =&gt; 'Fabien'),
array('photo' =&gt; $photo)
);

// Perform a DELETE requests, and pass HTTP headers
$client-&gt;request(
'DELETE',
'/post/12',
array(),
array(),
array('PHP_AUTH_USER' =&gt; 'username', 'PHP_AUTH_PW' =&gt; 'pa$$word')
);

Last but not least, you can force each request to be executed in its own PHP process to avoid any side-effects when working with several clients in the same script:

$client-&gt;insulate();

Browsing

The Client supports many operations that can be done in a real browser:


$client-&gt;back();
$client-&gt;forward();
$client-&gt;reload();

// Clears all cookies and the history
$client-&gt;restart();
Accessing Internal Objects

If you use the client to test your application, you might want to access the client’s internal objects:


$history = $client-&gt;getHistory();
$cookieJar = $client-&gt;getCookieJar();

You can also get the objects related to the latest request:


$request = $client-&gt;getRequest();
$response = $client-&gt;getResponse();
$crawler = $client-&gt;getCrawler();

If your requests are not insulated, you can also access the Container and the Kernel:

$container = $client-&gt;getContainer();
$kernel = $client-&gt;getKernel();

Accessing the Container

It’s highly recommended that a functional test only tests the Response. But under certain very rare circumstances, you might want to access some internal objects to write assertions. In such cases, you can access the dependency injection container:


$container = $client-&gt;getContainer();

Be warned that this does not work if you insulate the client or if you use an HTTP layer. For a list of services available in your application, use the container:debug console task.

 

Something more details you should refer to the official symfony book from here.

Enable PHP5.3 on hostgator

January 8th, 2012 | admin

Anywhere, .htaccess:

Action application/x-hg-php53 /cgi-sys/php53
AddHandler application/x-hg-php53 .php