SlideShare a Scribd company logo
1 of 23
Fast relational web site
construction with PHP




 Nelson Gomes (nelson.gomes@telecom.pt)
  Team Leader
  ZCE, ITIL Foundation V3, LPIC1-101
  16th of November 2012
Talk Index

Introduction
Frameworks
Relational Database Model
Setting up
The 'Magic'
Queries
Transactions
Conclusion
Links
Q&A
Introduction

The purpose of this talk is to help web developers to take
  advantage of some known PHP frameworks to develop
  complex websites rapidly;
Although we're showing some specific frameworks in this
  talk, other frameworks exist that do almost the same thing
  or even better;
Just google the web and try out other frameworks and use
  the ones you like the most;
The benefit of using these frameworks is to be more
  productive, to use best pratices and to develop faster;
Introduction (cont.)

Developing complex sites with complex relational databases
  can be very difficult without the right tools:
  Manage Database Connections;
  Maintaining Relational Integrity;
  Performing Transactions;
  Acessing data spread over several tables;
  Updating, deleting and inserting records without loosing
    integrity;
Introduction (cont.)

Example of how some developers still program:
 mysql_query(“insert into customers (name, phone) values
     ('$name', '$phone');


When using many tables the developers need to create
  methods to insert, update, delete and query records, this can
  give a lot of work;


In this presentation, I'll try to show how to do all of this
  with minimum programming...
Introduction (cont.)

Web site security depends greatly of the awareness
  developers have for security issues;
Many PHP developers do bad code because don't know the
  problems that can arise from bad programming:
  SQL Injection;
  Cross-Site Scripting;
  Cross-Site Request Forgery;
  (...)
Using these frameworks correctly reduce (some) security
  vulnerabilities;
Introduction (cont.)

Other frameworks:
  Propel;
  Zend_Db;
  Log4PHP;
  Zend;
  Symfony;
  xAjax;
  NuSOAP;
Frameworks

Introducing some PHP frameworks:
  Doctrine – is a Object relational mapper that works on
    top of PDO (PHP Data Objects);
  Smarty – an engine for web templating in PHP;
  MVC – (could use one MVC framework, but on this talk
    won't use any);


You can easily change any of these frameworks with others
  of your choice;
Frameworks (cont.)

Doctrine
  With Doctrine you can use 'Code First', 'Model First' and
    'Database First' approaches, meaning you start by
    creating objects, UML or a database as a start point;
  All doctrine queries are made using DQL – Doctrine
    Query Language;
In this talk we'll go throught 'Database First' approach,
  meaning Doctrine will look into the database and generate
  code for it;
In this talk I'm using Doctrine 1.2.4, why?
Frameworks (cont.)

Advantages of using Doctrine:
 Object Oriented Approach;
  No need to rewrite code when switching database;
  No need to keep track of identifiers of the inserted fields;
  Object are written to database by Doctrine, no need to
    SQL!
  Associations are managed by Doctrine;
  Database can be generated by our models (yaml, xml)
Frameworks (cont.)

Smarty
  Is a template engine for PHP;
  Allows separating design from code;
  Eases the maintainability of on large web sites;
  Allows reuse of templates;
  Makes your website go faster;
  Improves security;
  Easily extensible;
Relational Database Model
Setting Up

Doctrine:
 require_once BASE_DIR.'/lib/Doctrine­1.2.4/Doctrine.php';
 spl_autoload_register(array('Doctrine', 'autoload'));
 spl_autoload_register(array('Doctrine', 'modelsAutoload'));


 $manager = Doctrine_Manager::getInstance();
 $manager­>setAttribute(Doctrine::ATTR_MODEL_LOADING, 
    Doctrine::MODEL_LOADING_CONSERVATIVE);
 $manager­>setCharset('utf8');
 $manager­>connection('mysql://codebits:codebits@127.0.0.1/codebits');
 if (DEBUGMODE) 
       Doctrine::generateModelsFromDb(dirname(__FILE__).'/models/');
 Doctrine::loadModels(dirname(__FILE__).'/models/');
Setting Up (cont.)

Smarty:

 require_once(BASE_DIR.'/lib/Smarty­3.1.12/libs/Smarty.class.php');


 $smarty = new Smarty();
 $smarty­>template_dir = dirname(__FILE__).'/lib/templates/';
 $smarty­>compile_dir  = dirname(__FILE__).'/lib/templates_c/';
 $smarty­>config_dir   = dirname(__FILE__).'/lib/configs/';
 $smarty­>cache_dir    = dirname(__FILE__).'/cache/';


 $smarty­>compile_check=DEBUGMODE;
The 'Magic'

Folder models has been filled by Doctrine with code:
    models/*.php (to fill with your business logic);
    models/generated/*.php (object definitions);


Folder lib/templates_c/*.php has been filled by Smarty with
  munged templates;


Now that the magic is working let's fill a web page with the
  data we have in the tables!
The 'Magic'

Declaring table relations using hasMany, hasOne:

class Customers extends BaseCustomers {
    public function setUp() {
        $this­>hasMany('CustomerUsers as relatedUsers',
              array(
                  'local'=>'id',
                  'foreign'=>'fk_customer_id',
              )
        );
        (…)
    }
}
The 'Magic'

Avoiding XSS in Smarty:
  function escFilter($content,$smarty) { 
      return htmlspecialchars($content,ENT_QUOTES,UTF­8);
  }
  $smarty­>registerFilter('variable','escFilter');



To show unsafe content just explicitly do:
  {$variable nofilter}



Doctrine manages strings avoiding SQL Injection attempts!
  (but cannot do miracles!)
Transactions

But a good business layer only works well if it is
  transactional, to maintain relational integrity.
  $conn=Doctrine_Manager::connection();
  try{
      $conn­>beginTransaction();
      $customer=new Customers();
      $customer­>name=$name; (...)
      $customer­>save();
      $address=new Addresses();
      $address­>fk_customer_id=$customer­>id; (...)
      $address­>save();
   $conn­>commit();
  } catch(Exception $ex) {
      $conn­>rollback();
  }
Queries

Any language or framework is secure depending on how
  users use it:

  static function updateCustomerName($name, $id) {
      $conn=Doctrine_Manager::connection();
      $conn­>execute(“update customers set name='$name' where id=$id”);
  }



Bad pratice to concat any user input, use instead Doctrine
  methods!
The above example can also be database dependant which
  isn't a good practice.
Queries

Usind DQL:
   static function getAllUserCustomers($id,$page=0){
   return Doctrine_Query::create()
       ­>select('c.*')
       ­>from('Customers c')
       ­>where('c.relatedUsers.fk_customer_id=:userid', 
            array(':userid'=>$id))
       ­>orderBy('c.name')
       ­>limit(20)
       ­>offset($page*20)
       #­>getSqlQuery();
       ­>execute();
   }
Conclusion

In this demo:
  We accessed data scattered over 7 different tables with
    (almost) zero programming;
  We didn't established or managed any connection;
  Our application can be now easily converted to another
    database engine with minimum effort;
  Each page is only a couple of lines in size, no more
    HTML embedding nightmares...;
  Our application has become more secure;
  In a couple of minutes...
Links

http://www.doctrine-project.org/
http://www.smarty.net/
http://logging.apache.org/log4php/
http://code.google.com/p/nusoap-for-php5/
http://www.zend.com/
http://www.xajaxproject.org/
(...)
Q&A




      Thank You

More Related Content

What's hot

My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I thinkWim Godden
 
New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)Markus Eisele
 
Building Custom AngularJS Directives - A Step-by-Step Guide - Dan Wahlin | Fa...
Building Custom AngularJS Directives - A Step-by-Step Guide - Dan Wahlin | Fa...Building Custom AngularJS Directives - A Step-by-Step Guide - Dan Wahlin | Fa...
Building Custom AngularJS Directives - A Step-by-Step Guide - Dan Wahlin | Fa...FalafelSoftware
 
AngularJS for designers and developers
AngularJS for designers and developersAngularJS for designers and developers
AngularJS for designers and developersKai Koenig
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I thinkWim Godden
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsCarol McDonald
 
Hacking hhvm
Hacking hhvmHacking hhvm
Hacking hhvmwajrcs
 
Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)ejlp12
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)Igor Bronovskyy
 
Custom AngularJS Directives
Custom AngularJS DirectivesCustom AngularJS Directives
Custom AngularJS Directivesyprodev
 
Laravel 5.2 Gates, AuthServiceProvider and Policies
Laravel 5.2 Gates, AuthServiceProvider and PoliciesLaravel 5.2 Gates, AuthServiceProvider and Policies
Laravel 5.2 Gates, AuthServiceProvider and PoliciesAlison Gianotto
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS ArchitectureEyal Vardi
 
Powerful persistence layer with Google Guice & MyBatis
Powerful persistence layer with Google Guice & MyBatisPowerful persistence layer with Google Guice & MyBatis
Powerful persistence layer with Google Guice & MyBatissimonetripodi
 
Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014Greg Szczotka
 
Basics of angular directive (Part - 1)
Basics of angular directive (Part - 1)Basics of angular directive (Part - 1)
Basics of angular directive (Part - 1)Vijay Kani
 
Angular Directives from Scratch
Angular Directives from ScratchAngular Directives from Scratch
Angular Directives from ScratchChristian Lilley
 
Entity Persistence with JPA
Entity Persistence with JPAEntity Persistence with JPA
Entity Persistence with JPASubin Sugunan
 

What's hot (20)

My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)New Features of JSR 317 (JPA 2.0)
New Features of JSR 317 (JPA 2.0)
 
Building Custom AngularJS Directives - A Step-by-Step Guide - Dan Wahlin | Fa...
Building Custom AngularJS Directives - A Step-by-Step Guide - Dan Wahlin | Fa...Building Custom AngularJS Directives - A Step-by-Step Guide - Dan Wahlin | Fa...
Building Custom AngularJS Directives - A Step-by-Step Guide - Dan Wahlin | Fa...
 
AngularJS for designers and developers
AngularJS for designers and developersAngularJS for designers and developers
AngularJS for designers and developers
 
My app is secure... I think
My app is secure... I thinkMy app is secure... I think
My app is secure... I think
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.js
 
Hacking hhvm
Hacking hhvmHacking hhvm
Hacking hhvm
 
Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)Introduction to JPA (JPA version 2.0)
Introduction to JPA (JPA version 2.0)
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
 
Custom AngularJS Directives
Custom AngularJS DirectivesCustom AngularJS Directives
Custom AngularJS Directives
 
Laravel 5.2 Gates, AuthServiceProvider and Policies
Laravel 5.2 Gates, AuthServiceProvider and PoliciesLaravel 5.2 Gates, AuthServiceProvider and Policies
Laravel 5.2 Gates, AuthServiceProvider and Policies
 
JPA Best Practices
JPA Best PracticesJPA Best Practices
JPA Best Practices
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS Architecture
 
Powerful persistence layer with Google Guice & MyBatis
Powerful persistence layer with Google Guice & MyBatisPowerful persistence layer with Google Guice & MyBatis
Powerful persistence layer with Google Guice & MyBatis
 
Simple Jdbc With Spring 2.5
Simple Jdbc With Spring 2.5Simple Jdbc With Spring 2.5
Simple Jdbc With Spring 2.5
 
Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014Dependency injection Drupal Camp Wrocław 2014
Dependency injection Drupal Camp Wrocław 2014
 
Java persistence api 2.1
Java persistence api 2.1Java persistence api 2.1
Java persistence api 2.1
 
Basics of angular directive (Part - 1)
Basics of angular directive (Part - 1)Basics of angular directive (Part - 1)
Basics of angular directive (Part - 1)
 
Angular Directives from Scratch
Angular Directives from ScratchAngular Directives from Scratch
Angular Directives from Scratch
 
Entity Persistence with JPA
Entity Persistence with JPAEntity Persistence with JPA
Entity Persistence with JPA
 

Viewers also liked

Small Biz CEDC Introduction
Small Biz CEDC IntroductionSmall Biz CEDC Introduction
Small Biz CEDC IntroductionMary Phillips
 
Cinco claves de los mercados hoteleros de Madrid y Barcelona 2016
Cinco claves de los mercados hoteleros de Madrid y Barcelona 2016Cinco claves de los mercados hoteleros de Madrid y Barcelona 2016
Cinco claves de los mercados hoteleros de Madrid y Barcelona 2016Turistenístico
 
Шкільний екологічний клуб “Веселка” у системі виховної роботи
Шкільний екологічний клуб  “Веселка”  у системі виховної роботи Шкільний екологічний клуб  “Веселка”  у системі виховної роботи
Шкільний екологічний клуб “Веселка” у системі виховної роботи Марина Д
 
RTCG - Patent Publication
RTCG - Patent PublicationRTCG - Patent Publication
RTCG - Patent PublicationEitan Keren
 
Анимационный ролик мир вокруг нас
Анимационный ролик мир вокруг насАнимационный ролик мир вокруг нас
Анимационный ролик мир вокруг насМарина Д
 
The Right Kind of Startups
The Right Kind of StartupsThe Right Kind of Startups
The Right Kind of StartupsAtomic Object
 
El principito ayelen gaspar
El principito ayelen gasparEl principito ayelen gaspar
El principito ayelen gasparayelengaspar
 
Alfonso pinilla ej tema 4
Alfonso pinilla ej tema 4Alfonso pinilla ej tema 4
Alfonso pinilla ej tema 4Slavah
 
Identifying Antibiotics posing potential Health Risk: Microbial Resistance Sc...
Identifying Antibiotics posing potential Health Risk: Microbial Resistance Sc...Identifying Antibiotics posing potential Health Risk: Microbial Resistance Sc...
Identifying Antibiotics posing potential Health Risk: Microbial Resistance Sc...Atai Rabby
 
Public Management 2012
Public Management 2012Public Management 2012
Public Management 2012Der Konijnen
 
What Millennials Want in Meetings
What Millennials Want in MeetingsWhat Millennials Want in Meetings
What Millennials Want in MeetingsTuristenístico
 
LinkedIn Recruiting Solutions
LinkedIn Recruiting SolutionsLinkedIn Recruiting Solutions
LinkedIn Recruiting SolutionsDrew Wills
 

Viewers also liked (20)

Small Biz CEDC Introduction
Small Biz CEDC IntroductionSmall Biz CEDC Introduction
Small Biz CEDC Introduction
 
Horror film trailers
Horror film trailersHorror film trailers
Horror film trailers
 
Power
PowerPower
Power
 
Cinco claves de los mercados hoteleros de Madrid y Barcelona 2016
Cinco claves de los mercados hoteleros de Madrid y Barcelona 2016Cinco claves de los mercados hoteleros de Madrid y Barcelona 2016
Cinco claves de los mercados hoteleros de Madrid y Barcelona 2016
 
Шкільний екологічний клуб “Веселка” у системі виховної роботи
Шкільний екологічний клуб  “Веселка”  у системі виховної роботи Шкільний екологічний клуб  “Веселка”  у системі виховної роботи
Шкільний екологічний клуб “Веселка” у системі виховної роботи
 
RTCG - Patent Publication
RTCG - Patent PublicationRTCG - Patent Publication
RTCG - Patent Publication
 
Анимационный ролик мир вокруг нас
Анимационный ролик мир вокруг насАнимационный ролик мир вокруг нас
Анимационный ролик мир вокруг нас
 
The Right Kind of Startups
The Right Kind of StartupsThe Right Kind of Startups
The Right Kind of Startups
 
El principito ayelen gaspar
El principito ayelen gasparEl principito ayelen gaspar
El principito ayelen gaspar
 
公司简介
公司简介公司简介
公司简介
 
Ruby, Meet iPhone
Ruby, Meet iPhoneRuby, Meet iPhone
Ruby, Meet iPhone
 
Alfonso pinilla ej tema 4
Alfonso pinilla ej tema 4Alfonso pinilla ej tema 4
Alfonso pinilla ej tema 4
 
Shandra Spears Bombay 2011 2
Shandra Spears Bombay 2011 2Shandra Spears Bombay 2011 2
Shandra Spears Bombay 2011 2
 
WLCF
WLCFWLCF
WLCF
 
Identifying Antibiotics posing potential Health Risk: Microbial Resistance Sc...
Identifying Antibiotics posing potential Health Risk: Microbial Resistance Sc...Identifying Antibiotics posing potential Health Risk: Microbial Resistance Sc...
Identifying Antibiotics posing potential Health Risk: Microbial Resistance Sc...
 
Public Management 2012
Public Management 2012Public Management 2012
Public Management 2012
 
Multicultural education
Multicultural educationMulticultural education
Multicultural education
 
What Millennials Want in Meetings
What Millennials Want in MeetingsWhat Millennials Want in Meetings
What Millennials Want in Meetings
 
Slide Share
Slide Share Slide Share
Slide Share
 
LinkedIn Recruiting Solutions
LinkedIn Recruiting SolutionsLinkedIn Recruiting Solutions
LinkedIn Recruiting Solutions
 

Similar to Codebits 2012 - Fast relational web site construction.

Javascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsJavascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsSoós Gábor
 
Osiąganie mądrej architektury z Symfony2
Osiąganie mądrej architektury z Symfony2 Osiąganie mądrej architektury z Symfony2
Osiąganie mądrej architektury z Symfony2 3camp
 
Introduction To Code Igniter
Introduction To Code IgniterIntroduction To Code Igniter
Introduction To Code IgniterAmzad Hossain
 
Finding Your Way: Understanding Magento Code
Finding Your Way: Understanding Magento CodeFinding Your Way: Understanding Magento Code
Finding Your Way: Understanding Magento CodeBen Marks
 
Web internship Yii Framework
Web internship  Yii FrameworkWeb internship  Yii Framework
Web internship Yii FrameworkNoveo
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's CodeWildan Maulana
 
Mojolicious, real-time web framework
Mojolicious, real-time web frameworkMojolicious, real-time web framework
Mojolicious, real-time web frameworktaggg
 
Symfony2 - from the trenches
Symfony2 - from the trenchesSymfony2 - from the trenches
Symfony2 - from the trenchesLukas Smith
 
Drupal Best Practices
Drupal Best PracticesDrupal Best Practices
Drupal Best Practicesmanugoel2003
 
Php & my sql - how do pdo, mysq-li, and x devapi do what they do
Php & my sql  - how do pdo, mysq-li, and x devapi do what they doPhp & my sql  - how do pdo, mysq-li, and x devapi do what they do
Php & my sql - how do pdo, mysq-li, and x devapi do what they doDave Stokes
 
Php interview questions
Php interview questionsPhp interview questions
Php interview questionssekar c
 
[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress Development[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress DevelopmentAdam Tomat
 
Working With The Symfony Admin Generator
Working With The Symfony Admin GeneratorWorking With The Symfony Admin Generator
Working With The Symfony Admin GeneratorJohn Cleveley
 
ONE MORE TIME ABOUT CODE STANDARDS AND BEST PRACTICES
ONE MORE TIME ABOUT CODE STANDARDS AND BEST PRACTICESONE MORE TIME ABOUT CODE STANDARDS AND BEST PRACTICES
ONE MORE TIME ABOUT CODE STANDARDS AND BEST PRACTICESDrupalCamp Kyiv
 
Drupal Security from Drupalcamp Bratislava
Drupal Security from Drupalcamp BratislavaDrupal Security from Drupalcamp Bratislava
Drupal Security from Drupalcamp BratislavaGábor Hojtsy
 

Similar to Codebits 2012 - Fast relational web site construction. (20)

Javascript frameworks: Backbone.js
Javascript frameworks: Backbone.jsJavascript frameworks: Backbone.js
Javascript frameworks: Backbone.js
 
Osiąganie mądrej architektury z Symfony2
Osiąganie mądrej architektury z Symfony2 Osiąganie mądrej architektury z Symfony2
Osiąganie mądrej architektury z Symfony2
 
Introduction To Code Igniter
Introduction To Code IgniterIntroduction To Code Igniter
Introduction To Code Igniter
 
Finding Your Way: Understanding Magento Code
Finding Your Way: Understanding Magento CodeFinding Your Way: Understanding Magento Code
Finding Your Way: Understanding Magento Code
 
Codegnitorppt
CodegnitorpptCodegnitorppt
Codegnitorppt
 
Web internship Yii Framework
Web internship  Yii FrameworkWeb internship  Yii Framework
Web internship Yii Framework
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
 
Mojolicious, real-time web framework
Mojolicious, real-time web frameworkMojolicious, real-time web framework
Mojolicious, real-time web framework
 
Symfony2 - from the trenches
Symfony2 - from the trenchesSymfony2 - from the trenches
Symfony2 - from the trenches
 
Drupal Best Practices
Drupal Best PracticesDrupal Best Practices
Drupal Best Practices
 
Php & my sql - how do pdo, mysq-li, and x devapi do what they do
Php & my sql  - how do pdo, mysq-li, and x devapi do what they doPhp & my sql  - how do pdo, mysq-li, and x devapi do what they do
Php & my sql - how do pdo, mysq-li, and x devapi do what they do
 
Php interview questions
Php interview questionsPhp interview questions
Php interview questions
 
Fatc
FatcFatc
Fatc
 
Yii Introduction
Yii IntroductionYii Introduction
Yii Introduction
 
[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress Development[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress Development
 
Working With The Symfony Admin Generator
Working With The Symfony Admin GeneratorWorking With The Symfony Admin Generator
Working With The Symfony Admin Generator
 
Ruby For Startups
Ruby For StartupsRuby For Startups
Ruby For Startups
 
Intro to Laravel 4
Intro to Laravel 4Intro to Laravel 4
Intro to Laravel 4
 
ONE MORE TIME ABOUT CODE STANDARDS AND BEST PRACTICES
ONE MORE TIME ABOUT CODE STANDARDS AND BEST PRACTICESONE MORE TIME ABOUT CODE STANDARDS AND BEST PRACTICES
ONE MORE TIME ABOUT CODE STANDARDS AND BEST PRACTICES
 
Drupal Security from Drupalcamp Bratislava
Drupal Security from Drupalcamp BratislavaDrupal Security from Drupalcamp Bratislava
Drupal Security from Drupalcamp Bratislava
 

Codebits 2012 - Fast relational web site construction.

  • 1. Fast relational web site construction with PHP  Nelson Gomes (nelson.gomes@telecom.pt) Team Leader ZCE, ITIL Foundation V3, LPIC1-101 16th of November 2012
  • 2. Talk Index Introduction Frameworks Relational Database Model Setting up The 'Magic' Queries Transactions Conclusion Links Q&A
  • 3. Introduction The purpose of this talk is to help web developers to take advantage of some known PHP frameworks to develop complex websites rapidly; Although we're showing some specific frameworks in this talk, other frameworks exist that do almost the same thing or even better; Just google the web and try out other frameworks and use the ones you like the most; The benefit of using these frameworks is to be more productive, to use best pratices and to develop faster;
  • 4. Introduction (cont.) Developing complex sites with complex relational databases can be very difficult without the right tools: Manage Database Connections; Maintaining Relational Integrity; Performing Transactions; Acessing data spread over several tables; Updating, deleting and inserting records without loosing integrity;
  • 5. Introduction (cont.) Example of how some developers still program: mysql_query(“insert into customers (name, phone) values ('$name', '$phone'); When using many tables the developers need to create methods to insert, update, delete and query records, this can give a lot of work; In this presentation, I'll try to show how to do all of this with minimum programming...
  • 6. Introduction (cont.) Web site security depends greatly of the awareness developers have for security issues; Many PHP developers do bad code because don't know the problems that can arise from bad programming: SQL Injection; Cross-Site Scripting; Cross-Site Request Forgery; (...) Using these frameworks correctly reduce (some) security vulnerabilities;
  • 7. Introduction (cont.) Other frameworks: Propel; Zend_Db; Log4PHP; Zend; Symfony; xAjax; NuSOAP;
  • 8. Frameworks Introducing some PHP frameworks: Doctrine – is a Object relational mapper that works on top of PDO (PHP Data Objects); Smarty – an engine for web templating in PHP; MVC – (could use one MVC framework, but on this talk won't use any); You can easily change any of these frameworks with others of your choice;
  • 9. Frameworks (cont.) Doctrine With Doctrine you can use 'Code First', 'Model First' and 'Database First' approaches, meaning you start by creating objects, UML or a database as a start point; All doctrine queries are made using DQL – Doctrine Query Language; In this talk we'll go throught 'Database First' approach, meaning Doctrine will look into the database and generate code for it; In this talk I'm using Doctrine 1.2.4, why?
  • 10. Frameworks (cont.) Advantages of using Doctrine: Object Oriented Approach; No need to rewrite code when switching database; No need to keep track of identifiers of the inserted fields; Object are written to database by Doctrine, no need to SQL! Associations are managed by Doctrine; Database can be generated by our models (yaml, xml)
  • 11. Frameworks (cont.) Smarty Is a template engine for PHP; Allows separating design from code; Eases the maintainability of on large web sites; Allows reuse of templates; Makes your website go faster; Improves security; Easily extensible;
  • 13. Setting Up Doctrine: require_once BASE_DIR.'/lib/Doctrine­1.2.4/Doctrine.php'; spl_autoload_register(array('Doctrine', 'autoload')); spl_autoload_register(array('Doctrine', 'modelsAutoload')); $manager = Doctrine_Manager::getInstance(); $manager­>setAttribute(Doctrine::ATTR_MODEL_LOADING,  Doctrine::MODEL_LOADING_CONSERVATIVE); $manager­>setCharset('utf8'); $manager­>connection('mysql://codebits:codebits@127.0.0.1/codebits'); if (DEBUGMODE)  Doctrine::generateModelsFromDb(dirname(__FILE__).'/models/'); Doctrine::loadModels(dirname(__FILE__).'/models/');
  • 14. Setting Up (cont.) Smarty: require_once(BASE_DIR.'/lib/Smarty­3.1.12/libs/Smarty.class.php'); $smarty = new Smarty(); $smarty­>template_dir = dirname(__FILE__).'/lib/templates/'; $smarty­>compile_dir  = dirname(__FILE__).'/lib/templates_c/'; $smarty­>config_dir   = dirname(__FILE__).'/lib/configs/'; $smarty­>cache_dir    = dirname(__FILE__).'/cache/'; $smarty­>compile_check=DEBUGMODE;
  • 15. The 'Magic' Folder models has been filled by Doctrine with code: models/*.php (to fill with your business logic); models/generated/*.php (object definitions); Folder lib/templates_c/*.php has been filled by Smarty with munged templates; Now that the magic is working let's fill a web page with the data we have in the tables!
  • 16. The 'Magic' Declaring table relations using hasMany, hasOne: class Customers extends BaseCustomers { public function setUp() { $this­>hasMany('CustomerUsers as relatedUsers', array( 'local'=>'id', 'foreign'=>'fk_customer_id', ) ); (…) } }
  • 17. The 'Magic' Avoiding XSS in Smarty: function escFilter($content,$smarty) {  return htmlspecialchars($content,ENT_QUOTES,UTF­8); } $smarty­>registerFilter('variable','escFilter'); To show unsafe content just explicitly do: {$variable nofilter} Doctrine manages strings avoiding SQL Injection attempts! (but cannot do miracles!)
  • 18. Transactions But a good business layer only works well if it is transactional, to maintain relational integrity. $conn=Doctrine_Manager::connection(); try{ $conn­>beginTransaction(); $customer=new Customers(); $customer­>name=$name; (...) $customer­>save(); $address=new Addresses(); $address­>fk_customer_id=$customer­>id; (...) $address­>save();  $conn­>commit(); } catch(Exception $ex) { $conn­>rollback(); }
  • 19. Queries Any language or framework is secure depending on how users use it: static function updateCustomerName($name, $id) { $conn=Doctrine_Manager::connection(); $conn­>execute(“update customers set name='$name' where id=$id”); } Bad pratice to concat any user input, use instead Doctrine methods! The above example can also be database dependant which isn't a good practice.
  • 20. Queries Usind DQL: static function getAllUserCustomers($id,$page=0){ return Doctrine_Query::create() ­>select('c.*') ­>from('Customers c') ­>where('c.relatedUsers.fk_customer_id=:userid',  array(':userid'=>$id)) ­>orderBy('c.name') ­>limit(20) ­>offset($page*20) #­>getSqlQuery(); ­>execute(); }
  • 21. Conclusion In this demo: We accessed data scattered over 7 different tables with (almost) zero programming; We didn't established or managed any connection; Our application can be now easily converted to another database engine with minimum effort; Each page is only a couple of lines in size, no more HTML embedding nightmares...; Our application has become more secure; In a couple of minutes...
  • 23. Q&A Thank You