Pages

Saturday, August 17, 2013

Revision Controling using Git Part I

Creating a Git repositay

revision controlling or version controlling is a very important thing in modern software development. To know more about it's importance read the fallowing article at oss watch.
                                 Initializing and using Git is easier than expected. At first Git must be installed to computer. Second, User identity should be set as fallows

  git config --global user.email "you@example.com"
  git config --global user.name "Your Name"

Third, create a file called ".gitignore" at the root of the project. Open the file and add folder paths that should not be included into the Git repository. Paths should be as started from project root directory.

Forth, initialize it repository by executing
        $ git init
Fifth, Add all necessary files to the git repository
        $ git add .
Finlay , Commit
        $ git commit -m "<your message>"

Thats it, If all are done properly 

resourcess

http://git-scm.com/book/en/Git-Basics-Getting-a-Git-Repository
http://git-scm.com/book/en/Getting-Started-First-Time-Git-Setup
http://symfony.com/doc/current/cookbook/workflow/new_project_git.html

       

      

Sunday, July 14, 2013

Creating forms in Symfony2 part III

I had created a "one to many " relation and a form related to them. Today I am going to create a "many to many " relation and there forms. I will use these forms to create a "User loging" in my next blog post.

OK, my relationship is simple, I take 'user' and 'role'. a user may have zero or many roles and a role mayhave zero or many users. (This diagram does not shows the zero or many relationship ).



Create 'User' and 'Role' entities by executing 
$ php app/console generate:doctrine:entity
command. (keep in mind configuration format should be in "xml" format for this tutorial)

then entity configuration files should be updated. 
first open the 
<my bundle>/Resources/config/doctrine/User.orm.xml file and add fallowing to the file inside the <entity></entity> tags.

<many-to-many field="role" inversed-by="user" target-entity="Acme\<my bundle>\Entity\Role">
<join-table name="UserRole">
<join-columns>
<join-column name="userId" referenced-column-name="id" />
</join-columns>
<inverse-join-columns>
<join-column name="rolrId" referenced-column-name="id" />
</inverse-join-columns>
</join-table>
</many-to-many>

then 
open the 
<my bundle>/Resources/config/doctrine/Role.orm.xml file and add fallowing to the file inside the <entity></entity> tags.


<many-to-many field="user" mapped-by="role" target-entity="Acme\<my bundle>\Entity\User"/>


then update the entities by executing 
$ php app/console generate:doctrine:entities <my bundle>
get more information about doctrine many to many relationships from here.

update the database 
$ php app/console doctrine:schema:create or
$ php app/console doctrine:schema:update

Now entities creation is completed. Now CRUD should be created. Do these using 
$ php app/console doctrine:generate:crud

command for both User and Role entities.
Now few changes should be done to forms. For the 'Role' form actually it shouldn't have a option to select user even it was designed for it. But for the User entity it should have a  multiple select filed for select user's role's

if the CRUD creation was executed correctly file called
Acme/<my bundle>/Form/RoleType.php was generated with some php code.
inside the RoleType class there is a method named buildForm. inside this
field options is add to the $builder instance.

it is looks like that

$builder
->add('name')
->add('role')
->add('user');;

no need to display users, remove that 
->add('user');;

finally it looks like 
$builder
->add('name')
->add('role')

then open the 
Acme/<my bundle>/Form/UserType.php  file update the $builder instance inside the BuildForm method.

it is looks like

$builder
->add('username')
->add('salt')
->add('password')
->add('email')
->add('isActive')
->add('role')


role field need to be populated with roles from the "Role". to do this edit it as fallow.


$builder
->add('username')
->add('salt')
->add('password')
->add('email')
->add('isActive')
->add('role','entity',array(
'class' => 'AcmeAuthBundle:Role',
'property' => 'name',
'multiple' => TRUE
))










Monday, June 24, 2013

Creating forms in Symfony2 Part II

We have created blog user level form, Now we have to create User. user has 'name', 'display name','e mail', 'image id' and 'blog user level id'. According to our ERD one user has one blog user level, one user level has many Users. To create the user form let's begin with creating entity by running
$ php app/console generate:doctrine:entity
and create 
'name', 'display name','e mail', 'image id' files.  Now we have to create 'blog user level id' field. I still couldn't find a way to create relations in command prompt. But i found a way to do it by editing entity configuration file. open the 'BlogUser.orm.xml' file and add fallowing

    <many-to-one field="bloguserlevel" target-entity="Acme\UserBundle\Entity\BlogUserLevel">
        <join-column name="blog_user_level_id" referenced-column-name="id"/>
    </many-to-one> 


final file looks like this

<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  <entity name="Acme\UserBundle\Entity\BlogUser">
    <id name="id" type="integer" column="id">
      <generator strategy="AUTO"/>
    </id>
    <field name="name" type="string" column="name" length="255"/>
    <field name="displayName" type="string" column="display_name" length="255"/>
    <field name="email" type="string" column="email" length="255"/>
    <field name="image" type="integer" column="image"/>
    <many-to-one field="bloguserlevel" target-entity="Acme\UserBundle\Entity\BlogUserLevel">
        <join-column name="blog_user_level_id" referenced-column-name="id"/>
    </many-to-one>      
  </entity>
</doctrine-mapping>


then create entity by executing
$ php app/console generate:doctrine:entities AcmeUserBundle




update the database
$ php app/console doctrine:schema:update --force

Create CRUD operations
$ php app/console generate:doctrine:crud

We have a drop down(blog_user_level_id) in this form. To load the user levels open the
Acme/UserBundle/Form/BlogUserType.php for and update buildForm() method. the method will be looks like as fallows

    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('name')
            ->add('displayName')
            ->add('email')
            ->add('image')
            ->add('bloguserlevel','entity',array(
                    'class' => 'AcmeUserBundle:BlogUserLevel',
                    'property' => 'name',
            ))
        ;
    }


thats it. goto http://localhost:8000/bloguser/ in check the form is working..







Tuesday, May 28, 2013

Creating forms in Symfony2 Part I

Symfony2 command line tool has provided a excellent way to create forms without too much bother about the code.
 
  Now i am going to create all forms(CRUD) for "blog_user_level" table. Guess how much time will I spend for it. OK  keep that in your mind.

First of all i create entity for the "blog_user_level" to do that run fallowing command in the terminal.

     $ php app/console generate:doctrine:entity

then it will ask fallowing parameters.

    The Entity shortcut name: AcmeUserBundle:BlogUserLevel
    Configuration format (yml, xml, php, or annotation) [annotation]: xml
    New field name (press <return> to stop adding fields): name
    Field type [string]:
    Field length [255]:

    New field name (press <return> to stop adding fields): level
    Field type [string]: integer

    New field name (press <return> to stop adding fields):

    Do you want to generate an empty repository class [no]?


    Do you confirm generation [yes]? 


then update the database
    $ php app/console doctrine:schema:update --force
now we want to create crud. to do that
    $ php app/console generate:doctrine:crud --overwrite

then it will ask some parameters

    The Entity shortcut name: AcmeUserBundle:BlogUserLevel
    Do you want to generate the "write" actions [no]? yes
    Configuration format (yml, xml, php, or annotation) [annotation]: xml
    Routes prefix [/bloguserlevel]:

    ...........


  
Sometimes it will ask to update routing.yml file. yeh that's all.
now go to the http://localhost:8000/bloguserlevel/ and test CRUD application.







Creating a bundle in Symfony2

Overview
    Learning with a sample project is a best way to learn a project. Here I am going to create a blog system. Here is my ERD. actually this is not mine, i have downloaded .mwb file from http://www.jarrodoberto.com and littlebit modification to it. thanks jarrod.


I have divided these into two separate section, user and blog. So i have to create to bundles. here i am going to crate "User" bundle.
  
Symfony2 command line tool provided a good support to developers. they don't need to create all file manual. just have to execute few commands in the terminal and will get a bundle easily.

open the terminal and change your directory to the project folder, then execute fallowing command

$ php app/console generate:bundle

then it will ask parameter one by one. in this time I create a bundle called "Document". the bundle will automatically be created inside the "src" folder.
and the bundle must be located inside the "Acme" folder and it's name must be ended with suffix "Bundle". at this time command line tool ask  namespace value, here it is "Acme/UserBundle". then it will ask as fallows

Bundle namespace: Acme/UserBundle
Bundle name [Acme
UserBundle]:
Target directory [/var/www/kanasblog/src]:
Configuration format (yml, xml, php, or annotation): yml
Do you want to generate the whole directory structure [no]? Yes
Do you confirm generation [yes]? Yes
Confirm automatic update of your Kernel [yes]?
Confirm automatic update of the Routing [yes]?
 

default values has shown inside the squire brackets.

thats it.. the bundle has generated now. to check that open the fallowing url in your browser

 http://localhost:8000/hello/kanasblog

it should display "kanasblog" in the browser..


Sunday, May 26, 2013

Including javascript and css in Symfony2


    when installing the framework by default it comes with a bundle called "DemoBundle". I used that bundle to locate css and javascript. here i want to load twiter Bootstrap. i downloaded the bootstrap and uncompressed and place it in the "/<project folder>/src/Acme/DemoBundle/Resources/public/css/" folder. So now we want to call to bootstrap globally. "/samitiya/app/Resources/views/base.html.twig" file is a file that can be callable in every view file. And another this i don't want to mess "base.html.twig" file. So I create two separate files called
"/src/Acme/DemoBundle/Resources/views/Template/css.html.twig" and
"/src/Acme/DemoBundle/Resources/views/Template/js.html.twig".

then include them into the  "base.html.twig". before include them we need to set "AcmeDemoBundle" as a asset. Open the
"/<project folder>/app/config/config.yml" file and find the
"# Assetic Configuration", then include the "AcmeDemoBundle" in to "bundles" list. this is how it looks like.

assetic:
    debug:          %kernel.debug%
    use_controller: false
    bundles:        [AcmeDemoBundle]
    #java: /usr/bin/java
    filters:
        cssrewrite: ~
        #closure:
        #    jar: %kernel.root_dir%/Resources/java/compiler.jar
        #yui_css:
        #    jar: %kernel.root_dir%/Resources/java/yuicompressor-2.4.7.jar





Ok, lets include above file into "base.html.twig". Open the base.html.twig file, include fallowing lines to the <head></head> tags.


        {% include 'AcmeDemoBundle:Template:js.html.twig' %}
        {% include 'AcmeDemoBundle:Template:css.html.twig' %}


this is twig, If you want to include something we want to use {%include %} tag.
when we call for the bundle then it will automatically look at the its "Resources/views/" folder. we user ":" instead of "/" for separate directories.

Now we can include js files to "Template:js.html.twig" and css files to "Template:css.html.twig". Open the
"/src/Acme/DemoBundle/Resources/views/Template/js.html.twig" include the fallowing content

{% javascripts
    '@AcmeDemoBundle/Resources/public/js/jquery-2.0.1.min.js'
    '@AcmeDemoBundle/Resources/public/css/bootstrap/js/bootstrap.min.js'
    '@AcmeDemoBundle/Resources/public/css/bootstrap/js/bootstrap-dropdown.js'
         
 %}
    <script type="text/javascript" src="{{ asset_url }}"></script>
{% endjavascripts %}


yes, this is not like twig include this require full path and start the bundle name with "@" sign. "bootstrap" require "jquery". So i have load first. "bootstrap-dropdown.js" wants to create drop downs. thats why i have these two files.
then open the css.html.twig file include fallowing content.

{% stylesheets
    '@AcmeDemoBundle/Resources/public/css/bootstrap/css/bootstrap.min.css'
    '@AcmeDemoBundle/Resources/public/css/bootstrap/css/bootstrap-responsive.css'
   
 filter='cssrewrite' %}
    <link rel="stylesheet" href="{{ asset_url }}" />
{% endstylesheets %}


thats it. to check inclusion reload any web page in the browser(firefox) and view the page source. above five files must be shown in the <head> tags and click on the the file links. they must load the appreciate js and css files. 




Saturday, May 25, 2013

database setup in symfony2

MySQL
     this is very very simple. Open the "/<project folder>/app/config/parameters.yml" and provide the appropriate values. this is my values

parameters:
    database_driver:   pdo_mysql
    database_host:     127.0.0.1
    database_port:     ~
    database_name:     kanasblog
    database_user:     root
    database_password: ~


then go to the  project folder and execute the fallowing command



    $ php app/console doctrine:database:create

oh wait. i forgot to tell something. in php there two most popular ORM frameworks available. Doctrine   and Propel . both frameworks can be used with Symfony2 very easily. in here i used Doctrine and it will install automatically. If it is not doctrine bundle can be be added using composer.

mongodb
    Actually this is bit tufter to install than mysql. First of all php mongodb extension should be installed to php(both command line and working php).
then update php.ini file by including "extension=mongo.so". to find the ini file location
    $ php -i |grep php\.ini

Ok, let's install mongodb bundle usong composer. So we have to update the "composer.json" file. include fallowing to "require" dictionary.

        "doctrine/mongodb-odm": "1.0.*@dev",
        "doctrine/mongodb-odm-bundle": "3.0.*@dev"


then update
     $ php composer.phar update

now we have to do two more things. register notation and driver..
to register annotation open the "app/autoload.php" file and  insert fallowing content just below the "AnnotationRegistry::registerLoader(array($loader, 'loadClass'));" line

use Doctrine\ODM\MongoDB\Mapping\Driver\AnnotationDriver;
AnnotationDriver::registerAnnotationClasses();


to register bundle open the "/app/AppKernel.php" file and add fallowing to "$bundle" array

    new Doctrine\Bundle\MongoDBBundle\DoctrineMongoDBBundle(),

finaly set database parameters for mongodb. open the "/app/config/config.yml"
and add fallowing

doctrine_mongodb:
    connections:
        default:
            server: mongodb://localhost:27017
            options: {}
    default_database: samitiya
    document_managers:
        default:
            auto_mapping: true



thats it. execute fallowing in the terminal.

    $ php app/console doctrine:mongodb:schema:create


for more information visit page DoctrineMongoDBBundle




   


Sunday, April 14, 2013

installing symfony2 on ubuntu

system requirements
before all, you should install php, mysql and apache2 on your computer

then apache2 must be configured.

  1. enable mod rewrite
  2. set allowoveride to fileinfo
to do above things execute fallowing commands in terminal

  1. sudo a2enmod rewrite
  2. sudo gedit /etc/apache2/sites-available/default and then  set AllowOverride None to AllowOverride FileInfo
 as well as for this tutorial composer , mongodb should be installed on your computer

installing symfony2 
download the latest version from http://symfony.com/download 

extract & rename(kanablog) it and copy to document root. kanaslab.org is the project name here

update the source by using composer (sudo composer update;)

start the server “php app/console server:run

and to test your installation goto     http://localhost:8000/config.php

now change the permission
    $ rm -rf app/cache/*
    $ rm -rf app/logs/*
    sudo setfacl -R -m u:www-data:rwx -m u:<computer name>:rwx app/cache app/logs
    sudo setfacl -dR -m u:www-data:rwx -m u:<computer name>:rwx app/cache app/logs

OR
    sudo chmod -R 777 *

update the source using  composer

$ php -r "eval('?>'.file_get_contents('https://getcomposer.org/installer'));"
$ php composer.phar update