Showing posts with label symfony tutorial. Show all posts
Showing posts with label symfony tutorial. Show all posts

Tuesday, April 19, 2011

Symfony Load Helper in Action

Symfony provides a rich set of methods in View part of Symfony MVC, which by defualt are not available in Action part, to make this available you have to load the specific helper that have your desire method, for example if you want to use image_path() method of Symfony you will need to load 'Assest' Helper, or if you want to use url_for() method you will load 'Url' helper, a complete list of helpers and there respective methods is available here

Now, Let the code talk

if i want to use image_path() method i will do it like this,
// ...
// may some code here...
// ...

sfContext::getInstance()
      ->getConfiguration()
        ->loadHelpers("Asset");

// this will load Symfony Asset Helper.. and make available all its helper.

$imagePath=image_path("../uploads/profile_images/IMAGE_NAME");

// ...
// more code...
// ...
Continue Reading...

Thursday, April 7, 2011

Symfony url_for in ACTION

symfony tutorial
Symfony url_for() method return the URL according to current context, remember url_for method is available only in VIEW part of Symfony MVC, what if one wants to create a HTML in MODEL (although it is not recommended, just in case) and in that HTML there are link which needs to be formatted according to current context, for that there is a method in Symfony generateUrl().

generateUrl() Method Signature

string generateUrl('URL_ROUTE',
         array(
        'module'=>'MODULE_NAME',
        'action'=>'ACTION_CALLED',
        'PARAMS'=>'VALUE'
             ),
        $isAbsolute
);
URL_ROUTE is the SEO Friendly URL pattern you defined in config file of module, if not defined use 'default' second is the config array in which we define module name and the action we want to call next is the parameter we want to pass via URL you can pass as many as you want params through it, in the form 'PARAM1'=>'VALUE1','PARAM2'=>'VALUE2',.... and last parameter is $isAbsolute it instruct whether we want relative or absolute URL, default is false it generate relative URL by default.

Example

$this->generateUrl('default',
array('module'=>'User','action'=>'EditUser','uid'=>$id))
the out will be something like this...
backend_dev.php/User/EditUser/uid/1130
hope it helps...
Continue Reading...

Thursday, March 17, 2011

Symfony Session Timeout

Session handling is one of the most important things in web development, it helps to track user, its activity and most importantly give user a personalization feel, Symfony make it very easy to handle user Sessions by changing just one value in a yaml file you can manage user's Sessions, lets get to point :) i am using Netbeans (great IDE) for my development... open you project in Netbeans, if you dont know how to configure Symfony to work with Netbeans this might help you.

Symfony Session Timeout

Open factories.yml located in apps/[MODULE_NAME]/config/factories.yml you will see somthing like this...
all:
  user:
    class: myUser
    param:
      timeout: false
myUser is the child class of sfBasicSecurityUser which is in apps/[MODULE_NAME]/lib/myUser.class.php you can change the name of the class, timeout is the property that controls Session time out of user if this is set as false time out never occur if a numeric value is given time out will occur after that, timeout value is in milliseconds i.e. if value is 36000 timeout will occur in 10 min (60*60*10), simple and easy is not it?
Continue Reading...

Friday, February 25, 2011

Paging in Symfony

In this tutorial we will learn how to implement Paging in Symfony, the process is fairly simple and easy to implement, just a little know how to PHP, Symfony and Doctrine is required.
First the code we will write in Controller or Symfony module Action class.
public function executePaging(sfWebRequest $request){

        $results_per_page=10;
        $set_first_page=1;

        $this->pagination = new sfDoctrinePager('User', $results_per_page);
        $this->pagination->setQuery(Doctrine::getTable('User')->createQuery('u'));
        $this->pagination->setPage($request->getParameter('page', $set_first_page));
        $this->pagination->init();
        
    }
now the code we write in View or the ethodNameSuccess in our case PagingSuccess.php
<?php foreach ($pagination->getResults() as $users): ?>

<?php endforeach; ?> 
<?php echo $users->getId(); ?> <?php echo $users->getFirstName(); ?> <?php echo $users->getLastName(); ?> <?php echo $users->getEmail(); ?>
<?php echo link_to('<<', 'myModule/Paging?page='.$pagination->getFirstPage()) ?>
<?php if ($pagination->haveToPaginate()): ?> <?php $links = $pagination->getLinks(); foreach ($links as $page): ?>
<?php echo ($page == $pagination->getPage()) ? $page : link_to($page, 'myModule/Paging?page='.$page) ?>
<?php endforeach ?> <?php endif ?>
<?php echo link_to('>>', 'myModule/Paging?page='.$pagination->getLastPage()) ?>
try to implement it and you will see its very easy :)
Continue Reading...

Sunday, February 20, 2011

Symfony Doctrine Native SQL

in my earlier post, Symfony Doctrine Execute Raw SQL i execute Raw or Native SQL quries, however method describe previously can only perform SELECT operations, in this post we will execute all type of SQL quires i.e. SELECT, INSERT, UPDATE, DELETE
public function myDBWrapper($query,$type=0){
      $connection=Doctrine_Manager::getInstance()
                  ->getCurrentConnection()->getDbh();
      // Get Connection of Database

      $statement=$connection->prepare($query);
      // Make Statement

      $statement->execute();
      // Execute Query

      if($type==0){
          // Check if it is SELECT query
          
          $results = $statement->fetchAll();
          return $results;
      }

  }

Usage

public function executeMyDBWrapperTest(sfWebRequest $request){

       $insertQuery="INSERT INTO users (username,email)
                       VALUES ('Originative','originative@live.com')";
       $selectQuery="Select * from users";

       $this->myDBWrapper($insertQuery);
       // INSERT data in table
       
       $this->results=$this->myDBWrapper($selectQuery, 1);
       // Fetch data from table save output 
       // which will be displayed in
       // MyDBWrapperTestSuccess.php

   }
Continue Reading...

Tuesday, January 18, 2011

Symfony Page Refresh / Reload

In this quick tutorial we will refresh the page using symfony i.e. we will call the same page form where is request is called lets do it...
public function executePageRefresh(sfWebRequest $request){
    //... something usefull here
    //... going back
    $this->redirect($request->getUri());
}
we use redirect function of symfony and method getUri() from $request object... getUri() give the complete URL inclucing the http and query string.
Continue Reading...

Wednesday, January 12, 2011

Symfony Doctrine Delete Row

In this tutorial we will delete a Row from database using Doctrine, lets do it with a simple example
public function executeDelete(sfWebRequest $request){

        Doctrine::getTable('User')
        ->findBy('id', $request->getParameter('id'))
        ->delete();

        $this->redirect('SOME/PAGE');
        $this->setTemplate(false);

    }
Doctrine simplify our CRUD operations, here we just give Id of the record to be deleted and use delete() method or Doctrine to remove that record.
Continue Reading...

Monday, January 10, 2011

Symfony Doctrine Execute Raw SQL

Converting to object oriented can be sometimes difficult as people are not used to it... same is the case with ORM, when you use it there may be some problems for the new comers.

Doctrine an ORM tool, can execute Raw SQL queries beside fully object and partial queries, executing raw sql queries is very simple following PHP code demonstrate it, here we use Doctrine with symfony.
public function executeShowUserInfo(sfWebRequest $request){

     $query = Doctrine_Query::create()
      ->query("select * from user");

     $result = $query->toArray();

     $count = count($result);

     for($i=0;$i<$count;$i++){

         echo $result [$i]["first_name"]
         ." => "
         .$result [$i]["email"]
         .",";

     }
}
here $query->toArray() convert returned response in to array.
Note : it is not recommended to echo from a controller, i do just for demonstration purpose.
Continue Reading...

Thursday, January 6, 2011

Symfony Doctrine Row Count

Doctrine is a very powerful ORM for PHP application, this tutorial demonstrate how you can get the number of rows returned by Doctrine.

Suppose we want to check if a user is valid or not, for that we need user name and password, here we are using symfony.

public function executeValidateUser(sfWebRequest $request){

$username = $request -> getParameter("username");
$password = $request -> getParameter("password");

$query = Doctrine_Query::create()
->select("id")
->from("user")
->where("username=$username")
->andWhere("password=$password");

$rowcount= $query -> count();

if( $rowcount == 1 ){

//do something useful, User Authenticated

}
else{

// do something useful here too even thoug User is Not Authenticated :)

}
} 

here we first get the $username and $passowrd from the form submitted using symfony $request->getParamenter() method then we make a Doctrine query and then we check how many results are returned by the Doctrine Query using Doctrine count() method and lastly we check if it is exactly 1 which mean user name and password is correct and user is a valid user if not then the else part work.
Continue Reading...

Tuesday, January 4, 2011

Symfony Doctrine Print Raw SQL

When you are debugging your code, it is very helpful to know what queries are executing at the database end, it helps a lot to simplify debugging.

Talking about Symfony with Doctrine as ORM, its very simple to know what query Doctrine is passing to the Database server, here is a small example that demonstrate it.

Suppose we want to get the First and Last name of our user and table is user, first we make a query.
$query=Doctrine_Query::create()
   ->select("first_name, last_name")
   ->from("user");
now we get this query using the Doctrine method getSQLQuery()
echo $query->getSQLQuery();
exit();
on the browser we get something like this
SELECT u.id AS u__id, u.first_name AS u__first_name, u.last_name AS u__last_name FROM user u
Continue Reading...

Monday, December 27, 2010

The Definitive Guide to Symfony

The Definitive Guide to symfony
Developing a new web application should not mean reinventing the wheel. Thats why a framework is an essential item in your development toolbox. It helps you respect coding standards; write bulletproof, maintainable code; and focus on business rules rather than waste time on repetitive tasks. This book introduces you to symfony, the leading framework for PHP developers, showing you how to wield its many features to develop web applications faster and more efficiently, even if you only know a bit of PHP.
In The Definitive Guide to symfony, you will learn about the Model-View-Controller architecture and the crucial role it plays in making frameworks like symfony possible. The book also covers framework installation and configuration, and shows you how to build pages, deal with templates, manage requests and sessions, and communicate with databases and servers. You will see how symfony can make your life easier by effectively managing form data, enhancing the user experience with Ajax, internationalizing applications for a global audience, and using smart URLs. Authors Franois Zaninotto and Fabien Potencier put a strong emphasis on the tools that symfony provides for professional environments, showing you how to take advantage of unit tests, scaffolding, plug-ins, the command line, and extensible configuration. And since frameworks often raise performance-related debate, this book will give you many tips and techniques for monitoring and improving your applications performance, from caching to expert configuration tweaks.
Always keen to offer practical instruction, the authors include a lot of code examples, expert tips, best practices, and illustrations throughout this book, with the goal of providing a resource that satisfies the educational needs of symfonys rapidly growing user community.
Continue Reading...

Friday, December 17, 2010

Symfony Netbeans HelloWorld Tutorial

To day we will try to make a simple traditional "Hello World" application using the Symfony Framework in Netbeans, we will make this application from scratch, from configuring Symfony in Netbeans and then creating a module and so on, in a step by step manner.

Prerequisites

  • Symfony 1.4.x, you can download it form here
  • Netbeans with PHP support, you can download it from here
  • WAMP, you can download it from here
  • Little knowledge of PHP :)

Lets Start

Install Netbeans, WAMP server and then unzip Symfony and rename then extract folder to symfony (for simplicity). Now open Netbeans and go to Tools > Options > PHP (tab)


in PHP 5 interpreter filed browse to the PHP5 exe, which is located in %WAMP_INSTALL_DIR%\bin\php\php5.3.0\php.exe and below it there is an option for Global Include path in that Add the Folder of symphony (extracted one).

Now click on Symfony Tab

symfony tutorial

tell Netbeans where is Symfony Script is, it will be located in %SYMFONY_EXTRACTED_DIR%\data\bin\symfony notice it \bin\symfony with out any extension, click Ok button.

Now create a new PHP Project File > New Project... > PHP > PHP Application and press Next Button

symfony tutorial

name the project as HelloWorld and save the project in www directory of WAMP it will be %WAMP_INSTALL_DIR%\www\HelloWorld Click next button twice and you will see following screen.

symfony tutorial

check the Symfony PHP Web Framework  and click Finish. now Netbeans will create a Symfony Project with all the necessary configurations.

symfony tutorial

you will see a directory structure in Project window and a log of all the action taken by Netbeans, let run the project in a web browser, with following URL http://localhost/HelloWorld/web/

symfony tutorial

as you can see there is no CSS and images here, although Symfony is working, go to  %SYMFONY_EXTRACTED_DIR%\data\web and copy the sf folder and paste it in web directory of your project and refresh the page and you see a nice Welcome page.

symfony tutorial

now back to Netbeans, create a module mySite ,to do this  right click on Project > Symfony > Run Command ...

symfony tutorial

this will open a command console with all the command that Symfony support and it contains all the documentation associated with a command. we will use the generate:module command, we don't need to write the whole we just select the command form the list and provide parameters in the parameter filed in our case we pass frontend mySite telling symfony to create mySite module in fronted module. press Run Command.

symfony tutorial

now if you see your directory structure you will notice a module mySite is created with its action (Controller) and templates (View) folder and a default files are also created.

symfony tutorial

now open actions.class.php in actions folder and replace method executeIndex(sfWebRequest $request) with following code.
public function executeIndex(sfWebRequest $request)
  {
    $this->greetings="Hello World, Symfony is Great :)";
  }
now open indexSuccess.php located in templates folder this file is by defualt empty, in it paste the following code
<?php
    echo "

$greetings

"; ?> 
open web browser and navigate to the URL http://localhost/HelloWorld/web/frontend_dev.php/mySite it will also show a debugging toolbar which show very useful information, if you don't want debugging toolbar change URL to http://localhost/HelloWorld/web/index.php/mySite you should be able to see following page.

symfony tutorial
simple isn't it? :)

Note: there may be other ways, better ways of doing this, if you know such ways share them, this is the way i learn it .
Continue Reading...

Thursday, December 9, 2010

Symfony in Netbeans

A more Detail tutorial can be found here

Recently i started to learn Symfony (a php framework), i started with tutorials that are given on its site which are mostly command line base things, i want an IDE for that supports Symfony, so i googled as usual i was surprised to see my favorite (NetBeans) has out of the box support for it (i should i have known it before), i found an excellent screen castthat explain how to use Symfony in Netbeans.





Screen cast original located here and it by Jeff Rubinoff
Continue Reading...
 

Blog Info

A Pakistani Website by Originative Systems

Total Pageviews

Tutorial Jinni Copyright © 2015 WoodMag is Modified by Originative Systems