SlideShare a Scribd company logo
Symfony2 Tutorial




    By Alexios Tzanetopoulos
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.
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.
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
Cons
• Requires command line (troll)
• Not easy to learn
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); ?>
Result?
• No error-checking
• Poor organization
• Difficult to reuse code
Ready to learn
symfony2?
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
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
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
3rd step The Data Model
# src/Ens/JobeetBundle/Resources/config/doctrine/CategoryAffiliate.orm.yml
EnsJobeetBundleEntityCategoryAffiliate:
 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
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;
•    }
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 --force
      Updating database schema...
      Database schema updated successfully! "7" queries were executed
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/DoctrineFixturesBundle
 version=origin/2.0
• Update the vendor libraries:
 php bin/vendors install --reinstall
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
Symfony2 Introduction Presentation
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!
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:
Symfony2 Introduction Presentation
5th step The Layout
Tell Symfony to make them available to the public.
      php app/console assets:install web
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
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" }
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>
      <!-- ... -->
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;
         }
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
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
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)
Q&A
Manual:
-http://symfony.com/doc/current/book/index.html

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

More Related Content

PDF
Symfony 2
PDF
Datagrids with Symfony 2, Backbone and Backgrid
PPTX
PHP 7 Crash Course - php[world] 2015
PDF
High Quality Symfony Bundles tutorial - Dutch PHP Conference 2014
PDF
Create a Symfony Application from a Drupal Perspective
PDF
Last train to php 7
PDF
PDF
Symfony internals [english]
Symfony 2
Datagrids with Symfony 2, Backbone and Backgrid
PHP 7 Crash Course - php[world] 2015
High Quality Symfony Bundles tutorial - Dutch PHP Conference 2014
Create a Symfony Application from a Drupal Perspective
Last train to php 7
Symfony internals [english]

What's hot (20)

PDF
Create your own composer package
PPT
PDF
Zend Framework 2 Components
PPT
Php Presentation
PDF
Behavior & Specification Driven Development in PHP - #OpenWest
PDF
What The Flask? and how to use it with some Google APIs
PPTX
Writing php extensions in golang
PPT
MySQL Presentation
KEY
CakePHP 2.0 - It'll rock your world
PDF
PDF
Introduction to PHP
PDF
Lean Php Presentation
PDF
A dive into Symfony 4
PDF
Ezobject wrapper workshop
PPTX
Php technical presentation
PPT
PHP Tutorials
PPT
Php Ppt
ODP
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
PPTX
PHP in one presentation
Create your own composer package
Zend Framework 2 Components
Php Presentation
Behavior & Specification Driven Development in PHP - #OpenWest
What The Flask? and how to use it with some Google APIs
Writing php extensions in golang
MySQL Presentation
CakePHP 2.0 - It'll rock your world
Introduction to PHP
Lean Php Presentation
A dive into Symfony 4
Ezobject wrapper workshop
Php technical presentation
PHP Tutorials
Php Ppt
Building Web Services with Zend Framework (PHP Benelux meeting 20100713 Vliss...
PHP in one presentation
Ad

Viewers also liked (20)

ODP
Presentation du framework symfony
PPT
Presentation Symfony
PPTX
Symfony 2 : chapitre 1 - Présentation Générale
PDF
Symfony 3
ODP
Introduction à CakePHP
PDF
Alphorm.com Support de la Formation Symfony 3 , les fondamentaux-ss
PDF
Introduction to symfony2
PPTX
Php symfony and software lifecycle
PPS
3.2 Les Infrastructures de données spatiales régionales développées dans le p...
PDF
de Google Maps à OpenStreetMap
PDF
Symfony2: Get your project started
PDF
Installation apache mandriva
DOC
PostgreSQL
PPT
Symfony ignite
ODP
ConfSL: Sviluppo Applicazioni web con Symfony
PDF
rapport_stage_issame
PDF
Angular2 with type script
KEY
Node.js et MongoDB: Mongoose
PDF
Bases de données spatiales
PDF
Bases de données Spatiales - POSTGIS
Presentation du framework symfony
Presentation Symfony
Symfony 2 : chapitre 1 - Présentation Générale
Symfony 3
Introduction à CakePHP
Alphorm.com Support de la Formation Symfony 3 , les fondamentaux-ss
Introduction to symfony2
Php symfony and software lifecycle
3.2 Les Infrastructures de données spatiales régionales développées dans le p...
de Google Maps à OpenStreetMap
Symfony2: Get your project started
Installation apache mandriva
PostgreSQL
Symfony ignite
ConfSL: Sviluppo Applicazioni web con Symfony
rapport_stage_issame
Angular2 with type script
Node.js et MongoDB: Mongoose
Bases de données spatiales
Bases de données Spatiales - POSTGIS
Ad

Similar to Symfony2 Introduction Presentation (20)

PDF
Working With The Symfony Admin Generator
PPS
Simplify your professional web development with symfony
PDF
RESTful API development in Laravel 4 - Christopher Pecoraro
PDF
Drupal 8 - Core and API Changes
PDF
Get things done with Yii - quickly build webapplications
PPTX
Creating your own framework on top of Symfony2 Components
PDF
Hands-on with the Symfony2 Framework
ODP
CodeIgniter PHP MVC Framework
PDF
Intro to drupal_7_architecture
PDF
Customizing oro crm webinar
PDF
Open erp technical_memento_v0.6.3_a4
PDF
WebNet Conference 2012 - Designing complex applications using html5 and knock...
PDF
The Basic Concept Of IOC
PPT
Edp bootstrapping a-software_company
PDF
MidwestPHP 2016 - Adventures in Laravel 5
PDF
OpenERP Technical Memento V0.7.3
PDF
Writing Ansible Modules (DENOG11)
PPT
Workshop: Symfony2 Intruduction: (Controller, Routing, Model)
PDF
OroCRM Partner Technical Training: September 2015
PPTX
Migrate yourself. code -> module -> mind
Working With The Symfony Admin Generator
Simplify your professional web development with symfony
RESTful API development in Laravel 4 - Christopher Pecoraro
Drupal 8 - Core and API Changes
Get things done with Yii - quickly build webapplications
Creating your own framework on top of Symfony2 Components
Hands-on with the Symfony2 Framework
CodeIgniter PHP MVC Framework
Intro to drupal_7_architecture
Customizing oro crm webinar
Open erp technical_memento_v0.6.3_a4
WebNet Conference 2012 - Designing complex applications using html5 and knock...
The Basic Concept Of IOC
Edp bootstrapping a-software_company
MidwestPHP 2016 - Adventures in Laravel 5
OpenERP Technical Memento V0.7.3
Writing Ansible Modules (DENOG11)
Workshop: Symfony2 Intruduction: (Controller, Routing, Model)
OroCRM Partner Technical Training: September 2015
Migrate yourself. code -> module -> mind

More from Nerd Tzanetopoulos (11)

PPTX
Ajax for dummies, and not only.
PPT
Symperasmata
PPT
PPT
PPT
PPT
Genikeuseis
PPT
PPT
Ypotheseis
PPT
PPT
Ergasia Kausima
PPT
εργασία καύσιμα
Ajax for dummies, and not only.
Symperasmata
Genikeuseis
Ypotheseis
Ergasia Kausima
εργασία καύσιμα

Recently uploaded (20)

PPTX
the-solar-system.pptxxxxxxxxxxxxxxxxxxxx
PPTX
BULAN K3 NASIONAL PowerPt Templates.pptx
PDF
TAIPANQQ SITUS MUDAH MENANG DAN MUDAH MAXWIN SEGERA DAFTAR DI TAIPANQQ DAN RA...
PPTX
TOEFL ITP Grammar_ Structure & Written Expression.pptx
PPTX
SPARSH-SVNITs-Annual-Cultural-Fest presentation for orientation
PPTX
Other Dance Forms - G10 MAPEH Reporting.pptx
PPT
business model and some other things that
PDF
Rakshabandhan – Celebrating the Bond of Siblings - by Meenakshi Khakat
PPTX
History ATA Presentation.pptxhttps://www.slideshare.net/slideshow/role-of-the...
PDF
EVs U-5 ONE SHOT Notes_c49f9e68-5eac-4201-bf86-b314ef5930ba.pdf
PPTX
providenetworksystemadministration.pptxhnnhgcbdjckk
PDF
Gess1025.pdfdadaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
PDF
Ct.pdffffffffffffffffffffffffffffffffffff
DOCX
Lambutchi Calin Claudiu had a discussion with the Buddha about the restructur...
DOCX
Nina Volyanska Controversy in Fishtank Live_ Unraveling the Mystery Behind th...
PDF
WKA #29: "FALLING FOR CUPID" TRANSCRIPT.pdf
PDF
My Oxford Year- A Love Story Set in the Halls of Oxford
DOC
NSCAD毕业证学历认证,温哥华岛大学毕业证国外证书制作申请
PPTX
asdmadsmammmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm.pptx
PPTX
wegen seminar ppt.pptxhkjbkhkjjlhjhjhlhhvg
the-solar-system.pptxxxxxxxxxxxxxxxxxxxx
BULAN K3 NASIONAL PowerPt Templates.pptx
TAIPANQQ SITUS MUDAH MENANG DAN MUDAH MAXWIN SEGERA DAFTAR DI TAIPANQQ DAN RA...
TOEFL ITP Grammar_ Structure & Written Expression.pptx
SPARSH-SVNITs-Annual-Cultural-Fest presentation for orientation
Other Dance Forms - G10 MAPEH Reporting.pptx
business model and some other things that
Rakshabandhan – Celebrating the Bond of Siblings - by Meenakshi Khakat
History ATA Presentation.pptxhttps://www.slideshare.net/slideshow/role-of-the...
EVs U-5 ONE SHOT Notes_c49f9e68-5eac-4201-bf86-b314ef5930ba.pdf
providenetworksystemadministration.pptxhnnhgcbdjckk
Gess1025.pdfdadaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
Ct.pdffffffffffffffffffffffffffffffffffff
Lambutchi Calin Claudiu had a discussion with the Buddha about the restructur...
Nina Volyanska Controversy in Fishtank Live_ Unraveling the Mystery Behind th...
WKA #29: "FALLING FOR CUPID" TRANSCRIPT.pdf
My Oxford Year- A Love Story Set in the Halls of Oxford
NSCAD毕业证学历认证,温哥华岛大学毕业证国外证书制作申请
asdmadsmammmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmmm.pptx
wegen seminar ppt.pptxhkjbkhkjjlhjhjhlhhvg

Symfony2 Introduction Presentation

  • 1. Symfony2 Tutorial By Alexios Tzanetopoulos
  • 2. 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.
  • 3. 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.
  • 4. 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
  • 5. Cons • Requires command line (troll) • Not easy to learn
  • 6. 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); ?>
  • 7. Result? • No error-checking • Poor organization • Difficult to reuse code
  • 9. 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
  • 11. 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
  • 12. 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
  • 13. 3rd step The Data Model # src/Ens/JobeetBundle/Resources/config/doctrine/CategoryAffiliate.orm.yml EnsJobeetBundleEntityCategoryAffiliate: 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
  • 14. 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; • }
  • 15. 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 --force Updating database schema... Database schema updated successfully! "7" queries were executed
  • 16. 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/DoctrineFixturesBundle version=origin/2.0 • Update the vendor libraries: php bin/vendors install --reinstall
  • 18. 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
  • 21. 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!
  • 22. 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:
  • 24. 5th step The Layout Tell Symfony to make them available to the public. php app/console assets:install web
  • 26. 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
  • 27. 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" }
  • 28. 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> <!-- ... -->
  • 29. 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; }
  • 30. 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
  • 32. 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
  • 33. 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)