Install Composer + Twig for Windows 8

I use Wamp server and I had a problem with installing Composer. I have found this solution:
You should enable php_openssl in the Wamp menu. After this you could open the php.ini and set ON the allow_url_fopen. So. After this restart the Wamp Server and open the command line:

 php -r "eval('?>'.file_get_contents('http://getcomposer.org/installer'));"  

Then you should enable php_phar extension in the Wamp Server menu.

After the Wamp restart you should create a composer.json file:

 {  
   "require": {  
     "twig/twig": "1.*"  
   }  
 }  

…and install the Twig:

 php composer.phar install  

I hope it will work… ūüôā

Advertisements
Posted in Uncategorized | Tagged , , | 2 Comments

Qunit —-> testing Ajax functions

If you need to test Ajax request you should do in this way. First you ought to create a HTML file It will be the test datafile therefore it contain only simple JSON

data.data/test_ajax_data.html

 {"data":"refreshed","val":"1"}  

Then you can write your test:

 var JSON_obj_val_integer = 0;  
 remoteGetInteger = function ( completedHandler) {  
           var post = $.ajax({  
                url: 'data/test_ajax_data.html',  
                type: "post",  
                dataType: "json",  
                data: { refresh: "1" },  
                success: function(JSON_obj) {  
                     $.each(JSON_obj,function() {  
                               JSON_obj_val_integer = JSON_obj.val;  
                      });  
                 }  
            });  
           post.done(function (result) {  
                completedHandler(JSON_obj_val_integer);  
           });  
           post.fail(function () {  
                completedHandler('error');  
           });  
 };  
 test( 'JSON_obj_val_String value = refreshed', function() {       
      var result = '';  
      stop(800);  
      remoteGetString( function (r) {  
           result = r;  
           equal(result, 'refreshed', "check Ajax String");  
           start();  
      });  
 });  

Thats it.

Posted in Uncategorized | Tagged , | Leave a comment

Client-side JavaScript unit testing with qunit

I think the client-side JavaScript unit testing is as important as server-side unit testing. There are lot of programmers whom¬†don’t think the the client-side unit testing is important.¬†I don’t understand the reason…because client-side software developing and server-side developing are the same¬†in this respect. The unit testing as well as the¬†TDD is not our enemy… ūüôā I guess ¬†we need to do unit testing server and client side, too.
Let me introduce the qunit because it is easy to use but I use several client-side unit testing tool:

jsUnit
Test Runner for JavaScript: Karma
BusterJs (client and server-side (Node.js) unit testing tool)

So. I did one simple example. I did a JavaScript class. I used the qunit, jQuery, jQuery UI.

Step 1.

index.html

 <!DOCTYPE html>  
 <html>  
 <head>  
  <meta charset="utf-8">  
  <title>Main Page</title>  
  <link rel="stylesheet" href="qunit-1.11.0.css">  
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />  
 </head>  
 <body>  
  <input id="btnShowBigNumber" type="button" value="Show big number"/>  
  <input id="btnShowAjaxResponse" type="button" value="Show Ajax response"/>  
  <input id="btnShowDialog" type="button" value="Show dialog"/>  

  <script src="jquery-1.9.1.min.js"></script>  
  <script src="jquery-ui-1.10.2/ui/jquery-ui.js"></script>  
  <script src="MAIN_TEST_APP.mainMonsterClass.js"></script>  
  <script src="main.js"></script>  
 </html>  

Step 2.

MAIN_TEST_APP.mainMonsterClass.js:

The class name is a little bit strange: “Monster” ūüôā and it has simple namespace because I think using namespaces is cool and useful. So, the code:

 /**   
  * Test Namespace, Test Class  
  * @author Mr. John Nobody  
  * @namespace Namespace for MAIN_TEST_APP classes and functions.   
  **/  
 var MAIN_TEST_APP = MAIN_TEST_APP || {};  

 MAIN_TEST_APP.mainMonsterClass = {  
   mainMethodInteger: function() {  
     var bigSum = (1 + 5 * (0));  
     return bigSum;  
   },  
   mainMethodJSONAjax: function() {  
     var ajax_result;  

     $.ajax({  
       url: "main.php",  
       type: "POST",  
       dataType: "json",  
       async: false,  
       success: function(response) {  
         $.each(response, function(key, item) {  
           if (key === 'value' && item === "ok")  
             ajax_result = item;  
         });  
       },  
       error: function(error) {  
         console.log("Error:");  
         console.log(error);  
       }  
     });  
     return ajax_result;  
   },  
   mainMethodJQUIDialog: function() {  
     var tag = $("<div></div>");  
     var dialog_content = "<p>Hello World Dialog</p>";  
     tag.html(dialog_content).dialog({modal: true}).dialog('open');  
   }  
 };  

Step 3.
main.php

The server-side PHP code is very complicated. :–)

 <?php  
 echo json_encode( array("value"=>"ok") );  
 exit;  

Ok. Let’s get to the testing.

Step 1.

test.html

 <!DOCTYPE html>  
 <html>  
 <head>  
  <meta charset="utf-8">  
  <title>Main Page Unit tests</title>  
  <link rel="stylesheet" href="qunit-1.11.0.css">  
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />  
 </head>  
 <body>  
  <div id="qunit"></div>  
  <div id="qunit-fixture"></div>  
  <script src="jquery-1.9.1.min.js"></script>  
  <script src="jquery-ui-1.10.2/ui/jquery-ui.js"></script>  
  <script src="MAIN_TEST_APP.mainMonsterClass.js"></script>  
  <script src="qunit-1.11.0.js"></script>  
  <script src="test1.js"></script>  
 </body>  
 </html>  

Step 2.

test.js:

The qunit is very simple. It has few assertions but that’s enough.

 /**  
  * Test: MAIN_TEST_APP.mainMonsterClass.mainMethodInteger  
  * @returns {}  
  */  
 test( "MAIN_TEST_APP_mainMonsterClass_mainMethodInteger test", function() {  
   var expected_value = 1;  
   equal(  
       MAIN_TEST_APP.mainMonsterClass.mainMethodInteger(),   
       expected_value,  
       "MAIN_TEST_APP.mainMonsterClass.mainMethodInteger; equal succeeds" );  
 });  

 test( "MAIN_TEST_APP_mainMonsterClass_mainMethodJSONAjax test", function() {  
   var expected_value = "ok";  
   equal(  
       MAIN_TEST_APP.mainMonsterClass.mainMethodJSONAjax(),   
       expected_value,  
       "MAIN_TEST_APP.mainMonsterClass.mainMethodJSONAjax; equal succeeds" );       
 });  

 test( "Strict_MAIN_TEST_APP_mainMonsterClass_mainMethodJSONAjax test", function() {  
   var expected_value = "ok";        
   strictEqual(  
       MAIN_TEST_APP.mainMonsterClass.mainMethodJSONAjax(),   
       expected_value,  
       "MAIN_TEST_APP.mainMonsterClass.mainMethodJSONAjax; equal succeeds" );        

 });  

 test( "Strict_MAIN_TEST_APP_mainMonsterClass_mainMethodJQUIDialog test", function() {  
     var tag = $("<div></div>");  
     var dialog_content = "<p>Hello World Dialog</p>";  
     tag.html(dialog_content).dialog({modal: true}).dialog('destroy');  
     ok(true, "dialog was");  
 });      

It is easy but very useful. You should make your code testable and you will be able to fix the bad dependencies.

Posted in Uncategorized | Tagged , | Leave a comment

Symfony2 quick tips: How to create “filter” in the controller?

Do you¬†remember¬†in the Symfony 1.x preExecute and postExecute methods? ūüôā Yes? They were ¬†cool but the Symfony2 has another (and a¬†lot nicer)¬†event manager . It name is Event Dispatcher. The Event Dispatcher is¬†flexible¬†and well-designed component and easy to use.

You should define your event in the app/config/config.yml:

 services:  
    test.controller_listener:  
     class: TestCompany\TestBundle\EventListener\TestListener  
     arguments: [ "HelloWorld" ]  
     tags:  
       - { name: kernel.event_listener, event: kernel.controller, method: onKernelController }    

Then you need to create your event class:

/src/TestCompany/TestBundle/EventListener/TestListener.php

 <?php  

 namespace TestCompany\TestBundle\EventListener;  

 use Symfony\Component\HttpKernel\Event\FilterControllerEvent;  

 class TestListener {  

   private $test_argument_hello_world;  

   public function __construct($arguments) {  
     $this->test_argument_hello_world = $arguments;  
   }  

   public function onKernelController(FilterControllerEvent $event) {  
     $controller = $event->getController();  

     var_dump($this->test_argument_hello_world);  

     if (!is_array($controller)) {  
       return;  
     }  
   }  

 }  

It is very easy and for example you can also define arguments in the configuration. If you need more information you should read the documentation of Symfony2 Event Dispatcher: http://symfony.com/doc/current/components/event_dispatcher/introduction.html

Posted in Uncategorized | Tagged , | Leave a comment

Symfony2: The CRUD problem.

This blog post will be short and quick. ūüôā I was testing some Symfony2¬†CRUD and Admin bundles:

The result of the tests? ūüôā Well, I don’t want to write negative things. So, I am only writing that I don’t want to use these bundles because each of them has more problems, bugs and are undocumented or its documentation was out of date, false etc.
I realized that useful, well-designed and ¬†well-maintained¬†external¬†Symfony2¬†CRUD generator or “Admin module” doesn’t exist or if it exist I didn’t find it… ūüôā

I think one of the¬†strength of Symfony 1.x was that it had very professional internal¬†admin generator. I guess¬†Symfony2 and Zend are the best PHP frameworks (but my¬†favourite¬†is Symfony2) but I think without CRUD generator Symfony2 doesn’t as good as would be with it.

Solution? I think at the moment the best CRUD generator for Symfony2 is SensioGeneratorBundle and the best solution is that if you extend it and you create on your own CRUD or admin app. The SensioGeneratorBundle generate very clean and simple code and easy to extend.

Posted in Uncategorized | Tagged , , | Leave a comment

Symfony2 quick tips: How to generate bundle and how to create simple entity + CRUD?

Step 1.

What is the Symfony bundle?

“A bundle is nothing more than a directory that houses everything related to a specific feature, including PHP classes, configuration, and even stylesheets and Javascript files…”

It’s just a quote from a Symfony2 documentation:¬†http://symfony.com/doc/current/book/page_creation.html

I generated new bundle with this command:

 php app/console generate:bundle  

and I used the Symfony2 (I used the current Symfony version: Symfony 2.2.0) command line wizard because it is very comfortable It made the bundle “skeleton”, create routings and something like this. I gave¬†the “TestCompany/TestBundle” namespace as well as I used annotations. After the bundle generation you should find your generated bundle under the /src/TestCompany/TestBundle path.

Step 2.

Create new database entity. I used Doctrine and MySQL database and I wrote my entity classes manually.

Don’t forget set the database configuration in the app/config/parameters.yml.

 parameters:  
   database_driver: pdo_mysql  
   database_host: 127.0.0.1  
   database_port: null  
   database_name: symfony2  
   database_user: yourusername  
   database_password: yourpass  
   mailer_transport: smtp  
   mailer_host: 127.0.0.1  
   mailer_user: null  
   mailer_password: null  
   locale: en  
   secret: a87c3c69d4b934488ab10f9272c1ba9b3  
   database_path: null  

So, I created two simple entity: Test, Category. Both entity has two fileds: id, title.  Between Test and Category is Many-to-many relationship.

/src/TestCompany/TestBundle/Entity/Test.php:

 <?php  

 namespace TestCompany\TestBundle\Entity;  

 use Doctrine\ORM\Mapping as ORM;  
 use Symfony\Component\Validator\Constraints as Assert;  

 /**  
  * @ORM\Entity  
  * @ORM\Table(name="test")  
  */  
 class Test {  

   /**  
    * @ORM\Id  
    * @ORM\Column(type="integer")  
    * @ORM\GeneratedValue(strategy="AUTO")  
    */  
   protected $id;  

   /**  
    * @ORM\Column(type="string", length=255, nullable=true)  
    * @Symfony\Component\Validator\Constraints\NotBlank  
    * @Assert\MaxLength(255)  
    * @var string  
    */  
   private $title;  

   /**  
    * @ORM\ManyToMany(targetEntity="Category")  
    * @ORM\JoinTable(name="test_category",  
    *   joinColumns={@ORM\JoinColumn(name="test_id", referencedColumnName="id", nullable=true)},  
    *   inverseJoinColumns={@ORM\JoinColumn(name="category_id", referencedColumnName="id", columnDefinition="INT NULL")}  
    *   )  
    */  
   private $category;  

 }  

The title field is validated – it can’t be empty.

 @Symfony\Component\Validator\Constraints\NotBlank   

It is just simple example definitely the real world is more complicated. It may be that you need to write on your own validators etc. You should read this documentation: http://symfony.com/doc/current/cookbook/validation/custom_constraint.html

/src/TestCompany/TestBundle/Entity/Category.php:

 <?php  

 namespace TestCompany\TestBundle\Entity;  

 use Doctrine\ORM\Mapping as ORM;  
 use Doctrine\Common\Collections\ArrayCollection;  

 /**  
  * @ORM\Entity  
  * @ORM\Table(name="category")  
  */  
 class Category {  

   /**  
    * @ORM\Id  
    * @ORM\Column(type="integer")  
    * @ORM\GeneratedValue(strategy="AUTO")  
    */  
   protected $id;  

   /**  
    * @ORM\Column(type="string")  
    * @Symfony\Component\Validator\Constraints\NotBlank  
    * @var string  
    */  
   private $title;  

   public function __toString() {  
     return $this->title;  
   }  

 }  

The¬†__toString() method is very important because It return the category title as string without it for example¬†won’t be able to work generated CRUD controllers as well as on your own controllers etc.

So, after that you should generate entities:

 php app/console doctrine:generate:entities TestCompanyTestBundle  

…then you can try the Symfony2 CRUD generator:

 php app/console generate:doctrine:crud  

or you can use this command without interactions:

 php app/console generate:doctrine:crud --entity=TestCompanyTestBundle:Test --format=annotation --with-write --no-interaction  

but before the CRUD generation you have to create database, create tables and indexes:

 php app/console doctrine:database:create  

 php app/console doctrine:schema:update --force  

The doctrine:schema:update command has two parameters:

doctrine:schema:update –force to execute the command
doctrine:schema:update –dump-sql to dump the SQL statements to the screen

I think you will need some fixtures in the category table. So, You should try the DoctrineFixturesBundle:

http://symfony.com/doc/current/bundles/DoctrineFixturesBundle/index.html

If all is well :-), you should find your CRUD on this URL:

http://localhost/YOURSYMFONYDIR/web/app_dev.php/test

Posted in Uncategorized | Tagged , , | 1 Comment

cgSceneGraph (CGSG) JavaScript HTML5 Canvas framework

cgSceneGraph is a great JS HTML5 canvas framework. It is relatively new project and it is not so well-known like KineticJS but I think cgSceneGraph is impressive.

The cgSceneGraph is fully objectum-oriented framework, it supports complex scenes, it is cross platform (IE 9&10, Chrome, Firefox, Opera, iOS, Android). It support mouse and touch events (what is very comfortable), you can see its full features list here: http://gwennaelbuchet.github.com/cgSceneGraph/about.html

OK, well, let’s see. For example…hmm. How can we¬†create graphical buttons with CGSG?

 <!DOCTYPE html>  
 <html>  
 <head>  
   <meta charset="UTF-8"/>  
   <meta http-equiv="Content-type" content="text/html;charset=UTF-8"/>  
   <meta name="viewport"  
      content="width = device-width, initial-scale = 1, minimum-scale = 1, maximum-scale = 1, user-scalable = no"/>  
   <script type="text/javascript" src="cgscenegraph_1.4.2.min.js"></script>  
   <script type="text/javascript" src="test_anim_class.js"></script>  
 </head>  
 <body style="margin:0px">  
 <canvas id="canvas1" width="80" height="50">  
   Your browser doesn't support the canvas element.  
 </canvas>  
 <script type="text/javascript">  
   var mainCanvas = document.getElementById("canvas1");  
   var game = new CGMainTest(mainCanvas);  
 </script>  
 </body>  
 </html>  

test_anim_class.js:

 var CGMainTest = CGSGScene.extend(  
     {  
       initialize: function(canvas) {  
         this._super(canvas);  
         this.initializeCanvas();  
         this.createScene();  
         this.startPlaying();  
       },  
       initializeCanvas: function() {  
         this.viewDimension = cgsgGetRealViewportDimension();  
         this.setCanvasDimension(this.viewDimension);  
       },  
       createScene: function() {  
         //first create a root node with an arbitrary size and position  
         this.rootNode = new CGSGNode(0, 0, 1, 1);  
         this.sceneGraph.addNode(this.rootNode, null);  
         //add buttons  
         var buttonNode1 = new CGSGNodeButton(10, 10, "Button1");  
         var buttonNode2 = new CGSGNodeButton(130, 10, "Button2");  
         var buttonNode3 = new CGSGNodeButton(250, 10, "Button3");  
         //bind events  
         buttonNode1.onClick = function(event) {  
           alert('onClick event button1');  
         };  
         buttonNode2.onClick = function(event) {  
           alert('onClick event button2');  
         };  
         buttonNode3.onClick = function(event) {  
           alert('onClick event button3');  
         };  
         //add the button nodes as child of the rootNode  
         this.rootNode.addChild(buttonNode1);  
         this.rootNode.addChild(buttonNode2);  
         this.rootNode.addChild(buttonNode3);  
       }  
     }  
 );  

It is easy. And it is full OOP. Well, for example, if you want to set the button properties (background image, color etc.) you can do it very easy:

 buttonNode2.setImageURL("background1.png");  

You can also set background image position etc.:

 buttonNode2.setPictoPosition(CGSGPositionMode.RIGHT);  

And my favourite feature: each object can be draggable and resizeable:

 buttonNode2.isDraggable = true;  
 buttonNode2.isResizable = true;  

Simple animation. cgSceneGraph has complete animation engine It use timeline and animation keys + it support pre-computed animation values.

 var CGMainTest = CGSGScene.extend(  
     {  
       initialize: function(canvas) {  
         this._super(canvas);  
         this.initializeCanvas();  
         this.createScene();  
         this.startPlaying();  
       },  
       initializeCanvas: function() {  
         this.viewDimension = cgsgGetRealViewportDimension();  
         this.setCanvasDimension(this.viewDimension);  
       },  
       createScene: function() {  
         this.rootNode = new CGSGNode(0, 0, 1000, 1000);  
         this.sceneGraph.addNode(this.rootNode, null);  
         var square1 = new CGSGNodeSquare(10, 10, 100, 100);  
         var square2 = new CGSGNodeSquare(140, 120, 100, 100);  
         this.sceneGraph.animate(square1, "position.x", 30, 0, 300, "linear", 0, false);  
         this.sceneGraph.animate(square2, "position.x", 30, 0, 200, "linear", 0, true);  
         this.sceneGraph.animate(square2, "scale.x", 200, 2, 1, "linear", 90, false);  
         this.sceneGraph.animate(square2, "rotation.angle", 30, 0, Math.PI, "linear", 0, true);  
         this.rootNode.addChild(square1);  
         this.rootNode.addChild(square2);  
       }  
     }  
 );  

I think it is correct. You should see more examples: http://gwennaelbuchet.github.com/cgSceneGraph/examples.html

You can extend  CGSGNode class so you can create on your own CGSGNode entities. There is on this URL http://www.rampancylabs.com/ludum25/ a simple game made with cgSceneGraph. It contain some extended CGSGNode class I think is really worth see it.

That’s it. I think You should try it. ūüôā

Posted in Uncategorized | Tagged , , , | 2 Comments