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
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.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
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 --forceUpdating 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/DoctrineFixturesBundleversion=origin/2.0
• Update the vendor libraries:php bin/vendors install --reinstall
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
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:
5th step The Layout
Tell Symfony to make them available to the public.php app/console assets:install web
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
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 & AManual:-http://symfony.com/doc/current/book/index.html
Tutorial-http://www.ens.ro/2012/03/21/jobeet-tutorial-with-symfony2/