symfony2
Friday, December 2, 2011
Social networking web application part1
In this tutorial we are going to create a web application having social networking functionality. For this we have user registration, user profile, web forms, friends list, photo album, message service.
Back again....
After a long time of absence, i going to make a series of tutorial based on some of the common applications with advanced concepts. within these days symfony2 become very robust and powerful framework. i'm considering an audience, which had minimum knowledge about symfony framework..
Monday, February 14, 2011
First step
In this tutorial we understand about the file structure of our web app.
Before that
1.obtain a new copy of symfony framework from here.
2.make a new folder inside your server and named as "webapp".
3.create a folder structure like below:
Before that
1.obtain a new copy of symfony framework from here.
2.make a new folder inside your server and named as "webapp".
3.create a folder structure like below:
www/ <- your web root directory
webapp/
app/
cache/
config/
logs/
src/
webapps/
HelloBundle/
Controller/
Resources/
vendor/
web/
4. place your unarchived symfony inside the vendor folder.
Friday, August 27, 2010
sugarbox in brief
This post is the summary of the previous three tutorial posts.
1. download the latest sugarbox from here.. (or you can use git clone command)
2. upload to your server, initially set permission to all
3.check whether you have all the required items(go to your browser http://localhost/sugarbox/web/check.php)
4.In terminal cd to your sugarbox directory
5.in terminal type this
php blog/console -s
6.you'll get a symfony environment. to see all the available commands type this:
1. download the latest sugarbox from here.. (or you can use git clone command)
2. upload to your server, initially set permission to all
3.check whether you have all the required items(go to your browser http://localhost/sugarbox/web/check.php)
4.In terminal cd to your sugarbox directory
5.in terminal type this
php blog/console -s
6.you'll get a symfony environment. to see all the available commands type this:
list
7.to create database as configured in blog/config/config.yml type this in terminal:
doctrine:database:create
8.we create the Entity model in src/Application/BlogBundle/Entity/Blog.php doctrine take this and convert to database schema. to create this(schema) type
doctrine:schema:create
9.next, create repositories for entity
doctrine:generate:repositories
10.the above will create BlogBundle/Entity/BlogRepositories.php
After finishing the above steps check in your browser.
http://localhost/sugarbox/web/index.php
To create new blog post :
http://localhost/sugarbox/web/index.php/blog/new
Monday, August 23, 2010
sugarbox part 3
routing.yml
homepage:
pattern: /
defaults: { _controller: FrameworkBundle:Default:index }
blog:
resource: BlogBundle/Resources/config/routing.yml
From the first line(homepage), it's clear that, the URL http://localhost/sugarbox/web/index.php/ goes to the 'Default' controller in 'FrameworkBundle' and point to the 'index' action. It shows this in your browser:
Congratulations!
You have successfully created a new Symfony 2 application.
So check it yourself. You can give any name instead of homepage.
The second(blog), point to another routing file inside src/Application/BlogBundle/Resources/config/routing.yml
it goes like this:
blog:
pattern: /blog
defaults: { _controller: BlogBundle:Blog:index }
blog_new:
pattern: /blog/new
defaults: { _controller: BlogBundle:Blog:new }
so when a request like this http://localhost/sugarbox/web/index.php/blog points to 'Blog' controller in 'BlogBundle' and 'index' action. This outputs this:
Blog Application
Hello Blog index!
Http://localhost/sugarbox/web/index.php/blog/new points to 'Blog' controller in 'BlogBundle' and 'new' action. This outputs this:
Beware: we can't save the post now. So by clicking submit button make no sense!
In your terminal go to sugarbox directory
$ cd sugarbox
symfony2 has inbuilt CLI. We now initiate thie
$ php blog/console -s
this will display this:
to list all commands
Symfony > list
Symfony displays this:
Now we are going to create database as configured in config.yml
initialy, we drop the database(todo), if there any present.
Symfony > doctrine:database:drop
Dropped database for connection named todo
Symfony > doctrine:database:create
Created database for connection named todo
to check, go to your phpmyadmin. You'll see todo database(empty)
To create tables according to schema created in BlogBundle/Entity/Blog.php.
first, we create repositories
Symfony > doctrine:generate:repositories
Generating entity repositories for "BlogBundle"
> generating Bundle\BlogBundle\Entity\BlogRepository
now we create the schema
Symfony > doctrine:schema:create
to check, go to phpmyadmin. There is a table named 'posts'
homepage:
pattern: /
defaults: { _controller: FrameworkBundle:Default:index }
blog:
resource: BlogBundle/Resources/config/routing.yml
From the first line(homepage), it's clear that, the URL http://localhost/sugarbox/web/index.php/ goes to the 'Default' controller in 'FrameworkBundle' and point to the 'index' action. It shows this in your browser:
Congratulations!
You have successfully created a new Symfony 2 application.
So check it yourself. You can give any name instead of homepage.
The second(blog), point to another routing file inside src/Application/BlogBundle/Resources/config/routing.yml
it goes like this:
blog:
pattern: /blog
defaults: { _controller: BlogBundle:Blog:index }
blog_new:
pattern: /blog/new
defaults: { _controller: BlogBundle:Blog:new }
so when a request like this http://localhost/sugarbox/web/index.php/blog points to 'Blog' controller in 'BlogBundle' and 'index' action. This outputs this:
Blog Application
Hello Blog index!
Http://localhost/sugarbox/web/index.php/blog/new points to 'Blog' controller in 'BlogBundle' and 'new' action. This outputs this:
Beware: we can't save the post now. So by clicking submit button make no sense!
In your terminal go to sugarbox directory
$ cd sugarbox
symfony2 has inbuilt CLI. We now initiate thie
$ php blog/console -s
this will display this:
to list all commands
Symfony > list
Symfony displays this:
Now we are going to create database as configured in config.yml
initialy, we drop the database(todo), if there any present.
Symfony > doctrine:database:drop
Dropped database for connection named todo
Symfony > doctrine:database:create
Created database for connection named todo
to check, go to your phpmyadmin. You'll see todo database(empty)
To create tables according to schema created in BlogBundle/Entity/Blog.php.
first, we create repositories
Symfony > doctrine:generate:repositories
Generating entity repositories for "BlogBundle"
> generating Bundle\BlogBundle\Entity\BlogRepository
now we create the schema
Symfony > doctrine:schema:create
to check, go to phpmyadmin. There is a table named 'posts'
Labels:
symfony,
symfony2,
symfony2 tutorial,
symfony2-sugarbox
sugarbox part2
autoload.php
$vendorDir = __DIR__.'/vendor';
require_once $vendorDir.'/symfony/src/Symfony/Framework/UniversalClassLoader.php';
use Symfony\Framework\UniversalClassLoader;
$loader = new UniversalClassLoader();
$loader->registerNamespaces(array(
'Symfony' => $vendorDir.'/symfony/src',
'Application' => __DIR__,
'Bundle' => __DIR__,
'Doctrine\\Common' => $vendorDir.'/doctrine-common/lib',
'Doctrine\\DBAL\\Migrations' => $vendorDir.'/doctrine-migrations/lib',
'Doctrine\\ODM\\MongoDB' => $vendorDir.'/doctrine-mongodb/lib',
'Doctrine\\DBAL' => $vendorDir.'/doctrine-dbal/lib',
'Doctrine' => $vendorDir.'/doctrine/lib',
'Zend' => $vendorDir.'/zend/library',
));
$loader->registerPrefixes(array(
'Swift_' => $vendorDir.'/swiftmailer/lib/classes',
'Twig_' => $vendorDir.'/twig/lib',
));
$loader->register();
namespace Application\BlogBundle;
use Symfony\Framework\Bundle\Bundle;
class BlogBundle extends Bundle
{
}
declare(ENCODING = 'utf-8');
namespace Application\BlogBundle\Entity;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints;
/**
* @Entity(repositoryClass="Bundle\BlogBundle\Entity\BlogRepository")
* @Table(name="posts")
* @HasLifecycleCallbacks
*/
class Blog
{
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('title', new Constraints\NotBlank());
$metadata->addPropertyConstraint('title', new Constraints\MinLength(5));
$metadata->addGetterConstraint('description', new Constraints\NotNull());
}
/**
* @Id @Column(type="integer")
* @GeneratedValue(strategy="AUTO")
*/
private $id;
/**
*
* @Column(type="string", length=250)
*
*/
protected $title;
/**
*
*
* @column(type="string", length=250)
*/
protected $description;
public function getId()
{
return $this->id;
}
public function setTitle($title) {
$this->title = $title;
}
public function getTitle() {
return $this->title;
}
public function setDescription($description) {
$this->description = $description;
}
public function getDescription() {
return $this->description;
}
}
let's take a look:
$vendorDir = __DIR__.'/vendor';
require_once $vendorDir.'/symfony/src/Symfony/Framework/UniversalClassLoader.php';
use Symfony\Framework\UniversalClassLoader;
$loader = new UniversalClassLoader();
$loader->registerNamespaces(array(
'Symfony' => $vendorDir.'/symfony/src',
'Application' => __DIR__,
'Bundle' => __DIR__,
'Doctrine\\Common' => $vendorDir.'/doctrine-common/lib',
'Doctrine\\DBAL\\Migrations' => $vendorDir.'/doctrine-migrations/lib',
'Doctrine\\ODM\\MongoDB' => $vendorDir.'/doctrine-mongodb/lib',
'Doctrine\\DBAL' => $vendorDir.'/doctrine-dbal/lib',
'Doctrine' => $vendorDir.'/doctrine/lib',
'Zend' => $vendorDir.'/zend/library',
));
$loader->registerPrefixes(array(
'Swift_' => $vendorDir.'/swiftmailer/lib/classes',
'Twig_' => $vendorDir.'/twig/lib',
));
$loader->register();
Now we good to create class for our own application-blog. All the php files related to application goes to corresponding application bundles. In this case inside BlogBundle.
Inside BlogBundle you'll see these folders:
Controller
Entity
Resources
and this file BlogBundle.php
open BlogBundle.php
BlogBundle.php
namespace Application\BlogBundle;
use Symfony\Framework\Bundle\Bundle;
class BlogBundle extends Bundle
{
}
All your controller classess goes into Controller folder.
Model classess goes into Entity folder
All layouts, views, custom application routes goes into Resources folder.
Ok. let's begin with Model classess. In this tutorial we are using doctrine 2 as ORM. You can read more about doctrine 2 here. S2 also supports propel. So you have download the doctrine 2 from here.
In doctrine2 we can create schema from three files: plain php(annotation), YAML, xml. We go for annotation type, bcoz it has more advantage. In Entity folder create a php file – Blog.php
Blog.php
declare(ENCODING = 'utf-8');
namespace Application\BlogBundle\Entity;
use Symfony\Component\Validator\Mapping\ClassMetadata;
use Symfony\Component\Validator\Constraints;
/**
* @Entity(repositoryClass="Bundle\BlogBundle\Entity\BlogRepository")
* @Table(name="posts")
* @HasLifecycleCallbacks
*/
class Blog
{
public static function loadValidatorMetadata(ClassMetadata $metadata)
{
$metadata->addPropertyConstraint('title', new Constraints\NotBlank());
$metadata->addPropertyConstraint('title', new Constraints\MinLength(5));
$metadata->addGetterConstraint('description', new Constraints\NotNull());
}
/**
* @Id @Column(type="integer")
* @GeneratedValue(strategy="AUTO")
*/
private $id;
/**
*
* @Column(type="string", length=250)
*
*/
protected $title;
/**
*
*
* @column(type="string", length=250)
*/
protected $description;
public function getId()
{
return $this->id;
}
public function setTitle($title) {
$this->title = $title;
}
public function getTitle() {
return $this->title;
}
public function setDescription($description) {
$this->description = $description;
}
public function getDescription() {
return $this->description;
}
}
Doctrine ORM change the above class into schema and create database. For this we use CLI(command line interface). To setup doctrine and configure our application we've to write blog/config/config.yml .
kernel.config:
charset: UTF-8
error_handler: null
web.config:
router: { resource: "%kernel.root_dir%/config/routing.yml" }
validation: { enabled: true, annotations: true }
web.templating:
escaping: htmlspecialchars
doctrine.dbal:
connections:
default:
driverClass: Doctrine\DBAL\Driver\PDOMySql\Driver #
dbname: todo
user: root
password: admin
doctrine.orm: ~
charset: UTF-8
error_handler: null
web.config:
router: { resource: "%kernel.root_dir%/config/routing.yml" }
validation: { enabled: true, annotations: true }
web.templating:
escaping: htmlspecialchars
doctrine.dbal:
connections:
default:
driverClass: Doctrine\DBAL\Driver\PDOMySql\Driver #
dbname: todo
user: root
password: admin
doctrine.orm: ~
in s2, you can create multiple database connection. here use single (default) connection. you can give the database name, mysql username, password .
[continue]
note: these tutorials are updated frequently. i know there are so many typos and errors are there. please comment those here. if you have any doubts disscuss here.
sugarbox
In this application we are using latest symfony2 code. There are so many different changes are made in this latest version. You can get the original symfony2 code from http://github.com/symfony
So we have to make a custom application. Sugarbox can be downloaded from here.
The steps:
Download sugarbox from above mentioned URL- unzip and upload to server root
This the final structure.
symfony2 basic:
web/index.php is front controller. It's the only php file that access from a browser. So all your php files are well protected. Index.php accepts the HTTP request from the browser and sends it to the application. S2 is kernal based application. Kernal is the heart of all s2 operations. So to create a s2 app we need to create sub class of this kernal (abstract) class. This is placed under blog folder. So create a php file called BlogKernel.php. The naming is very important. Create another folder 'config' inside blog main folder. All configuration files and routing files are placed under config folder. For this tutorial we not go for caching and logging mechanism. We can back here after finishing this tutorial.
In s2, all are in the form of bundles. 'Bundles are first class citizen'. So our application bundle(BlogBundle) will place inside Application folder. Ok. So let's do some coding.
Front Controller
Open web/index.php file using your favourite text editor.
require_once __DIR__.'/../blog/BlogKernel.php';
$kernel = new BlogKernel('dev', true);
$kernel->handle()->send();
$kernel = new BlogKernel('dev', true);
$kernel->handle()->send();
These are the only lines that goes into index.php. Here we create a new instance of our Blogkernal class which we will create soon. In $kernel = new BlogKernel('prod', false); line, 'prod' and 'false' are two arguments that pass to the blog application. 'prod' means setup the production environment and false means no debugging. Instead of 'prod' you can give 'dev' for development. In development environment you need debugging on – so instead of 'false' we write 'true'.
Application kernel
Ok lets move to BlogKernel.php.
require_once __DIR__.'/../src/autoload.php';
use Symfony\Framework\Kernel;
use Symfony\Component\DependencyInjection\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class BlogKernel extends Kernel
{
public function registerRootDir()
{
return __DIR__;
}
public function boot()
{
Symfony\Component\OutputEscaper\Escaper::markClassesAsSafe(array(
'Symfony\Component\Form\Form',
'Symfony\Component\Form\Field'
));
return parent::boot();
}
public function registerBundles()
{
$bundles = array(
new Symfony\Framework\KernelBundle(),
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\ZendBundle\ZendBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Symfony\Bundle\DoctrineBundle\DoctrineBundle(),
//new Symfony\Bundle\DoctrineMigrationsBundle\DoctrineMigrationsBundle(),
//new Symfony\Bundle\DoctrineMongoDBBundle\DoctrineMongoDBBundle(),
//new Symfony\Bundle\PropelBundle\PropelBundle(),
//new Symfony\Bundle\TwigBundle\TwigBundle(),
new Application\BlogBundle\BlogBundle(),
);
if ($this->isDebug()) {
}
return $bundles;
}
public function registerBundleDirs()
{
return array(
'Application' => __DIR__.'/../src/Application',
'Bundle' => __DIR__.'/../src/Bundle',
'Symfony\\Bundle' => __DIR__.'/../src/vendor/symfony/src/Symfony/Bundle',
);
}
//to load config files
public function registerContainerConfiguration(LoaderInterface $loader)
{
// use YAML for configuration
// comment to use another configuration format
$container = new ContainerBuilder();
$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
$container->setParameter('validator.message_interpolator.class', 'Application\\BlogBundle\\Validator\\NoValidationXliffMessageInterpolator');
return $container;
// uncomment to use XML for configuration
//$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.xml');
// uncomment to use PHP for configuration
//$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.php');
}
}
use Symfony\Framework\Kernel;
use Symfony\Component\DependencyInjection\Loader\LoaderInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
class BlogKernel extends Kernel
{
public function registerRootDir()
{
return __DIR__;
}
public function boot()
{
Symfony\Component\OutputEscaper\Escaper::markClassesAsSafe(array(
'Symfony\Component\Form\Form',
'Symfony\Component\Form\Field'
));
return parent::boot();
}
public function registerBundles()
{
$bundles = array(
new Symfony\Framework\KernelBundle(),
new Symfony\Bundle\FrameworkBundle\FrameworkBundle(),
new Symfony\Bundle\ZendBundle\ZendBundle(),
new Symfony\Bundle\SwiftmailerBundle\SwiftmailerBundle(),
new Symfony\Bundle\DoctrineBundle\DoctrineBundle(),
//new Symfony\Bundle\DoctrineMigrationsBundle\DoctrineMigrationsBundle(),
//new Symfony\Bundle\DoctrineMongoDBBundle\DoctrineMongoDBBundle(),
//new Symfony\Bundle\PropelBundle\PropelBundle(),
//new Symfony\Bundle\TwigBundle\TwigBundle(),
new Application\BlogBundle\BlogBundle(),
);
if ($this->isDebug()) {
}
return $bundles;
}
public function registerBundleDirs()
{
return array(
'Application' => __DIR__.'/../src/Application',
'Bundle' => __DIR__.'/../src/Bundle',
'Symfony\\Bundle' => __DIR__.'/../src/vendor/symfony/src/Symfony/Bundle',
);
}
//to load config files
public function registerContainerConfiguration(LoaderInterface $loader)
{
// use YAML for configuration
// comment to use another configuration format
$container = new ContainerBuilder();
$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.yml');
$container->setParameter('validator.message_interpolator.class', 'Application\\BlogBundle\\Validator\\NoValidationXliffMessageInterpolator');
return $container;
// uncomment to use XML for configuration
//$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.xml');
// uncomment to use PHP for configuration
//$loader->load(__DIR__.'/config/config_'.$this->getEnvironment().'.php');
}
}
i think the above is self explanatory.
Now we go to the autoload.php.
[continue]
Subscribe to:
Posts (Atom)