refactorización de aplicaciones php/symfony2

Post on 18-Dec-2014

1.613 Views

Category:

Technology

0 Downloads

Preview:

Click to see full reader

DESCRIPTION

Slides de la charla "Refactorización de aplicaciones PHP/Symfony2" en deSymfony

TRANSCRIPT

Raúl Fraile

• Software developer en

• PHP 5.3 Zend Certified Engineer

• Symfony Certified Developer

• LadybugPHP

raulfraile

1. Refactoring 1012. Coding Standard3. IDE4. Separación código/datos5. Acoplamiento al entorno6. Don’t Repeat Yourself7. Fat controllers

Agenda

Proyecto de prueba

APIJokes (I)GET /api/list Obtiene la lista de chistes en JSONPOST /api/add Añade un nuevo chistePOST /api/edit Edita un chisteGET / Web con la lista de chistes en HTML

APIJokes (II)Casos especiales

Se envía un email al administrador cada vez que se añade o edita un chiste.

No se permiten chistes sobre Java.

Refactoring 101

Reescribir VS Refactorizar

Reescribir

http://www.flickr.com/photos/meliah/2601885140/

http://www.flickr.com/photos/90692443@N05/8239219385/

Refactorizar

Refactorizar debe ser un proceso contínuo

Siempre partiendo de un software que funciona...

...y con tests

Coding Standard

http://www.flickr.com/photos/zpeckler/2835570492/

¿Cambiar de CS?

Importante: Elegir un CS y ser consistente

Proyectos open source: compartir mismo 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

Problemas: DIC, foreach, repositorios...

<?php $mailer = $this->get('mailer');$mailer->send($message);

<?php /** @var $mailer \Swift_Mailer */$mailer = $this->get('mailer');

$mailer->send($message);

Type hints, aunque no solo por el 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);

Separación código/datos

Son distintoshttp://www.flickr.com/photos/yukariryu/121153772/

Un cambio en datos o configuración no debe requerir cambiar código

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();}

Acoplamiento al entorno

http://www.flickr.com/photos/darkhornet/4945282009/

FAIL

{% if app.environment == 'prod' %} <script type="text/javascript"> // Google Analytics code </script>{% endif %}

La aplicación no debe tomar decisiones

dependiendo del entorno

Mejor: configuraciones distintas por entorno

{% 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 Symfony\Component\Validator\Constraint; /** * @Annotation */class ContainsJava extends Constraint{ public $message = 'Java jokes are not allowed';}

 use Symfony\Component\Validator\Constraint;use Symfony\Component\Validator\ConstraintValidator; class ContainsJavaValidator extends ConstraintValidator{ public function validate($value, Constraint $constraint) { if (stripos($value, 'java') !== false) { $this->context->addViolation($constraint->message); } }}

Fat controllers

¡A dieta!

http://www.flickr.com/photos/golf_pictures/3017331832/

Configuración, eventos, anotaciones, servicios, métodos más simples, herencia, param

converters...

top related