Saturday, June 16, 12. Introducing

Similar documents
Symfony2 and Drupal. Why to talk about Symfony2 framework?

Drupal 8. Core and API Changes Shabir Ahmad MS Software Engg. NUST Principal Software Engineser PHP/Drupal

A Tour of Silex and Symfony Components. Robert

Object Oriented Software Design - I

Practical Guided Tour of Symfony

The Book for Symfony 2.0

Symfony2: estudo de caso IngressoPrático

How To Design Your Code In Php (Php)

The Book. Prepared by the core team, this is the Symfony bible. It is the reference for any user of the platform,

Stop being Rails developer

Cache All The Things

EZ PLATFORM DESIGN AND DEVELOP CONTENT-DRIVEN WEBSITES AND APPLICATIONS

Dashboard Skin Tutorial. For ETS2 HTML5 Mobile Dashboard v3.0.2

Web Frameworks. web development done right. Course of Web Technologies A.A. 2010/2011 Valerio Maggio, PhD Student Prof.

Patterns in. Lecture 2 GoF Design Patterns Creational. Sharif University of Technology. Department of Computer Engineering

Preparing for Drupal 8

Everything you ever wanted to know about Drupal 8*

Drupal 8 The site builder's release

MASTERTAG DEVELOPER GUIDE

A new theme layer for Drupal 8? with jenlampton, chx, JohnAlbin, mortendk, effulgentsia, EclipseGc, & davidneedham

FormAPI, AJAX and Node.js

Design with Reuse. Building software from reusable components. Ian Sommerville 2000 Software Engineering, 6th edition. Chapter 14 Slide 1

5 Mistakes to Avoid on Your Drupal Website

Software Engineering. Software Engineering. Component-Based. Based on Software Engineering, 7 th Edition by Ian Sommerville

The Django web development framework for the Python-aware

Ingegneria del Software Corso di Laurea in Informatica per il Management. Object Oriented Principles

Automatic vs. Manual Code Analysis

Business Application Development Platform

Realization of Inventory Databases and Object-Relational Mapping for the Common Information Model

How To Draw A Cell Phone Into A Cellphone In Unminimal Diagram (Uml)

Here is a quick diagram of the ULV SSO/Sync Application. Number 3 is what we deal with in this document.

Gantry Basics. Presented By: Jesse Hammil (Peanut Gallery: David Beuving)

The Components Book Version: master

<Insert Picture Here> What's New in NetBeans IDE 7.2

Drupal and ArcGIS Yes, it can be done. Frank McLean Developer

TOSCA Interoperability Demonstration

Drupal to WordPress migration worksheet

Paul Boisvert. Director Product Management, Magento

Accelerating Wordpress for Pagerank and Profit

Creating Value through Innovation MAGENTO 1.X TO MAGENTO 2.0 MIGRATION

PRIVACY AWARE ACCESS CONTROL FOR CLOUD-BASED DATA PLATFORMS

HYBRID. Course Packet

GlassFish v3. Building an ex tensible modular Java EE application server. Jerome Dochez and Ludovic Champenois Sun Microsystems, Inc.

Tutorial: Building a Dojo Application using IBM Rational Application Developer Loan Payment Calculator

OO Design Quality Metrics

FROM COMPILER SWITCHES TO STRATEGIC REUSE

Requirements Management

easy_review version BoostMyShop

Faichi Solutions. The Changing Face of Drupal with Drupal 8

Cross Site Scripting (XSS) and PHP Security. Anthony Ferrara NYPHP and OWASP Security Series June 30, 2011

Drupal 8 Theming. Exploring Twig & Other Frontend Changes CROWD. Communications Group, LLC CROWD. Communications Group, LLC

(An) Optimal Drupal 7 Module Configuration for Site Performance JOE PRICE

Beyond The Web Drupal Meets The Desktop (And Mobile) Justin Miller Code Sorcery Workshop, LLC

EXAM PRO:Design & Develop Windows Apps Using MS.NET Frmwk 4. Buy Full Product.

PROJECT REPORT OF BUILDING COURSE MANAGEMENT SYSTEM BY DJANGO FRAMEWORK

Building a Modular Server Platform with OSGi. Dileepa Jayakody Software Engineer SSWSO2 Inc.

GUI and Web Programming

Solution Guide. Optimizing Microsoft SharePoint 2013 with Citrix NetScaler. citrix.com

Design Patterns. Design patterns are known solutions for common problems. Design patterns give us a system of names and ideas for common problems.

Client-server 3-tier N-tier

The Rules 1. One level of indentation per method 2. Don t use the ELSE keyword 3. Wrap all primitives and Strings

SharePoint 2010 End User - Level II

Drupal 6 to Drupal 7 Migration Worksheet

Frameworks & Android. Programmeertechnieken, Tim Cocx

[Jet-Magento Integration]

Modern Web Application Framework Python, SQL Alchemy, Jinja2 & Flask

Choosing a Content Management System (CMS)

COSC 3351 Software Design. Recap for the first quiz. Edgar Gabriel. Spring For the 1 st Quiz

Ektron to EPiServer Digital Experience Cloud: Information Architecture

Agile Software Development

DEPLOYMENT GUIDE Version 1.1. Deploying the BIG-IP LTM v10 with Citrix Presentation Server 4.5

Simple Tips to Improve Drupal Performance: No Coding Required. By Erik Webb, Senior Technical Consultant, Acquia

Bricks Architecture Technical Whitepaper

September 18, Modular development in Magento 2. Igor Miniailo Magento

mod_tcl TCL inside the Apache web server

CHAPTER 2 MODELLING FOR DISTRIBUTED NETWORK SYSTEMS: THE CLIENT- SERVER MODEL

UpTime 4 Health Monitoring Component

Dominic Betts Grigori Melnik Fernando Simonazzi Mani Subramanian

Django Assess Managed Nicely Documentation

Information Systems Analysis and Design CSC John Mylopoulos. Software Architectures Information Systems Analysis and Design CSC340

Agentry SAP Framework. SAP Mobile Platform 3.0

NASA Workflow Tool. User Guide. September 29, 2010

Virtualization Reduces the Cost of Supporting Open Industrial Control Systems

Chapter 1: Key Concepts of Programming and Software Engineering

Cloudwords Drupal Module. Quick Start Guide

Four Reasons Your Technical Team Will Love Acquia Cloud Site Factory

Visual Basic Programming. An Introduction

Siebel Business Process Framework: Workflow Guide. Siebel Innovation Pack 2013 Version 8.1/8.2 September 2013

Software Visualization and Model Generation

XXI. Object-Oriented Database Design

Variable Base Interface

THE ROAD TO CODE. ANDROID DEVELOPMENT IMMERSIVE May 31. WEB DEVELOPMENT IMMERSIVE May 31 GENERAL ASSEMBLY

Guiding Principles for Modeling and Designing Reusable Services

Systems Integration: Co C mp m onent- t bas a e s d s o s ftw ft a w r a e r e ngin i eeri r n i g

Programming in C# with Microsoft Visual Studio 2010

DataDirect XQuery Technical Overview

Patterns for Business Object Model Integration in Process-Driven and Service-Oriented Architectures

A 100k Users.. Now What?

Object Oriented Database Management System for Decision Support System.

Heterogeneous Tools for Heterogeneous Network Management with WBEM

Transcription:

Introducing

Allow me to introduce myself Claudio Beatrice @omissis 6+ years of experience on PHP Organizing Drupal events since 2009 PHP, Drupal & Symfony consulting Web Radio Telecommunications

What s Symfony2 A reusable set of standalone, decoupled, and cohesive PHP 5.3 components A full-stack web framework A Request/Response framework built around the HTTP specification An awesome community! A promoter of best practices, standardization and interoperability

Leave The STUPID Alone As time went by, habits and practices that once seemed acceptable have proven that they were making our code harder to understand and maintain. In other words, STUPID. But what makes code such a thing? Singleton Tight coupling Untestability Premature optimization Indescriptive naming Duplication

Singleton It s a design pattern that restricts the creation of an object to one instance(think of a DB connection). It does introduce undesirable limitations(what if we ll need TWO DB connections?), global state and hardcoded dependencies which are all making code more difficult to test and more coupled.

Singleton class DB { private static $instance; private function construct() { //... code goes here... public static function getinstance() { if (empty(self::$instance)) { self::$instance = new self; return self::$instance; //... more code goes here...

Tight Coupling It happens when classes are put in relation by using type hints, static calls or direct instantiation. Introduces hardcoded dependencies between classes, which complicates: code reuse unit testing integration modifications

Tight Coupling // An example of tight coupling class House { public function construct() { $this->door = new Door(); $this->window = new Window(); // And a possible solution class House { // Door and Window are interfaces public function construct(door $door, Window $window) { $this->door = $door; $this->window = $window;

Untestability If classes are complex, tightly coupled or trying to do too much, then there s a good chance that it s also quite hard if not impossible to test it in isolation. The lack of proper test coverage will make code harder to maintain and change, as it becomes very difficult to tell if any modification is actually breaking something.

Premature Optimization Most of the time major performance issues are caused by small portions of code(80/20 rule). It is easier to optimize correct code than to correct optimized code. Performance are not always a concern, therefore optimize when it s a proved problem, you ll save time and raise productivity.

Indescriptive Naming There are two hard things in computer science: cache invalidation, naming things and off-by-one errors. -- Phil Karlton, variated by the Interwebs Even if hard, naming is a fundamental part of the job and should be considered part of the documentation, therefore remember to: communicate intents favor clarity over brevity think that code is read far more often than written, so it s more convenient to ease reads over writes

Duplication How many times did they tell you to not repeat yourself?

BE SOLID! What alternatives to write STUPID code do we have? Another acronym to the rescue: SOLID! It encloses five class design principles: Single responsibility principle Open/closed principle Liskov substitution principle Interface segregation principle Dependency inversion principle

Single Responsibility There should never be more than one reason for a class to change. Every class should have a single responsibility and fully encapsulate it. If change becomes localized, complexity and cost of change are reduced, moreover there s less risk of ripple effects.

Single Responsibility interface Modem { function dial($phonenumber); function hangup(); function send($message); function receive(); The above interface shows two responsibilities: connection management and data communication, making them good candidates for two separate interfaces/implementations.

Open/Closed Software entities (classes, functions, etc) should be open for extension, but closed for modification. This principle states that the source code of software entities shouldn t ever be changed: those entities must be derived in order to add the wanted behaviors. Client Server Client Abstract Server Server

Liskov Substitution Objects in a program should be replaceable with instances of their subtypes without altering any of the desirable properties of that program, such as correctness and performed task. It intends to guarantee semantic interoperability of object types in a hierarchy.

Liskov Substitution class Rectangle { protected $width; protected $height; function setwidth($width) {... function getwidth() {... function setheight($height) {... function getheight() {... class Square extends Rectangle { function setwidth($width) { $this->width = $width; $this->height = $width; function setheight($height) { $this->width= $height; $this->height = $height; function draw(rectangle $r) { $r->setwidth(5); $r->setheight(4); // is it correct to assume that changing the width of a Rectangle leaves is height unchanged? assertequals( 20, $r->setwidth() * $r->setheight() );

Liskov Substitution The flaw in the Rectangle-Square design shows that even if conceptually a square is a rectangle, a Square object is not a Rectangle object, since a Square does not behave as a Rectangle. As a result, the public behavior the clients expect for the base class must be preserved in order to conform to the LSP.

Interface Segregation Many client-specific interfaces are better than one big one. This principle helps decreasing the coupling between objects by minimizing the intersecting surface. interface MultiFunctionPrinter { function print(...); function scan(...); function fax(...); interface Printer { function print(...); interface Scanner { function print(...); interface Fax { function print(...);

Dependency Inversion High-level entities should not depend on low-level entities and both should depend on abstractions. Abstractions should not depend upon details: details should depend upon abstractions. Component A Component A Service Component A Package Component B Component B Package

Dependency Inversion class Vehicle { protected $tyres; public function construct() { $this->tyres = array_fill(0, 4, new Tyre(50)); class Tyre { private $diameter; public function construct($diameter) { $this->setdiameter($diameter); public function setdiameter($diameter) { $this->diameter = $diameter; public function getdiameter() { return $this->diameter;

Dependency Inversion namespace Vehicle; namespace Vehicle; class Vehicle { protected $tyres; abstract class AbstractTyre { private $diameter; function addtyre(abstracttyre $tyre) { $this->tyres[] = $tyre; function construct($diameter) {... function setdiameter($diameter) {... function getdiameter() {... namespace Tyre; use Vehicle\AbstractTyre; class RaceTyre extends AbstractTyre { private $compound; function setcompound($compound) {... function getcompound() {...

How About Symfony Now? Being aware of the principles of software development mentioned earlier allow us to better understand some of the choices that have been made for the framework as well as some of the tools that have been made available, such as: Class Loader Service Container Event Dispatcher HTTP Foundation HTTP Kernel

Class Loader It loads your project s classes automatically if they re following a standard PHP convention aka PSR-0. Doctrine\Common\IsolatedClassLoader => /path/to/project/lib/vendor/doctrine/common/isolatedclassloader.php Symfony\Core\Request => /path/to/project/lib/vendor/symfony/core/request.php Twig_Node_Expression_Array => /path/to/project/lib/vendor/twig/node/expression/array.php It s a great way to get out of the require_once hell while gaining better interoperability and lazy loading at the same time.

Service Container aka Dependency Injection Container A Service is any PHP object that performs a global task: think of a Mailer class. A Service Container is a special object (think of it as an Array of Objects on Steroids) that centralizes and standardizes the way objects are constructed inside an application: instead of directly creating Services, the developer configures the Container to take care of the task.

Event Dispatcher A lightweight implementation of the Observer Pattern, it provides a powerful and easy way to extend objects. Observer +update Observable +attach +detach +notify ConcreteObserver1 +update ConcreteObserver2 +update ConcreteObservable +attach +detach +notify

Event Dispatcher use Symfony\Component\EventDispatcher\EventDispatcher; $dispatcher = new EventDispatcher(); $callable = function (Event $event) use ($log) { $log->addwarning( th3 n1nj4 d1sp4tch3r 1s 4ft3r y0u ); $dispatcher->addlistener( foo.bar, $callable); $dispatcher->dispatch( foo.bar, new Event());

HTTP Foundation It replaces the PHP s global variables and functions that represent either requests or responses with a full-featured object-oriented layer for the HTTP messages. use Symfony\Component\HttpFoundation\Request; // http://example.com/?foo=bar $request = Request::createFromGlobals(); $request->query->get( foo ); // returns bar // simulate a request $request = Request::create('/foo', 'GET', array('name' => 'Bar')); use Symfony\Component\HttpFoundation\Response; $response = new Response('Content', 200, array( 'content-type' => 'text/html' )); // check the response is HTTP compliant and send it $response->prepare($request); $response->send();

HTTP Kernel The Kernel is the core of Symfony2: it is built on top of the HttpFoundation and its main goal is to convert a Request object into a Response object using a Controller, which in turn can be any kind of PHP callable. interface HttpKernelInterface { const MASTER_REQUEST = 1; const SUB_REQUEST = 2; /** *... * @return Response A Response instance *... * @api */ function handle(request $request, $type = self::master_request, $catch = true);

HTTP Kernel Workflow exception Sub- Request sub-response content exception Request request resolve controller controller resolve arguments call controller response Response view terminate

Symfony is not enough Let s take a look at some of the most important third-party libraries

Doctrine2 The Doctrine Project is made of a selected set of PHP libraries primarily focused on providing persistence services and related functionality: Common Database Abstraction Layer Object Relational Mapper MongoDB Object Document Mapper CouchDB Object Document Mapper PHPCR Object Document Mapper Migrations

Doctrine2 namespace Drupal\Bundle\NodeBundle\Document; use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB; use Doctrine\Common\Persistence\PersistentObject; /** * @MongoDB\Document(collection="node") */ class Node extends PersistentObject { /** * @MongoDB\Id */ protected $id; /** * @MongoDB\String */ protected $title; // accessor and mutators

Twig A flexible, fast and secure template engine for PHP. It offers a great set of features, a concise syntax and very good performances (it compiles to PHP and has an optional C extension); moreover it s super easy to extend and it s thoughtfully documented. It gives the presentation layer a big boost in terms of expressiveness, making it more powerful and easier to use: prepare yourself for sweet hugs by front-end developers :)

Twig {# Node list page # {% extends layout.html.twig % {% macro node_render(node) % <div id= node-{{node.id > <h2>{{ node.title title </h2> <div>{{ node.creationdate date( d/m/y ) </div> <div>{{ node.body </div> <div>{{ node.tags join(, ) </div> </div> {% endmacro % {% block body % {% for node in nodes % node_render(node); {% else % {{ We did not find any node. trans {% endfor % {% endblock body %

Assetic An advanced asset management framework for PHP. $css = new AssetCollection(array( new FileAsset('/path/to/src/styles.less', array(new LessFilter())), new GlobAsset('/path/to/css/*'), ), array( new Yui\CssCompressorFilter('/path/to/yuicompressor.jar'), )); // this will echo CSS compiled by LESS and compressed by YUI echo $css->dump(); It ships with a strong set of filters for handling css, js, less, sass, compression, minifying and much more. Moreover, it s nicely integrated with Twig.

Giving The Devil His Due Some resources I used to make these slides: http://nikic.github.com/ http://fabien.potencier.org/ http://symfony.com/ http://www.slideshare.net/jwage/symfony2-from-the-trenches http://www.slideshare.net/weaverryan/handson-with-the-symfony2-framework http://www.slideshare.net/weaverryan/symony2-a-next-generation-php-framework http://martinfowler.com/articles/injection.html http://www.butunclebob.com/articles.unclebob.principlesofood

And Many Moar! Find many more Symfony2 Bundles and PHP Libraries at knpbundles.com and packagist.org! (and while you re at it, take a look at Composer! ;)

Thank You! Claudio Beatrice @omissis