SlideShare a Scribd company logo
1 of 51
Download to read offline
REFACTORING
PHP/SYMFONY2
APPS
Thank you to all our sponsors!
Raúl Fraile
• Software developer at
• PHP 5.3 Zend Certified Engineer
• Symfony Certified Developer
• LadybugPHP
raulfraile
1. Refactoring 101
2. Coding Standard
3. IDE
4. Code/Data separation
5. Environment coupling
6. Don’t Repeat Yourself
7. Fat controllers
Agenda
Test project
APIJokes (I)
GET /api/list
Get the jokes list in JSON
POST /api/add
Add a new joke
POST /api/edit
Edit an existing joke
GET /
Public website with the joke list in HTML
APIJokes (II)
Special cases
Every time a joke is added or edited,
an email is sent to the administrator.
We don’t allow jokes about Java.
raulfraile/apijokes
There are tags for each step!
Refactoring 101
Rewrite VS Refactor
Rewrite
http://www.flickr.com/photos/meliah/2601885140/
http://www.flickr.com/photos/90692443@N05/8239219385/
Refactor
Refactoring is a
continuous process
Always taking a software
that works...
...and which has tests
Coding Standard
http://www.flickr.com/photos/zpeckler/2835570492/
Change my CS?!
Important: Choose a CS
and be consistent
Open source projects:
share the same CS
PSR-1/2
http://cs.sensiolabs.org
php-cs-fixer fix ApiJokesBundle/ --level=all --dry-run --diff -v
1) Controller/WebsiteController.php (braces, return)
---------- begin diff ----------
--- Original
+++ New
@@ @@
-class WebsiteController extends Controller {
- public function indexAction() {
+class WebsiteController extends Controller
+{
+ public function indexAction()
+ {
$em = $this->getDoctrine()->getManager();
$jokes = $em->getRepository('...')->findAll();
+
return $this->render('...', array(
'jokes' => $jokes
));
}
}
---------- end diff ----------
IDE
Problems: DIC, foreach,
repositories...
<?php
 
$mailer = $this->get('mailer');
$mailer->send($message);
<?php
 
/** @var $mailer Swift_Mailer */
$mailer = $this->get('mailer');
$mailer->send($message);
Type hints, not only to
help the IDE...
<?php
 
$data = array_map(function ($item) {
return array(
'id' => $item->getId(),
'content' => $item->getContent()
);
}, $jokes);
<?php
 
$data = array_map(function (Joke $item)
{
return array(
'id' => $item->getId(),
'content' => $item->getContent()
);
}, $jokes);
Code/Data
separation
They are different
http://www.flickr.com/photos/yukariryu/121153772/
A change in the data or
configuration should’t
require changing the code
public function load(ObjectManager $manager)
{
$jokes = array(
'There’s no place like 127.0.0.1',
'If at first you don’t succeed; call it version 1.0',
'Beware of programmers that carry screwdrivers',
'What color do you want that database?'
);
 
foreach ($jokes as $item) {
$joke = new Joke();
$joke->setContent($item);
 
$manager->persist($joke);
}
 
$manager->flush();
}
# fixtures/joke.yml
jokes:
- 'I would love to change the world, but they won’t...'
- 'There’s no place like 127.0.0.1'
- 'If at first you don’t succeed; call it version 1.0'
- 'You know it’s love when you memorize her IP...'
- 'Beware of programmers that carry screwdrivers'
- 'Best file compression around: “rm *.*” = 100...'
- 'The truth is out there…anybody got the URL?'
- 'What color do you want that database?'
public function load(ObjectManager $manager)
{
$jokes = Yaml::parse(__DIR__ . '/fixtures/joke.yml');
 
foreach ($jokes['jokes'] as $item) {
$joke = new Joke();
$joke->setContent($item);
 
$manager->persist($joke);
}
 
$manager->flush();
}
Environment coupling
http://www.flickr.com/photos/darkhornet/4945282009/
FAIL
{% if app.environment == 'prod' %}
<script type="text/javascript">
// Google Analytics code
</script>
{% endif %}
The software shouldn’t
take any decision based
on the environment
Better approach:
different configuration
for each environment
{% if enable_analytics %}
<script type="text/javascript">
// Google Analytics code
</script>
{% endif %}
Don’t Repeat
Yourself
// do not allow jokes about java)
if (stripos($content, 'java') !== false) {
throw new BadRequestHttpException(
'Java jokes are not allowed'
);
}
use SymfonyComponentValidatorConstraint;
 
/**
* @Annotation
*/
class ContainsJava extends Constraint
{
public $message = 'Java jokes are not allowed';
}
 
use SymfonyComponentValidatorConstraint;
use SymfonyComponentValidatorConstraintValidator;
 
class ContainsJavaValidator extends ConstraintValidator
{
public function validate($value, Constraint $constraint)
{
if (stripos($value, 'java') !== false) {
$this->context->addViolation($constraint->message);
}
}
}
Fat controllers
Go on a diet!
http://www.flickr.com/photos/golf_pictures/3017331832/
Configuration, events,
annotations, services, simpler
methods, inheritance, param
converters...
https://joind.in/8835
Questions?

More Related Content

What's hot

Copycopter Presentation by Joe Ferris at BostonRB
Copycopter Presentation by Joe Ferris at BostonRBCopycopter Presentation by Joe Ferris at BostonRB
Copycopter Presentation by Joe Ferris at BostonRB
bostonrb
 
Perl web frameworks
Perl web frameworksPerl web frameworks
Perl web frameworks
diego_k
 

What's hot (19)

How not to develop with Plone
How not to develop with PloneHow not to develop with Plone
How not to develop with Plone
 
Zen: Building Maintainable Catalyst Applications
Zen: Building Maintainable Catalyst ApplicationsZen: Building Maintainable Catalyst Applications
Zen: Building Maintainable Catalyst Applications
 
Copycopter Presentation by Joe Ferris at BostonRB
Copycopter Presentation by Joe Ferris at BostonRBCopycopter Presentation by Joe Ferris at BostonRB
Copycopter Presentation by Joe Ferris at BostonRB
 
Troubleshooting Puppet
Troubleshooting PuppetTroubleshooting Puppet
Troubleshooting Puppet
 
Nigel hamilton-megameet-2013
Nigel hamilton-megameet-2013Nigel hamilton-megameet-2013
Nigel hamilton-megameet-2013
 
Modularizing Rails Apps with Cells
Modularizing Rails Apps with CellsModularizing Rails Apps with Cells
Modularizing Rails Apps with Cells
 
I motion
I motionI motion
I motion
 
Pecha Kucha
Pecha KuchaPecha Kucha
Pecha Kucha
 
Engines
EnginesEngines
Engines
 
Web Apps in Perl - HTTP 101
Web Apps in Perl - HTTP 101Web Apps in Perl - HTTP 101
Web Apps in Perl - HTTP 101
 
Magical WordPress Development with Vagrant
Magical WordPress Development with VagrantMagical WordPress Development with Vagrant
Magical WordPress Development with Vagrant
 
Simplifying Code: Monster to Elegant in 5 Steps
Simplifying Code: Monster to Elegant in 5 StepsSimplifying Code: Monster to Elegant in 5 Steps
Simplifying Code: Monster to Elegant in 5 Steps
 
Reasons To Love Ruby
Reasons To Love RubyReasons To Love Ruby
Reasons To Love Ruby
 
Perl web frameworks
Perl web frameworksPerl web frameworks
Perl web frameworks
 
Mojo as a_client
Mojo as a_clientMojo as a_client
Mojo as a_client
 
You're Doing It Wrong
You're Doing It WrongYou're Doing It Wrong
You're Doing It Wrong
 
Rails Antipatterns | Open Session with Chad Pytel
Rails Antipatterns | Open Session with Chad Pytel Rails Antipatterns | Open Session with Chad Pytel
Rails Antipatterns | Open Session with Chad Pytel
 
WordPress Advanced Custom Fields - 101
WordPress  Advanced Custom Fields - 101WordPress  Advanced Custom Fields - 101
WordPress Advanced Custom Fields - 101
 
第1回PHP拡張勉強会
第1回PHP拡張勉強会第1回PHP拡張勉強会
第1回PHP拡張勉強会
 

Similar to Refactoring PHP/Symfony2 apps

HackU PHP and Node.js
HackU PHP and Node.jsHackU PHP and Node.js
HackU PHP and Node.js
souridatta
 

Similar to Refactoring PHP/Symfony2 apps (20)

A General Purpose Docker Image for PHP
A General Purpose Docker Image for PHPA General Purpose Docker Image for PHP
A General Purpose Docker Image for PHP
 
What To Expect From PHP7
What To Expect From PHP7What To Expect From PHP7
What To Expect From PHP7
 
The why and how of moving to php 5.4
The why and how of moving to php 5.4The why and how of moving to php 5.4
The why and how of moving to php 5.4
 
The new features of PHP 7 - Enrico Zimuel - Codemotion Milan 2016
The new features of PHP 7 - Enrico Zimuel - Codemotion Milan 2016The new features of PHP 7 - Enrico Zimuel - Codemotion Milan 2016
The new features of PHP 7 - Enrico Zimuel - Codemotion Milan 2016
 
The new features of PHP 7
The new features of PHP 7The new features of PHP 7
The new features of PHP 7
 
DevOps in PHP environment
DevOps in PHP environment DevOps in PHP environment
DevOps in PHP environment
 
What we Learned Implementing Puppet at Backstop
What we Learned Implementing Puppet at BackstopWhat we Learned Implementing Puppet at Backstop
What we Learned Implementing Puppet at Backstop
 
Php 7 evolution
Php 7 evolutionPhp 7 evolution
Php 7 evolution
 
PHP SA 2014 - Releasing Your Open Source Project
PHP SA 2014 - Releasing Your Open Source ProjectPHP SA 2014 - Releasing Your Open Source Project
PHP SA 2014 - Releasing Your Open Source Project
 
OSDC 2014: Ole Michaelis & Sönke Rümpler: Make it SOLID - Software Architectu...
OSDC 2014: Ole Michaelis & Sönke Rümpler: Make it SOLID - Software Architectu...OSDC 2014: Ole Michaelis & Sönke Rümpler: Make it SOLID - Software Architectu...
OSDC 2014: Ole Michaelis & Sönke Rümpler: Make it SOLID - Software Architectu...
 
Lean Php Presentation
Lean Php PresentationLean Php Presentation
Lean Php Presentation
 
Giới thiệu PHP 7
Giới thiệu PHP 7Giới thiệu PHP 7
Giới thiệu PHP 7
 
The why and how of moving to PHP 5.5/5.6
The why and how of moving to PHP 5.5/5.6The why and how of moving to PHP 5.5/5.6
The why and how of moving to PHP 5.5/5.6
 
HackU PHP and Node.js
HackU PHP and Node.jsHackU PHP and Node.js
HackU PHP and Node.js
 
Como programar melhor jogando game boy
Como programar melhor jogando game boyComo programar melhor jogando game boy
Como programar melhor jogando game boy
 
Symfony 2.0
Symfony 2.0Symfony 2.0
Symfony 2.0
 
CodePolitan Webinar: The Rise of PHP
CodePolitan Webinar: The Rise of PHPCodePolitan Webinar: The Rise of PHP
CodePolitan Webinar: The Rise of PHP
 
Php Crash Course - Macq Electronique 2010
Php Crash Course - Macq Electronique 2010Php Crash Course - Macq Electronique 2010
Php Crash Course - Macq Electronique 2010
 
PHP in 2018 - Q4 - AFUP Limoges
PHP in 2018 - Q4 - AFUP LimogesPHP in 2018 - Q4 - AFUP Limoges
PHP in 2018 - Q4 - AFUP Limoges
 
The why and how of moving to php 7
The why and how of moving to php 7The why and how of moving to php 7
The why and how of moving to php 7
 

More from Raul Fraile

MidwestPHP Symfony2 Internals
MidwestPHP Symfony2 InternalsMidwestPHP Symfony2 Internals
MidwestPHP Symfony2 Internals
Raul Fraile
 
Presentacion Symfony2
Presentacion Symfony2Presentacion Symfony2
Presentacion Symfony2
Raul Fraile
 

More from Raul Fraile (16)

Aplicaciones CLI profesionales con Symfony
Aplicaciones CLI profesionales con SymfonyAplicaciones CLI profesionales con Symfony
Aplicaciones CLI profesionales con Symfony
 
Steganography: Hiding your secrets with PHP
Steganography: Hiding your secrets with PHPSteganography: Hiding your secrets with PHP
Steganography: Hiding your secrets with PHP
 
How GZIP compression works - JS Conf EU 2014
How GZIP compression works - JS Conf EU 2014How GZIP compression works - JS Conf EU 2014
How GZIP compression works - JS Conf EU 2014
 
How GZIP works... in 10 minutes
How GZIP works... in 10 minutesHow GZIP works... in 10 minutes
How GZIP works... in 10 minutes
 
Symfony en Drupal 8 - DrupalCamp Spain
Symfony en Drupal 8 - DrupalCamp Spain Symfony en Drupal 8 - DrupalCamp Spain
Symfony en Drupal 8 - DrupalCamp Spain
 
$kernel->infect(): Creating a cryptovirus for Symfony2 apps
$kernel->infect(): Creating a cryptovirus for Symfony2 apps$kernel->infect(): Creating a cryptovirus for Symfony2 apps
$kernel->infect(): Creating a cryptovirus for Symfony2 apps
 
Materiales del curso de Symfony2
Materiales del curso de Symfony2Materiales del curso de Symfony2
Materiales del curso de Symfony2
 
Sistemas de ficheros para dispositivos embebidos
Sistemas de ficheros para dispositivos embebidosSistemas de ficheros para dispositivos embebidos
Sistemas de ficheros para dispositivos embebidos
 
MidwestPHP Symfony2 Internals
MidwestPHP Symfony2 InternalsMidwestPHP Symfony2 Internals
MidwestPHP Symfony2 Internals
 
Symfony internals [english]
Symfony internals [english]Symfony internals [english]
Symfony internals [english]
 
DeSymfony 2012: Symfony internals
DeSymfony 2012: Symfony internalsDeSymfony 2012: Symfony internals
DeSymfony 2012: Symfony internals
 
Symfony2: Interacción con CSS, JS y HTML5
Symfony2: Interacción con CSS, JS y HTML5Symfony2: Interacción con CSS, JS y HTML5
Symfony2: Interacción con CSS, JS y HTML5
 
Symfony2: Optimización y rendimiento
Symfony2: Optimización y rendimientoSymfony2: Optimización y rendimiento
Symfony2: Optimización y rendimiento
 
Symfony2: Framework para PHP5
Symfony2: Framework para PHP5Symfony2: Framework para PHP5
Symfony2: Framework para PHP5
 
Symfony2: Framework para PHP5
Symfony2: Framework para PHP5Symfony2: Framework para PHP5
Symfony2: Framework para PHP5
 
Presentacion Symfony2
Presentacion Symfony2Presentacion Symfony2
Presentacion Symfony2
 

Recently uploaded

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Recently uploaded (20)

Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 

Refactoring PHP/Symfony2 apps