nanos gigantium humeris insidentes (design patterns inside symfony 2)

Post on 18-May-2015

3.113 Views

Category:

Technology

2 Downloads

Preview:

Click to see full reader

DESCRIPTION

Talk presented by me and Giulio De Donato at SymfonyDayIt 2013

TRANSCRIPT

DESIGN PATTERNS INSIDE SYMFONY2

Nanos gigantium humeris insidentes

GIANTS

liurrrgio

GIORGIO CEFARO

@giorrrgio

GIULIO DE DONATO

@liuggio

DESIGN PATTERN?

A solution of a problem in a context

James O. Coplien (1994)

DESIGN PATTERN

“ For me a pattern is primarily a way to chunk up

advice about a topic “

DESIGN PATTERN

#1

INTENT:

A controller that handles all requests for a Web site

FRONT CONTROLLER

FRONT CONTROLLER

web/app.php

FRONT CONTROLLER ... and ?

web/app.php

INTENT:

Attach additional responsibilities to an object dynamically.

Decorators provide a flexible alternative to subclassing for

extending functionality.

DECORATOR

DECORATORSymfony\Component\HttpKernel\HttpCache\HttpCache

U DUNNO HttpKernelInterface?

Symfony\Component\HttpKernel\HttpKernelInterface

KERNEL AND SERVICE CONTAINER

Symfony\Component\HttpKernel\Kernel

INVERSION OF CONTROL

INTENT:Inversion of control is a style

of software construction where reusable code controls the execution

of problem-specific code

1988INVERSION OF CONTROL

“ Inversion of control is a common characteristic of frameworks,

so saying that these lightweight containers are special because they use inversion of

control is like saying my car is special because it has wheels.”

“ DON’T CALL US WE’LL CALL YOU ”

INVERSION OF CONTROL

HOLLYWOOD PRINCIPLE:

INVERSION OF CONTROL

"Dependency Injection is where components are given their dependencies through their

constructors, methods, or directly into fields."

PICO CONTAINER DEFINITION:

Dependency injection allows the removal of hard-coded dependencies

and makes it possible to change them, whether at run-time or compile-

time.

INJECTING A TRANSPORT INSIDE A MAILER

- FIGHT OF THE DAY -

SERVICE CONTAINERvs

DEPENDENCY INJECTION

INVERSION OF CONTROL

INTENT:

DECOUPLEDECOUPLEDECOUPLE

DECOUPLE

DECOUPLEDECOUPLE

DECOUPLE

DECOUPLE

DECOUPLEDECOUPLEDECOUPLE

??

DEPENDENCY INJECTION AND FRAMEWORKS

Grafico con spaghetti, infermiera che fa la puntura, lista della spesa per l'antipattern service locator, qualcosa di galattico per l'enhanced injection (tipo pulp fiction)

DI

DIC

http://www.loosecouplings.com/2011/01/dependency-injection-using-di-container.html

INTENT:

Define an interface for creating an object, but let subclasses decide which class

to instantiate. Factory Method lets a class defer instantiation to

subclasses.

FACTORY METHOD

FACTORY METHOD - DO IT WITH THE DIC

INTENT:

Provide an interface for creating families of related or dependent

objects withoutspecifying their concrete classes.

ABSTRACT FACTORY

ABSTRACT FACTORY - SecurityFactoryInterface

Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SecurityFactoryInterface

INTENT:

Separate the construction of a complex object from its

representation so that the same construction process can create

different representations.

BUILDER

FORM BUILDER

Symfony\Component\Form\FormBuilderInterface

FORM BUILDER

INTENT:

Provide a surrogate or placeholder for another

object to control access to it.

PROXY

DOCTRINE PROXY

app/cache/doctrine/odm/Proxies/ ...

INTENT:

Define an object that encapsulates how a set of objects interact. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their

interaction independently.

MEDIATOR

MEDIATOR

RouterListener

Kernel :: REQUEST EVENT DISPATCHER

SessionListener

FirewallLocaleListener

ProfilerListener

Fragm

entLi

stene

r

INTENT:

Defines a family of algorithms, encapsulate each one, and make them interchangeable.

Strategy lets the algorithm vary independently from clients that use it.

STRATEGY aka POLICY

FragmentRendererInterface

Symfony\Component\HttpKernel\Fragment\FragmentRendererInterface

Fragment Renderers

Symfony\Component\HttpKernel\Fragment\...

INTENT:

A layer of Mappers that moves data between objects and a database while keeping them independent of each other and the mapper

itself.

DATA MAPPER

INTENT:

Represent an operation to be performed on the elements of an object structure.

Visitor lets you define a new operation without changing the classes of the elements on which

it operates.

VISITOR

VALIDATION VISITOR

Symfony\Component\Validator\..

MVC

Controller

ViewModel

ANTI-PATTERNANTI-PATTERNANTI-PATTERN

AbstractionInversion, AccidentalComplexity, AccidentalInclusion, AddingEpicycles, AlcoholFueledDevelopment, AmbiguousViewpoint, AnalogyBreakdownAntiPattern, AnalysisParalysis, AnAthena, AppointedTeam, ArchitectsDontCode, ArchitectsPlayGolf, ArchitectureAsRequirements, ArchitectureByImplication, AsynchronousUnitTesting, AutogeneratedStovepipeAntiPattern, BandAid, BearTrap?, BigBallOfMud, BlameStorming, BlowhardJamboree, BoatAnchor, CargoCult, CarParkSyndrome, CascadingDialogBoxesAntiPattern, ContinuousObsolescence, ConfusionOfObjectives, ControlFreak, CopyAndPasteProgramming, CornCob, CoverYourAssets, CreepingFeaturitis, CrciCards, CryptoCracy, DeadEnd, DeathByPlanning, DecisionByArithmetic, DesignByCommittee, DesignForTheSakeOfDesign., DiscordantRewardMechanisms, DoerAndKnower, DryWaterhole, EgalitarianCompensation, EmailIsDangerous, EmperorsNewClothes, EmpireBuilding, ExceptionFunnel, FalseEconomy, FalseSurrogateEndpoint, FearOfSuccess, FireDrill, FloatingPointCurrency, FloatingPointFractions, FoolTrap, FunctionalDecomposition, FungibleTeams, FungibleProjectManager, GeographicallyDistributedDevelopment, GiveMeEstimatesNow, GlassWall, GodClass, GoldenHammer, GroundHogDayProject, HalfDoneIsEnough, HeirApparent, HeroCulture, HiddenRequirements, IdiotProofProcess., IfItIsWorkingDontChange, IfOk, InappropriateTechnicalObjective, InputKludge, ItsAnOperatorProblem, JobKeeper, JumbleAntipattern, JunkyardCoding, KillTwoBirdsWithOneStone, KitchenSinkDesign, LavaFlow, LeadingRequest, MagicContainer, ManagerControlsProcess, MushroomManagement, Nationalism, NetNegativeProducingProgrammer, NotInventedHere, NotTheAppropriateProtocol, NullFlag, OverGeneralizationOfBusinessLogic, OverUseOfPatterns, PathOfLeastResistance, ParsingHtmlWithRegex, PassingNullsToConstructors, PlugCompatibleInterchangeableEngineers, PoliticsOrientedArchitecture, PolterGeists, ReinventingTheWheel, ReinventTheWheel, RollYourOwnDatabase, RequirementsTossedOverTheWall, RubeGoldbergMachine, ScapeGoat, SeagullManagement, SecretSociety, SellingaProductYouCantRealize, ShootTheMessenger, SingleFunctionExitPoint, SmokeAndMirrors, SoftwareMerger, SpaghettiCode, SpecifyNothing, StandingOnTheShouldersOfMidgets, StovepipeAntiPattern, StringWithoutLength, SumoMarriage, SweepItUnderTheRugAntiPattern, SwissArmyKnife, ThatsNotReallyAnIssue, TheBlob, TheCustomersAreIdiots, TheGrandOldDukeOfYork, TheProcessIsTheDeliverable, TheyUnderstoodMe, ThrownOverTheWall, TowerOfVoodoo, TrainTheTrainer, UntestedButFinished, VendorLockIn, ViewgraphEngineering, VietnamWarAntiPattern, VoodooChickenCoding, WalkingThroughaMineField, WarmBodies, WeAreIdiots, WolfTicket, YetAnotherMeetingWillSolveIt, YetAnotherThreadWillSolveIt, YetAnotherProgrammer, ZeroMeansNull

ANTI PATTERNS

DESIGNFOR THE SAKE OF DESIGN

“I only ship the perfection"

ANTI PATTERNS

OVER ENGINEERING

OVERUSE OF PATTERNS

ANTI PATTERNS

THE BLOB

BIG BALL OF MUD

ANTI PATTERNS

GLOBALIZING

STANDING ON THE SHOULDER OF THE MIDGETS

ANTI PATTERNS

REINVENTING THE WHEEL

NIH SYNDROME

SPAGHETTI CODESPAGHETTI WITH MEATBALL

LASAGNA CODERAVIOLI CODE

RAVIOLI CODE

code spends more time being read and maintained than

being created

DECOUPLE

DECOUPLE

DECOUPLE.

GOOD QUESTIONS ARE BETTER THANGOOD ANSWERS

top related