Showing posts with label symfony-sugarbox. Show all posts
Showing posts with label symfony-sugarbox. Show all posts

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:
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 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();


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 .

  let's take a look:

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: ~


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:


  1. Download sugarbox from above mentioned URL
  2. 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();

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');
    }
}


i think the above is self explanatory.
Now we go to the autoload.php. 
[continue]