symfony2 introduction presentation

34
Symfony2 Tutorial By Alexios Tzanetopoulos

Upload: nerd-tzanetopoulos

Post on 27-Jan-2015

117 views

Category:

Entertainment & Humor


2 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Symfony2 Introduction Presentation

Symfony2 Tutorial

By Alexios Tzanetopoulos

Page 2: Symfony2 Introduction Presentation

What is Symfony2?

• Symfony2 is a PHP Framework that:

1. Provides a selection of components (i.e. the Symfony2 Components) and third-party libraries (e.g. Swiftmailer18 for sending emails);

2. Provides sensible configuration and a "glue" library that ties all of these pieces together.

3. Provides the feeling of objective programming cause it’s a MVC Framework.

Page 3: Symfony2 Introduction Presentation

What is MVC?

• MVC is a software architecture that separates the representation of information from the user's interaction with it. It consists of:

• A controller can send commands to its associated view to change the view's presentation of the model (e.g., by scrolling through a document).

• A model notifies its associated views and controllers when there has been a change in its state. This notification allows the views to produce updated output, and the controllers to change the available set of commands.

• A view requests from the model the information that it needs to generate an output representation.

Page 4: Symfony2 Introduction Presentation

Pros

• It allows a lot of flexibility around how the project is setup.• It is very fast and comparable to other web frameworks• Propel and Doctrine are both supported but not enforced. The creator

can choose to use whatever they want as an ORM(Object-relational mapping). Or none at all.

• Some of the Symfony2 components are now being implemented in large projects such as Drupal and PhpBB.

• Enough documentation and tutorials

Page 5: Symfony2 Introduction Presentation

Cons

• Requires command line (troll)• Not easy to learn

Page 6: Symfony2 Introduction Presentation

Flat PHP (blog posts page)

• <?php // index.php• $link = mysql_connect('localhost', 'myuser', 'mypassword');• mysql_select_db('blog_db', $link);• $result = mysql_query('SELECT id, title FROM post', $link); ?>• <!DOCTYPE html>• <html><head>• <title>List of Posts</title> </head> <body>• <h1>List of Posts</h1> <ul>• <?php while ($row = mysql_fetch_assoc($result)): ?>• <li>• <a href="/show.php?id=<?php echo $row['id'] ?>"> • <?php echo $row['title'] ?> </a>• </li> <?php endwhile; ?> </ul> </body> </html>• <?php mysql_close($link); ?>

Page 7: Symfony2 Introduction Presentation

Result?

• No error-checking• Poor organization• Difficult to reuse code

Page 8: Symfony2 Introduction Presentation

Ready to learn symfony2?

Page 9: Symfony2 Introduction Presentation

1st step Installation

• Download from http://symfony.com/download (standard version)• If you use php 5,4 it contains built-in web server• From 5,3 and below use your own web server (e.g xampp)• Unpack folder in htdocs• Test it @ http://localhost/symfony2/web/app_dev.php

Page 10: Symfony2 Introduction Presentation
Page 11: Symfony2 Introduction Presentation

2nd step Create application bundle

• As you know, a Symfony2 project is made up of bundles. • Execute in command line:

php app/console generate:bundle --namespace=Ens/JobeetBundle -- format=yml

• Clear cache then:php app/console cache:clear --env=prod

php app/console cache:clear --env=dev

Page 12: Symfony2 Introduction Presentation

3rd step The Data Model

Edit the parameters file;app/config/parameters.ini[parameters]    database_driver   = pdo_mysql    database_host     = localhost    database_name     = jobeet    database_user     = root    database_password = password

Use doctrine in command line to auto-create the database in mysql:

php app/console doctrine:database:create

Page 13: Symfony2 Introduction Presentation

3rd step The Data Model# src/Ens/JobeetBundle/Resources/config/doctrine/CategoryAffiliate.orm.ymlEns\JobeetBundle\Entity\CategoryAffiliate:  type: entity  table: category_affiliate  id:    id:      type: integer      generator: { strategy: AUTO }  manyToOne:    category:      targetEntity: Category      inversedBy: category_affiliates      joinColumn:        name: category_id        referencedColumnName: id    affiliate:      targetEntity: Affiliate      inversedBy: category_affiliates      joinColumn:        name: affiliate_id        referencedColumnName: id

Page 14: Symfony2 Introduction Presentation

3rd step The ORM • Now Doctrine can generate the classes that define our objects for us with the command:

php app/console doctrine:generate:entities EnsJobeetBundle

/**

• * Get location

• *

• * @return string

• */

• public function getLocation()

• {

• return $this->location;

• }

Page 15: Symfony2 Introduction Presentation

3rd step The ORM

We will also ask Doctrine to create our database tables (or to update them to reflect our setup) with the command:

php app/console doctrine:schema:update --forceUpdating database schema...Database schema updated successfully! "7" queries were executed

Page 16: Symfony2 Introduction Presentation

4th step Initial Data

• We will use DoctrineFixturesBundle.• Add the following to your deps file:

[doctrine-fixtures]git=http://github.com/doctrine/data-fixtures.git

[DoctrineFixturesBundle] git=http://github.com/doctrine/DoctrineFixturesBundle.git target=/bundles/Symfony/Bundle/DoctrineFixturesBundleversion=origin/2.0

• Update the vendor libraries:php bin/vendors install --reinstall

Page 17: Symfony2 Introduction Presentation
Page 18: Symfony2 Introduction Presentation

4th step Load data in tables

• To do this just execute this command:php app/console doctrine:fixtures:load

• See it in Action in the Browser• create a new controller with actions for listing, creating, editing and

deleting jobs executing this command:php app/console doctrine:generate:crud --entity=EnsJobeetBundle:Job --route-prefix=ens_job --with-write --format=yml

Page 19: Symfony2 Introduction Presentation
Page 20: Symfony2 Introduction Presentation
Page 21: Symfony2 Introduction Presentation

Till now?

• Barely written PHP code• Working web module for the job model• Ready to be tweaked and customized

Remember, no PHP code also means no bugs!

Page 22: Symfony2 Introduction Presentation

5th step The Layout

• Create a new file layout.html.twig in the src/Ens/JobeetBundle/Resources/views/ directory and put in the following code:

Page 23: Symfony2 Introduction Presentation
Page 24: Symfony2 Introduction Presentation

5th step The Layout

Tell Symfony to make them available to the public.php app/console assets:install web

Page 25: Symfony2 Introduction Presentation
Page 26: Symfony2 Introduction Presentation

5th step The Routing

• Used to be: /job.php?id=1• Now with symfony2: /job/1/show• Even: /job/sensio-labs/paris-france/1/web-developer

Page 27: Symfony2 Introduction Presentation

5th step The Routing

• Edit the ens_job_show route from the job.yml file:

# src/Ens/JobeetBundle/Resources/config/routing/job.yml

# ...ens_job_show:pattern: /{company}/{location}/{id}/{position}defaults: { _controller: "EnsJobeetBundle:Job:show" }

Page 28: Symfony2 Introduction Presentation

5th step The Routing

• Now, we need to pass all the parameters for the changed route for it to work:

<!-- src/Ens/JobeetBundle/Resources/views/Job/index.html.twig --><!-- ... --><a href="{{ path('ens_job_show', { 'id': entity.id, 'company':

entity.company, 'location': entity.location, 'position': entity.position }) }}">{{ entity.position }}</a><!-- ... -->

Page 29: Symfony2 Introduction Presentation

5th step The Routing

• NOW: http://jobeet.local/job/Sensio Labs/Paris, France/1/Web Developer• Need to remove spaces• This corrects the problem:

static public function slugify($text)

{

// replace all non letters or digits by -

$text = preg_replace('/\W+/', '-', $text);

// trim and lowercase

$text = strtolower(trim($text, '-'));

return $text;

}

Page 30: Symfony2 Introduction Presentation

5th step Route Debugging

• See every route in your application:php app/console router:debug

• Or a single route:php app/console router:debug ens_job_show

Page 31: Symfony2 Introduction Presentation
Page 32: Symfony2 Introduction Presentation

6th step Testing

• 2 methods:Unit tests and Functional tests

• Unit tests verify that each method and function is working properly• Functional tests verify that the resulting application behaves correctly

as a whole

Page 33: Symfony2 Introduction Presentation

7th and last step Bundles

• Bundles are like modules in Drupal.• Even symfony2 is a bundle itself.• Many useful bundles such as

-FOSUserBundle (Provides user management for your Symfony2 Project. Compatible with Doctrine ORM & ODM, and Propel)-SonataAdminBundle (AdminBundle - The missing Symfony2 Admin Generator)-FOSFacebookBundle (Integrate the Facebook Platform into

your Symfony2 application)-KnpPaginatorBundle (SEO friendly Symfony2 paginator to sort and paginate)

Page 34: Symfony2 Introduction Presentation

Q & AManual:-http://symfony.com/doc/current/book/index.html

Tutorial-http://www.ens.ro/2012/03/21/jobeet-tutorial-with-symfony2/