SlideShare una empresa de Scribd logo
1 de 310
Componentes
           El arma secreta de Symfony




#sf2Vigo                          Javier López | @loalf
Javier López

Nací en Córdoba, España.

Vivo en Londres, Reino Unido.

Trabajo en IPC Media (http://ipcmedia.com).

Escribo (a veces) en mi blog (http://www.loalf.com).

Twitteo como @loalf



  ... ¿quiéres saber más? http://www.linkedin.com/in/loalf
Los componentes
Son un conjunto de librerías autónomas,
desacopladas y complementarias que resuelven
problemas comunes del desarrollo web
21 Componentes

Browserkit     EventDispatcher         Security


ClassLoader        Routing          HttpFoundation


  Finder      DependencyInjection       Config


 Console         CssSelector           Locale


   Form          DomCrawler           HttpKernel


 Serializer        Process           Templating


   Yaml            Validator         Translation
21 Componentes

Browserkit     EventDispatcher         Security


ClassLoader        Routing          HttpFoundation


  Finder      DependencyInjection       Config


 Console         CssSelector           Locale


   Form          DomCrawler           HttpKernel


 Serializer        Process           Templating


   Yaml            Validator         Translation
Instalación
mkdir ComponentPlayground
cd ComponentPlayground
mkdir vendor
cd vendor
git clone https://github.com/symfony/symfony
descargar
autoload.php
autoload.php
<?php
autoload.php
<?php

require_once __DIR__.'/vendor/symfony/src/Symfony/Component/
ClassLoader/UniversalClassLoader.php';
autoload.php
<?php

require_once __DIR__.'/vendor/symfony/src/Symfony/Component/
ClassLoader/UniversalClassLoader.php';

use SymfonyComponentClassLoaderUniversalClassLoader;
autoload.php
<?php

require_once __DIR__.'/vendor/symfony/src/Symfony/Component/
ClassLoader/UniversalClassLoader.php';

use SymfonyComponentClassLoaderUniversalClassLoader;

$loader = new UniversalClassLoader();
autoload.php
<?php

require_once __DIR__.'/vendor/symfony/src/Symfony/Component/
ClassLoader/UniversalClassLoader.php';

use SymfonyComponentClassLoaderUniversalClassLoader;

$loader = new UniversalClassLoader();
$loader->registerNamespaces(array(
autoload.php
<?php

require_once __DIR__.'/vendor/symfony/src/Symfony/Component/
ClassLoader/UniversalClassLoader.php';

use SymfonyComponentClassLoaderUniversalClassLoader;

$loader = new UniversalClassLoader();
$loader->registerNamespaces(array(
  'Symfony'       => __DIR__.'/vendor/symfony/src',
autoload.php
<?php

require_once __DIR__.'/vendor/symfony/src/Symfony/Component/
ClassLoader/UniversalClassLoader.php';

use SymfonyComponentClassLoaderUniversalClassLoader;

$loader = new UniversalClassLoader();
$loader->registerNamespaces(array(
  'Symfony'       => __DIR__.'/vendor/symfony/src',
));
autoload.php
<?php

require_once __DIR__.'/vendor/symfony/src/Symfony/Component/
ClassLoader/UniversalClassLoader.php';

use SymfonyComponentClassLoaderUniversalClassLoader;

$loader = new UniversalClassLoader();
$loader->registerNamespaces(array(
  'Symfony'       => __DIR__.'/vendor/symfony/src',
));

$loader->register();
ejemplo.php
ejemplo.php

<?php
ejemplo.php

<?php

require_once 'autoload.php';
ejemplo.php

<?php

require_once 'autoload.php';

/*
ejemplo.php

<?php

require_once 'autoload.php';

/*
 * Código del ejemplo
ejemplo.php

<?php

require_once 'autoload.php';

/*
 * Código del ejemplo
 */
ejemplo.php

<?php

require_once 'autoload.php';

/*
 * Código del ejemplo
 */




> php ejemplo.php
Yaml
Parsea y genera archivos yml
parseando archivos YAML

#example.yml

descripcion: “Usuarios de symfony”
usuarios:
  javi:
    nombre: “Javi”
    apellidos: “López”
  raul:
    nombre: “Raúl”
    apellidos: “Fraile”
parseando archivos YAML

                                     use SymfonyComponentYamlYaml;
#example.yml

descripcion: “Usuarios de symfony”
usuarios:
  javi:
    nombre: “Javi”
    apellidos: “López”
  raul:
    nombre: “Raúl”
    apellidos: “Fraile”
parseando archivos YAML

                                     use SymfonyComponentYamlYaml;
#example.yml
                                     $data = Yaml::parse('example.yml');
descripcion: “Usuarios de symfony”
usuarios:
  javi:
    nombre: “Javi”
    apellidos: “López”
  raul:
    nombre: “Raúl”
    apellidos: “Fraile”
parseando archivos YAML

                                     use SymfonyComponentYamlYaml;
#example.yml
                                     $data = Yaml::parse('example.yml');
descripcion: “Usuarios de symfony”
usuarios:
                                     print $data['descripcion'];
  javi:
    nombre: “Javi”
    apellidos: “López”
  raul:
    nombre: “Raúl”
    apellidos: “Fraile”
parseando archivos YAML

                                     use SymfonyComponentYamlYaml;
#example.yml
                                     $data = Yaml::parse('example.yml');
descripcion: “Usuarios de symfony”
usuarios:
                                     print $data['descripcion'];
  javi:
    nombre: “Javi”
                                     foreach( $data['usuarios'] as $usuario)
    apellidos: “López”
  raul:
    nombre: “Raúl”
    apellidos: “Fraile”
parseando archivos YAML

                                     use SymfonyComponentYamlYaml;
#example.yml
                                     $data = Yaml::parse('example.yml');
descripcion: “Usuarios de symfony”
usuarios:
                                     print $data['descripcion'];
  javi:
    nombre: “Javi”
                                     foreach( $data['usuarios'] as $usuario)
    apellidos: “López”
                                     {
  raul:
    nombre: “Raúl”
    apellidos: “Fraile”
parseando archivos YAML

                                     use SymfonyComponentYamlYaml;
#example.yml
                                     $data = Yaml::parse('example.yml');
descripcion: “Usuarios de symfony”
usuarios:
                                     print $data['descripcion'];
  javi:
    nombre: “Javi”
                                     foreach( $data['usuarios'] as $usuario)
    apellidos: “López”
                                     {
  raul:
                                       print $usuario['nombre']
    nombre: “Raúl”
    apellidos: “Fraile”
parseando archivos YAML

                                     use SymfonyComponentYamlYaml;
#example.yml
                                     $data = Yaml::parse('example.yml');
descripcion: “Usuarios de symfony”
usuarios:
                                     print $data['descripcion'];
  javi:
    nombre: “Javi”
                                     foreach( $data['usuarios'] as $usuario)
    apellidos: “López”
                                     {
  raul:
                                       print $usuario['nombre']
    nombre: “Raúl”
                                             .' '.
    apellidos: “Fraile”
parseando archivos YAML

                                     use SymfonyComponentYamlYaml;
#example.yml
                                     $data = Yaml::parse('example.yml');
descripcion: “Usuarios de symfony”
usuarios:
                                     print $data['descripcion'];
  javi:
    nombre: “Javi”
                                     foreach( $data['usuarios'] as $usuario)
    apellidos: “López”
                                     {
  raul:
                                       print $usuario['nombre']
    nombre: “Raúl”
                                             .' '.
    apellidos: “Fraile”
                                             $usuario['apellidos'];
parseando archivos YAML

                                     use SymfonyComponentYamlYaml;
#example.yml
                                     $data = Yaml::parse('example.yml');
descripcion: “Usuarios de symfony”
usuarios:
                                     print $data['descripcion'];
  javi:
    nombre: “Javi”
                                     foreach( $data['usuarios'] as $usuario)
    apellidos: “López”
                                     {
  raul:
                                       print $usuario['nombre']
    nombre: “Raúl”
                                             .' '.
    apellidos: “Fraile”
                                             $usuario['apellidos'];
                                     }
parseando archivos YAML

                                     use SymfonyComponentYamlYaml;
#example.yml
                                     $data = Yaml::parse('example.yml');
descripcion: “Usuarios de symfony”
usuarios:
                                     print $data['descripcion'];
  -
    nombre: “Javi”
                                     foreach( $data['usuarios'] as $usuario)
    apellidos: “López”
                                     {
  -
                                       print $usuario['nombre']
    nombre: “Raúl”
                                             .' '.
    apellidos: “Fraile”
                                             $usuario['apellidos'];
                                     }
generando archivos YAML
generando archivos YAML

use SymfonyComponentYamlYaml;
generando archivos YAML

use SymfonyComponentYamlYaml;

$data['descripcion'] = "Usuarios de
symfony";
generando archivos YAML

use SymfonyComponentYamlYaml;

$data['descripcion'] = "Usuarios de
symfony";

$data['usuarios'][] = array(
generando archivos YAML

use SymfonyComponentYamlYaml;

$data['descripcion'] = "Usuarios de
symfony";

$data['usuarios'][] = array(
  'nombre' => 'Javi',
generando archivos YAML

use SymfonyComponentYamlYaml;

$data['descripcion'] = "Usuarios de
symfony";

$data['usuarios'][] = array(
  'nombre' => 'Javi',
  'apellidos' => 'Lopez'
generando archivos YAML

use SymfonyComponentYamlYaml;

$data['descripcion'] = "Usuarios de
symfony";

$data['usuarios'][] = array(
   'nombre' => 'Javi',
   'apellidos' => 'Lopez'
);
generando archivos YAML

use SymfonyComponentYamlYaml;

$data['descripcion'] = "Usuarios de
symfony";

$data['usuarios'][] = array(
   'nombre' => 'Javi',
   'apellidos' => 'Lopez'
);

$data['usuarios'][] = array(
generando archivos YAML

use SymfonyComponentYamlYaml;

$data['descripcion'] = "Usuarios de
symfony";

$data['usuarios'][] = array(
   'nombre' => 'Javi',
   'apellidos' => 'Lopez'
);

$data['usuarios'][] = array(
  'nombre' => 'Raul',
generando archivos YAML

use SymfonyComponentYamlYaml;

$data['descripcion'] = "Usuarios de
symfony";

$data['usuarios'][] = array(
   'nombre' => 'Javi',
   'apellidos' => 'Lopez'
);

$data['usuarios'][] = array(
  'nombre' => 'Raul',
  'apellidos' => 'Fraile'
generando archivos YAML

use SymfonyComponentYamlYaml;

$data['descripcion'] = "Usuarios de
symfony";

$data['usuarios'][] = array(
   'nombre' => 'Javi',
   'apellidos' => 'Lopez'
);

$data['usuarios'][] = array(
   'nombre' => 'Raul',
   'apellidos' => 'Fraile'
);
generando archivos YAML

use SymfonyComponentYamlYaml;

$data['descripcion'] = "Usuarios de
symfony";

$data['usuarios'][] = array(
   'nombre' => 'Javi',
   'apellidos' => 'Lopez'
);

$data['usuarios'][] = array(
   'nombre' => 'Raul',
   'apellidos' => 'Fraile'
);

print Yaml::dump($data);
generando archivos YAML

use SymfonyComponentYamlYaml;

$data['descripcion'] = "Usuarios de
symfony";
                                          descripcion: “Usuarios de symfony”
$data['usuarios'][] = array(              usuarios:
   'nombre' => 'Javi',                      0:
   'apellidos' => 'Lopez'                      nombre: “Javi”
);                                             apellidos: “López”
                                            1:
$data['usuarios'][] = array(                   nombre: “Raúl”
   'nombre' => 'Raul',                         apellidos: “Fraile”
   'apellidos' => 'Fraile'
);

print Yaml::dump($data);
YAML & PHP

#example.yml

generado: <?php echo date(‘d-m-Y’); ?>
descripcion: “Usuarios de symfony”
usuarios:
  javi:
    nombre: “Javi”
    apellidos: “López”
  raul:
    nombre: “Raúl”
    apellidos: “Fraile”
YAML & PHP

#example.yml

generado: <?php echo date(‘d-m-Y’); ?>   use SymfonyComponentYamlYaml;
descripcion: “Usuarios de symfony”
usuarios:                                Yaml::enablePhpParsing();
  javi:
    nombre: “Javi”                       $data = Yaml::parse('example.yml');
    apellidos: “López”
  raul:                                  print $data['generado'];
    nombre: “Raúl”
    apellidos: “Fraile”
Finder
Herramienta para encontrar archivos y directorios
buscando archivos por nombre
buscando archivos por nombre


use SymfonyComponentFinderFinder;
buscando archivos por nombre


use SymfonyComponentFinderFinder;


$files = Finder::create()
buscando archivos por nombre


use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->name("*.php")
buscando archivos por nombre


use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->name("*.php")
          ->name("*.{php,yml}")
buscando archivos por nombre


use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->name("*.php")
          ->name("*.{php,yml}")
          ->name("/.(php|yml)$/")
buscando archivos por nombre


use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->name("*.php")
          ->name("*.{php,yml}")
          ->name("/.(php|yml)$/")
          ->name("/^w{3,10}$/")
buscando archivos por nombre


use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->name("*.php")
          ->name("*.{php,yml}")
          ->name("/.(php|yml)$/")
          ->name("/^w{3,10}$/")
          ->name("foo.php")
buscando archivos por nombre


use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->name("*.php")
          ->name("*.{php,yml}")
          ->name("/.(php|yml)$/")
          ->name("/^w{3,10}$/")
          ->name("foo.php")
          ->in(__DIR__);
buscando archivos por nombre


  use SymfonyComponentFinderFinder;


  $files = Finder::create()
                    ->name("*.php")
                    ->name("*.{php,yml}")
                    ->name("/.(php|yml)$/")
                    ->name("/^w{3,10}$/")
                    ->name("foo.php")
                    ->in(__DIR__);




Referencia sobre Patrones Glob: http://cowburn.info/2010/04/30/glob-patterns/
buscando archivos por tamaño
buscando archivos por tamaño

use SymfonyComponentFinderFinder;
buscando archivos por tamaño

use SymfonyComponentFinderFinder;


$files = Finder::create()
buscando archivos por tamaño

use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->size("> 10k")
buscando archivos por tamaño

use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->size("> 10k")
          ->size("<= 4mi")
buscando archivos por tamaño

use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->size("> 10k")
          ->size("<= 4mi")
          ->size("2gi")
buscando archivos por tamaño

use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->size("> 10k")
          ->size("<= 4mi")
          ->size("2gi")
          ->in(__DIR__);
buscando archivos por tamaño

use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->size("> 10k")
          ->size("<= 4mi")
          ->size("2gi")
          ->in(__DIR__);


                                       k = 1000     ki = 1024
                                       m = 1000^2   mi = 1024^2
                                       g = 1000^3   gi = 1024^3
buscando archivos por fecha
buscando archivos por fecha


use SymfonyComponentFinderFinder;
buscando archivos por fecha


use SymfonyComponentFinderFinder;


$files = Finder::create()
buscando archivos por fecha


use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->date("since yesterday")
buscando archivos por fecha


use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->date("since yesterday")
          ->date("until 2 days ago")
buscando archivos por fecha


use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->date("since yesterday")
          ->date("until 2 days ago")
          ->date("> now - 2 hours")
buscando archivos por fecha


use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->date("since yesterday")
          ->date("until 2 days ago")
          ->date("> now - 2 hours")
          ->date(">= 2005-10-15 ")
buscando archivos por fecha


use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->date("since yesterday")
          ->date("until 2 days ago")
          ->date("> now - 2 hours")
          ->date(">= 2005-10-15 ")
          ->in(__DIR__);
buscando archivos por fecha


  use SymfonyComponentFinderFinder;


  $files = Finder::create()
                  ->date("since yesterday")
                  ->date("until 2 days ago")
                  ->date("> now - 2 hours")
                  ->date(">= 2005-10-15 ")
                  ->in(__DIR__);




Parámetro es cualquier argumento válido para strtotime()
fijando el nivel de profundidad
fijando el nivel de profundidad


use SymfonyComponentFinderFinder;
fijando el nivel de profundidad


use SymfonyComponentFinderFinder;


$files = Finder::create()
fijando el nivel de profundidad


use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->depth(0)
fijando el nivel de profundidad


use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->depth(0)
          ->depth(>1)
fijando el nivel de profundidad


use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->depth(0)
          ->depth(>1)
          ->depth(<3)
fijando el nivel de profundidad


use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->depth(0)
          ->depth(>1)
          ->depth(<3)
          ->in(__DIR__);
buscando sólo archivos
buscando sólo archivos



use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->files()
          ->in(__DIR__);
buscando sólo directorios
buscando sólo directorios



use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->directories()
          ->in(__DIR__);
obteniendo un resultado ordenado
obteniendo un resultado ordenado

use SymfonyComponentFinderFinder;
obteniendo un resultado ordenado

use SymfonyComponentFinderFinder;


$files = Finder::create()
obteniendo un resultado ordenado

use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->sortByName()
obteniendo un resultado ordenado

use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->sortByName()
          ->sortByType()
obteniendo un resultado ordenado

use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->sortByName()
          ->sortByType()
          ->sort(
obteniendo un resultado ordenado

use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->sortByName()
          ->sortByType()
          ->sort(
              function(SplFileInfo $file1, SplFileInfo $file2){
obteniendo un resultado ordenado

use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->sortByName()
          ->sortByType()
          ->sort(
              function(SplFileInfo $file1, SplFileInfo $file2){
                return $file1->getSize() > $file2->getSize();
obteniendo un resultado ordenado

use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->sortByName()
          ->sortByType()
          ->sort(
              function(SplFileInfo $file1, SplFileInfo $file2){
                return $file1->getSize() > $file2->getSize();
              }
obteniendo un resultado ordenado

use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->sortByName()
          ->sortByType()
          ->sort(
              function(SplFileInfo $file1, SplFileInfo $file2){
                return $file1->getSize() > $file2->getSize();
              }
            )
obteniendo un resultado ordenado

use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->sortByName()
          ->sortByType()
          ->sort(
              function(SplFileInfo $file1, SplFileInfo $file2){
                return $file1->getSize() > $file2->getSize();
              }
            )
          ->in(__DIR__);
archivos php en la carpeta raíz del proyecto
archivos php en la carpeta raíz del proyecto


use SymfonyComponentFinderFinder;
archivos php en la carpeta raíz del proyecto


use SymfonyComponentFinderFinder;


$files = Finder::create()
archivos php en la carpeta raíz del proyecto


use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->files()
archivos php en la carpeta raíz del proyecto


use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->files()
          ->depth(0)
archivos php en la carpeta raíz del proyecto


use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->files()
          ->depth(0)
          ->name("*.php")
archivos php en la carpeta raíz del proyecto


use SymfonyComponentFinderFinder;


$files = Finder::create()
          ->files()
          ->depth(0)
          ->name("*.php")
          ->in(__DIR__);
imágenes en un contener Amazon S3
imágenes en un contener Amazon S3


$s3 = new Zend_Service_Amazon_S3($key, $secret);
imágenes en un contener Amazon S3


$s3 = new Zend_Service_Amazon_S3($key, $secret);
$s3->registerStreamWrapper("s3");
imágenes en un contener Amazon S3


$s3 = new Zend_Service_Amazon_S3($key, $secret);
$s3->registerStreamWrapper("s3");
imágenes en un contener Amazon S3


$s3 = new Zend_Service_Amazon_S3($key, $secret);
$s3->registerStreamWrapper("s3");


$files = Finder::create()
imágenes en un contener Amazon S3


$s3 = new Zend_Service_Amazon_S3($key, $secret);
$s3->registerStreamWrapper("s3");


$files = Finder::create()
          ->name('*.{jpg,jpeg,png,gif}')
imágenes en un contener Amazon S3


$s3 = new Zend_Service_Amazon_S3($key, $secret);
$s3->registerStreamWrapper("s3");


$files = Finder::create()
          ->name('*.{jpg,jpeg,png,gif}')
          ->size('< 100K')
imágenes en un contener Amazon S3


$s3 = new Zend_Service_Amazon_S3($key, $secret);
$s3->registerStreamWrapper("s3");


$files = Finder::create()
          ->name('*.{jpg,jpeg,png,gif}')
          ->size('< 100K')
          ->date('since 1 hour ago')
imágenes en un contener Amazon S3


$s3 = new Zend_Service_Amazon_S3($key, $secret);
$s3->registerStreamWrapper("s3");


$files = Finder::create()
          ->name('*.{jpg,jpeg,png,gif}')
          ->size('< 100K')
          ->date('since 1 hour ago')
          ->in('s3://bucket-name');
Process
Facilita la ejecución de comandos del sistema
¿está Twitter online?
¿está Twitter online?

use SymfonyComponentProcessProcess;
¿está Twitter online?

use SymfonyComponentProcessProcess;


$process = new Process('ping -c 1 twitter.com');
¿está Twitter online?

use SymfonyComponentProcessProcess;


$process = new Process('ping -c 1 twitter.com');
$process->run();
¿está Twitter online?

use SymfonyComponentProcessProcess;


$process = new Process('ping -c 1 twitter.com');
$process->run();


if($process->isSuccessful()){
¿está Twitter online?

use SymfonyComponentProcessProcess;


$process = new Process('ping -c 1 twitter.com');
$process->run();


if($process->isSuccessful()){
  print "Twitter esta online";
¿está Twitter online?

use SymfonyComponentProcessProcess;


$process = new Process('ping -c 1 twitter.com');
$process->run();


if($process->isSuccessful()){
  print "Twitter esta online";
}else{
¿está Twitter online?

use SymfonyComponentProcessProcess;


$process = new Process('ping -c 1 twitter.com');
$process->run();


if($process->isSuccessful()){
  print "Twitter esta online";
}else{
  print "Twitter esta offline";
¿está Twitter online?

use SymfonyComponentProcessProcess;


$process = new Process('ping -c 1 twitter.com');
$process->run();


if($process->isSuccessful()){
  print "Twitter esta online";
}else{
    print "Twitter esta offline";
}
ping -c 4 twitter.com
calculando tiempos medios de respuesta
calculando tiempos medios de respuesta
$process = new Process('ping -c 4 twitter.com');
calculando tiempos medios de respuesta
$process = new Process('ping -c 4 twitter.com');
$process->run();
calculando tiempos medios de respuesta
$process = new Process('ping -c 4 twitter.com');
$process->run();


if($process->isSuccessful())
calculando tiempos medios de respuesta
$process = new Process('ping -c 4 twitter.com');
$process->run();


if($process->isSuccessful())
{
calculando tiempos medios de respuesta
$process = new Process('ping -c 4 twitter.com');
$process->run();


if($process->isSuccessful())
{
    $output = $process->getOutput();
calculando tiempos medios de respuesta
$process = new Process('ping -c 4 twitter.com');
$process->run();


if($process->isSuccessful())
{
    $output = $process->getOutput();
calculando tiempos medios de respuesta
$process = new Process('ping -c 4 twitter.com');
$process->run();


if($process->isSuccessful())
{
    $output = $process->getOutput();


    $pattern = '/time=(d+.d+) ms/';
calculando tiempos medios de respuesta
$process = new Process('ping -c 4 twitter.com');
$process->run();


if($process->isSuccessful())
{
    $output = $process->getOutput();


    $pattern = '/time=(d+.d+) ms/';
    preg_match_all($pattern, $output, $matches);
calculando tiempos medios de respuesta
$process = new Process('ping -c 4 twitter.com');
$process->run();


if($process->isSuccessful())
{
    $output = $process->getOutput();


    $pattern = '/time=(d+.d+) ms/';
    preg_match_all($pattern, $output, $matches);
    $average = array_sum($matches[1])/count($matches[1]);
calculando tiempos medios de respuesta
$process = new Process('ping -c 4 twitter.com');
$process->run();


if($process->isSuccessful())
{
    $output = $process->getOutput();


    $pattern = '/time=(d+.d+) ms/';
    preg_match_all($pattern, $output, $matches);
    $average = array_sum($matches[1])/count($matches[1]);
calculando tiempos medios de respuesta
$process = new Process('ping -c 4 twitter.com');
$process->run();


if($process->isSuccessful())
{
    $output = $process->getOutput();


    $pattern = '/time=(d+.d+) ms/';
    preg_match_all($pattern, $output, $matches);
    $average = array_sum($matches[1])/count($matches[1]);


    printf("Avergage time=%.3f ms", $average);
calculando tiempos medios de respuesta
$process = new Process('ping -c 4 twitter.com');
$process->run();


if($process->isSuccessful())
{
    $output = $process->getOutput();


    $pattern = '/time=(d+.d+) ms/';
    preg_match_all($pattern, $output, $matches);
    $average = array_sum($matches[1])/count($matches[1]);


    printf("Avergage time=%.3f ms", $average);
}else{
calculando tiempos medios de respuesta
$process = new Process('ping -c 4 twitter.com');
$process->run();


if($process->isSuccessful())
{
    $output = $process->getOutput();


    $pattern = '/time=(d+.d+) ms/';
    preg_match_all($pattern, $output, $matches);
    $average = array_sum($matches[1])/count($matches[1]);


    printf("Avergage time=%.3f ms", $average);
}else{
    print "Twitter está offline";
calculando tiempos medios de respuesta
$process = new Process('ping -c 4 twitter.com');
$process->run();


if($process->isSuccessful())
{
    $output = $process->getOutput();


    $pattern = '/time=(d+.d+) ms/';
    preg_match_all($pattern, $output, $matches);
    $average = array_sum($matches[1])/count($matches[1]);


    printf("Avergage time=%.3f ms", $average);
}else{
    print "Twitter está offline";
}
mostrando sólo los tiempos
mostrando sólo los tiempos

use SymfonyComponentProcessProcess;
mostrando sólo los tiempos

use SymfonyComponentProcessProcess;


$process = new Process('ping -c 4 twitter.com');
mostrando sólo los tiempos

use SymfonyComponentProcessProcess;


$process = new Process('ping -c 4 twitter.com');
$process->run(function($type, $buffer) {
mostrando sólo los tiempos

use SymfonyComponentProcessProcess;


$process = new Process('ping -c 4 twitter.com');
$process->run(function($type, $buffer) {
  if('out' === $type){
mostrando sólo los tiempos

use SymfonyComponentProcessProcess;


$process = new Process('ping -c 4 twitter.com');
$process->run(function($type, $buffer) {
  if('out' === $type){
    $pattern = '/time=(d+.d+) ms/';
mostrando sólo los tiempos

use SymfonyComponentProcessProcess;


$process = new Process('ping -c 4 twitter.com');
$process->run(function($type, $buffer) {
  if('out' === $type){
    $pattern = '/time=(d+.d+) ms/';
    if(preg_match_all($pattern, $buffer, $matches)){;
mostrando sólo los tiempos

use SymfonyComponentProcessProcess;


$process = new Process('ping -c 4 twitter.com');
$process->run(function($type, $buffer) {
  if('out' === $type){
    $pattern = '/time=(d+.d+) ms/';
    if(preg_match_all($pattern, $buffer, $matches)){;
      print $matches[0][0]."n";
mostrando sólo los tiempos

use SymfonyComponentProcessProcess;


$process = new Process('ping -c 4 twitter.com');
$process->run(function($type, $buffer) {
  if('out' === $type){
    $pattern = '/time=(d+.d+) ms/';
    if(preg_match_all($pattern, $buffer, $matches)){;
        print $matches[0][0]."n";
    }
mostrando sólo los tiempos

use SymfonyComponentProcessProcess;


$process = new Process('ping -c 4 twitter.com');
$process->run(function($type, $buffer) {
  if('out' === $type){
    $pattern = '/time=(d+.d+) ms/';
    if(preg_match_all($pattern, $buffer, $matches)){;
        print $matches[0][0]."n";
    }
  }elseif( 'err' === $type ){
mostrando sólo los tiempos

use SymfonyComponentProcessProcess;


$process = new Process('ping -c 4 twitter.com');
$process->run(function($type, $buffer) {
  if('out' === $type){
    $pattern = '/time=(d+.d+) ms/';
    if(preg_match_all($pattern, $buffer, $matches)){;
        print $matches[0][0]."n";
    }
  }elseif( 'err' === $type ){
    print "Twitter esta offline";
mostrando sólo los tiempos

use SymfonyComponentProcessProcess;


$process = new Process('ping -c 4 twitter.com');
$process->run(function($type, $buffer) {
  if('out' === $type){
      $pattern = '/time=(d+.d+) ms/';
      if(preg_match_all($pattern, $buffer, $matches)){;
          print $matches[0][0]."n";
      }
  }elseif( 'err' === $type ){
      print "Twitter esta offline";
  }
mostrando sólo los tiempos

use SymfonyComponentProcessProcess;


$process = new Process('ping -c 4 twitter.com');
$process->run(function($type, $buffer) {
  if('out' === $type){
      $pattern = '/time=(d+.d+) ms/';
      if(preg_match_all($pattern, $buffer, $matches)){;
          print $matches[0][0]."n";
      }
  }elseif( 'err' === $type ){
      print "Twitter esta offline";
  }
});
DomCrawler
Facilita la extracción de información de objetos DOM
Búsqueda en Twitter
Búsqueda en Twitter


use SymfonyComponentDomCrawlerCrawler;
Búsqueda en Twitter


use SymfonyComponentDomCrawlerCrawler;


$uri    = 'http://search.twitter.com/search.atom?q=sf2vigo';
Búsqueda en Twitter


use SymfonyComponentDomCrawlerCrawler;


$uri     = 'http://search.twitter.com/search.atom?q=sf2vigo';
$crawler = new Crawler();
Búsqueda en Twitter


use SymfonyComponentDomCrawlerCrawler;


$uri     = 'http://search.twitter.com/search.atom?q=sf2vigo';
$crawler = new Crawler();
$content = file_get_contents($uri);
Búsqueda en Twitter


use SymfonyComponentDomCrawlerCrawler;


$uri     = 'http://search.twitter.com/search.atom?q=sf2vigo';
$crawler = new Crawler();
$content = file_get_contents($uri);
$crawler->addXmlContent($content);
Búsqueda en Twitter


use SymfonyComponentDomCrawlerCrawler;


$uri     = 'http://search.twitter.com/search.atom?q=sf2vigo';
$crawler = new Crawler();
$content = file_get_contents($uri);
$crawler->addXmlContent($content);


foreach($crawler->filterXpath('//content') as $node)
Búsqueda en Twitter


use SymfonyComponentDomCrawlerCrawler;


$uri     = 'http://search.twitter.com/search.atom?q=sf2vigo';
$crawler = new Crawler();
$content = file_get_contents($uri);
$crawler->addXmlContent($content);


foreach($crawler->filterXpath('//content') as $node)
{
Búsqueda en Twitter


use SymfonyComponentDomCrawlerCrawler;


$uri       = 'http://search.twitter.com/search.atom?q=sf2vigo';
$crawler = new Crawler();
$content = file_get_contents($uri);
$crawler->addXmlContent($content);


foreach($crawler->filterXpath('//content') as $node)
{
    print $node->nodeValue;
Búsqueda en Twitter


use SymfonyComponentDomCrawlerCrawler;


$uri       = 'http://search.twitter.com/search.atom?q=sf2vigo';
$crawler = new Crawler();
$content = file_get_contents($uri);
$crawler->addXmlContent($content);


foreach($crawler->filterXpath('//content') as $node)
{
    print $node->nodeValue;
}
Enlaces del blog de symfony.com
Enlaces del blog de symfony.com

use SymfonyComponentDomCrawlerCrawler;
Enlaces del blog de symfony.com

use SymfonyComponentDomCrawlerCrawler;


$uri    = 'http://symfony.com/blog';
Enlaces del blog de symfony.com

use SymfonyComponentDomCrawlerCrawler;


$uri     = 'http://symfony.com/blog';
$content = file_get_contents($uri);
Enlaces del blog de symfony.com

use SymfonyComponentDomCrawlerCrawler;


$uri     = 'http://symfony.com/blog';
$content = file_get_contents($uri);


$crawler = new Crawler($content, $uri);
Enlaces del blog de symfony.com

use SymfonyComponentDomCrawlerCrawler;


$uri     = 'http://symfony.com/blog';
$content = file_get_contents($uri);


$crawler = new Crawler($content, $uri);


$nodes = $crawler->filterXPath('//div[@class="box_article"]//a');
Enlaces del blog de symfony.com

use SymfonyComponentDomCrawlerCrawler;


$uri     = 'http://symfony.com/blog';
$content = file_get_contents($uri);


$crawler = new Crawler($content, $uri);


$nodes = $crawler->filterXPath('//div[@class="box_article"]//a');
foreach($nodes->links() as $link)
Enlaces del blog de symfony.com

use SymfonyComponentDomCrawlerCrawler;


$uri     = 'http://symfony.com/blog';
$content = file_get_contents($uri);


$crawler = new Crawler($content, $uri);


$nodes = $crawler->filterXPath('//div[@class="box_article"]//a');
foreach($nodes->links() as $link)
{
Enlaces del blog de symfony.com

use SymfonyComponentDomCrawlerCrawler;


$uri       = 'http://symfony.com/blog';
$content = file_get_contents($uri);


$crawler = new Crawler($content, $uri);


$nodes = $crawler->filterXPath('//div[@class="box_article"]//a');
foreach($nodes->links() as $link)
{
    print $link->getUri();
Enlaces del blog de symfony.com

use SymfonyComponentDomCrawlerCrawler;


$uri       = 'http://symfony.com/blog';
$content = file_get_contents($uri);


$crawler = new Crawler($content, $uri);


$nodes = $crawler->filterXPath('//div[@class="box_article"]//a');
foreach($nodes->links() as $link)
{
    print $link->getUri();
}
CssSelector
Selectores CSS => Expresiones XPath
Convirtiendo CSS a XPath
Convirtiendo CSS a XPath



use SymfonyComponentCssSelectorCssSelector;
Convirtiendo CSS a XPath



use SymfonyComponentCssSelectorCssSelector;

print CssSelector::toXPath('div.box_article a');
Convirtiendo CSS a XPath



use SymfonyComponentCssSelectorCssSelector;

print CssSelector::toXPath('div.box_article a');

/*
Convirtiendo CSS a XPath



use SymfonyComponentCssSelectorCssSelector;

print CssSelector::toXPath('div.box_article a');

/*
 * descendant-or-self::div[
Convirtiendo CSS a XPath



use SymfonyComponentCssSelectorCssSelector;

print CssSelector::toXPath('div.box_article a');

/*
 * descendant-or-self::div[
 *   contains(
Convirtiendo CSS a XPath



use SymfonyComponentCssSelectorCssSelector;

print CssSelector::toXPath('div.box_article a');

/*
 * descendant-or-self::div[
 *   contains(
 *    concat(' ', normalize-   space(@class), ' '),
Convirtiendo CSS a XPath



use SymfonyComponentCssSelectorCssSelector;

print CssSelector::toXPath('div.box_article a');

/*
 * descendant-or-self::div[
 *   contains(
 *    concat(' ', normalize-   space(@class), ' '),
 *    ' box_article '
Convirtiendo CSS a XPath



use SymfonyComponentCssSelectorCssSelector;

print CssSelector::toXPath('div.box_article a');

/*
 * descendant-or-self::div[
 *   contains(
 *    concat(' ', normalize-   space(@class), ' '),
 *    ' box_article '
 *    )
Convirtiendo CSS a XPath



use SymfonyComponentCssSelectorCssSelector;

print CssSelector::toXPath('div.box_article a');

/*
 * descendant-or-self::div[
 *   contains(
 *    concat(' ', normalize-   space(@class), ' '),
 *    ' box_article '
 *    )
 * ]/descendant::a
Convirtiendo CSS a XPath



use SymfonyComponentCssSelectorCssSelector;

print CssSelector::toXPath('div.box_article a');

/*
 * descendant-or-self::div[
 *    contains(
 *     concat(' ', normalize-   space(@class), ' '),
 *     ' box_article '
 *    )
 * ]/descendant::a
 */
Enlaces del blog de symfony.com
Enlaces del blog de symfony.com


use SymfonyComponentDomCrawlerCrawler;
Enlaces del blog de symfony.com


use SymfonyComponentDomCrawlerCrawler;

$uri    = 'http://symfony.com/blog';
Enlaces del blog de symfony.com


use SymfonyComponentDomCrawlerCrawler;

$uri     = 'http://symfony.com/blog';
$content = file_get_contents($uri);
Enlaces del blog de symfony.com


use SymfonyComponentDomCrawlerCrawler;

$uri     = 'http://symfony.com/blog';
$content = file_get_contents($uri);

$crawler = new Crawler($content, $uri);
Enlaces del blog de symfony.com


use SymfonyComponentDomCrawlerCrawler;

$uri     = 'http://symfony.com/blog';
$content = file_get_contents($uri);

$crawler = new Crawler($content, $uri);

$nodes = $crawler->filter('div.box_article a');
Validator
Lleva a cabo tareas de validación
Validando que un valor sea no nulo
Validando que un valor sea no nulo



use SymfonyComponentValidatorConstraintsNotNull;
Validando que un valor sea no nulo



use SymfonyComponentValidatorConstraintsNotNull;
use SymfonyComponentValidatorConstraintsNotNullValidator;
Validando que un valor sea no nulo



use SymfonyComponentValidatorConstraintsNotNull;
use SymfonyComponentValidatorConstraintsNotNullValidator;


$validator = new NotNullValidator();
Validando que un valor sea no nulo



use SymfonyComponentValidatorConstraintsNotNull;
use SymfonyComponentValidatorConstraintsNotNullValidator;


$validator = new NotNullValidator();
if(!$validator->isValid(null, new NotNull()))
Validando que un valor sea no nulo



use SymfonyComponentValidatorConstraintsNotNull;
use SymfonyComponentValidatorConstraintsNotNullValidator;


$validator = new NotNullValidator();
if(!$validator->isValid(null, new NotNull()))
{
Validando que un valor sea no nulo



use SymfonyComponentValidatorConstraintsNotNull;
use SymfonyComponentValidatorConstraintsNotNullValidator;


$validator = new NotNullValidator();
if(!$validator->isValid(null, new NotNull()))
{
    print $validator->getMessageTemplate();
Validando que un valor sea no nulo



use SymfonyComponentValidatorConstraintsNotNull;
use SymfonyComponentValidatorConstraintsNotNullValidator;


$validator = new NotNullValidator();
if(!$validator->isValid(null, new NotNull()))
{
    print $validator->getMessageTemplate();
    // "The value should not be null"
Validando que un valor sea no nulo



use SymfonyComponentValidatorConstraintsNotNull;
use SymfonyComponentValidatorConstraintsNotNullValidator;


$validator = new NotNullValidator();
if(!$validator->isValid(null, new NotNull()))
{
    print $validator->getMessageTemplate();
    // "The value should not be null"
}
24 Validadores
 Blank          Max           Date


NotBlank         Min          Time


  Null           Url        DateTime


NotNull         Email        Locale


  True           IP         Language


 False          File         Country


Choice          Image       Collection


 Type           Size        Callback
Usando la clase Validator
Usando la clase Validator
use SymfonyComponentValidatorValidator;
Usando la clase Validator
use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
Usando la clase Validator
use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
use SymfonyComponentValidatorMappingBlackholeMetadataFactory;
Usando la clase Validator
use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
use SymfonyComponentValidatorMappingBlackholeMetadataFactory;
use SymfonyComponentValidatorConstraints as Asserts;
Usando la clase Validator
use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
use SymfonyComponentValidatorMappingBlackholeMetadataFactory;
use SymfonyComponentValidatorConstraints as Asserts;


$validator = new Validator(
Usando la clase Validator
use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
use SymfonyComponentValidatorMappingBlackholeMetadataFactory;
use SymfonyComponentValidatorConstraints as Asserts;


$validator = new Validator(
                   new BlackholeMetadataFactory,
Usando la clase Validator
use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
use SymfonyComponentValidatorMappingBlackholeMetadataFactory;
use SymfonyComponentValidatorConstraints as Asserts;


$validator = new Validator(
                   new BlackholeMetadataFactory,
                   new ConstraintValidatorFactory
Usando la clase Validator
use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
use SymfonyComponentValidatorMappingBlackholeMetadataFactory;
use SymfonyComponentValidatorConstraints as Asserts;


$validator = new Validator(
                   new BlackholeMetadataFactory,
                   new ConstraintValidatorFactory
);
Usando la clase Validator
use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
use SymfonyComponentValidatorMappingBlackholeMetadataFactory;
use SymfonyComponentValidatorConstraints as Asserts;


$validator = new Validator(
                   new BlackholeMetadataFactory,
                   new ConstraintValidatorFactory
);


$errors = $validator->validateValue('', new AssertsNotBlank());
Usando la clase Validator
use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
use SymfonyComponentValidatorMappingBlackholeMetadataFactory;
use SymfonyComponentValidatorConstraints as Asserts;


$validator = new Validator(
                   new BlackholeMetadataFactory,
                   new ConstraintValidatorFactory
);


$errors = $validator->validateValue('', new AssertsNotBlank());
if($errors->count())
Usando la clase Validator
use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
use SymfonyComponentValidatorMappingBlackholeMetadataFactory;
use SymfonyComponentValidatorConstraints as Asserts;


$validator = new Validator(
                   new BlackholeMetadataFactory,
                   new ConstraintValidatorFactory
);


$errors = $validator->validateValue('', new AssertsNotBlank());
if($errors->count())
{
Usando la clase Validator
use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
use SymfonyComponentValidatorMappingBlackholeMetadataFactory;
use SymfonyComponentValidatorConstraints as Asserts;


$validator = new Validator(
                   new BlackholeMetadataFactory,
                      new ConstraintValidatorFactory
);


$errors = $validator->validateValue('', new AssertsNotBlank());
if($errors->count())
{
     print $errors;
Usando la clase Validator
use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
use SymfonyComponentValidatorMappingBlackholeMetadataFactory;
use SymfonyComponentValidatorConstraints as Asserts;


$validator = new Validator(
                   new BlackholeMetadataFactory,
                      new ConstraintValidatorFactory
);


$errors = $validator->validateValue('', new AssertsNotBlank());
if($errors->count())
{
     print $errors;
}
Usando la clase Validator
use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
use SymfonyComponentValidatorMappingBlackholeMetadataFactory;
use SymfonyComponentValidatorConstraints as Asserts;


$validator = new Validator(
                   new BlackholeMetadataFactory,
                       new ConstraintValidatorFactory
);


$errors = $validator->validateValue('', new AssertsNotBlank());
if($errors->count())
{
     print $errors;
}
            ConstraintViolationList
Validando un objeto (PHP)


class Person
{
    public $name;
    public $age;
}
Validando un objeto (PHP)


class Person
{
    public $name;
    public $age;
}




$name no puede ser una cadena vacía
$age deberán ser un número comprendido entre 18 y 99 años
Validando un objeto (PHP)
Validando un objeto (PHP)

use SymfonyComponentValidatorValidator;
Validando un objeto (PHP)

use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
Validando un objeto (PHP)

use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
use SymfonyComponentValidatorMappingClassMetadataFactory;
Validando un objeto (PHP)

use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
use SymfonyComponentValidatorMappingClassMetadataFactory;
use SymfonyComponentValidatorMappingLoaderStaticMethodLoader;
Validando un objeto (PHP)

use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
use SymfonyComponentValidatorMappingClassMetadataFactory;
use SymfonyComponentValidatorMappingLoaderStaticMethodLoader;


$validator = new Validator(
Validando un objeto (PHP)

use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
use SymfonyComponentValidatorMappingClassMetadataFactory;
use SymfonyComponentValidatorMappingLoaderStaticMethodLoader;


$validator = new Validator(
  new ClassMetadataFactory(new StaticMethodLoader() ),
Validando un objeto (PHP)

use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
use SymfonyComponentValidatorMappingClassMetadataFactory;
use SymfonyComponentValidatorMappingLoaderStaticMethodLoader;


$validator = new Validator(
  new ClassMetadataFactory(new StaticMethodLoader() ),
  new ConstraintValidatorFactory()
Validando un objeto (PHP)

use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
use SymfonyComponentValidatorMappingClassMetadataFactory;
use SymfonyComponentValidatorMappingLoaderStaticMethodLoader;


$validator = new Validator(
  new ClassMetadataFactory(new StaticMethodLoader() ),
     new ConstraintValidatorFactory()
);
Validando un objeto (PHP)

use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
use SymfonyComponentValidatorMappingClassMetadataFactory;
use SymfonyComponentValidatorMappingLoaderStaticMethodLoader;


$validator = new Validator(
  new ClassMetadataFactory(new StaticMethodLoader() ),
     new ConstraintValidatorFactory()
);


$person = new Person();
Validando un objeto (PHP)

use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
use SymfonyComponentValidatorMappingClassMetadataFactory;
use SymfonyComponentValidatorMappingLoaderStaticMethodLoader;


$validator = new Validator(
  new ClassMetadataFactory(new StaticMethodLoader() ),
     new ConstraintValidatorFactory()
);


$person = new Person();
$errors = $validator->validate($person);
Validando un objeto (PHP)
use SymfonyComponentValidatorMappingClassMetadata;
use SymfonyComponentValidatorConstraint as Asserts;


class Person
{
    public $name;
    public $age;


    static function loadValidatorMetadata(ClassMetadata $metadata)
    {
        $metadata
          ->addPropertyConstraint('name', new AssertsNotBlank())
          ->addPropertyConstraint('age' , new AssertsMin(18));
          ->addPropertyConstraint('age' , new AssertsMax(99));
    }
}
Validando un objeto (YAML)


class Person
{
    public $name;
    public $age;
}
Validando un objeto (YAML)


class Person
{
    public $name;
    public $age;
}




$name no puede ser una cadena vacía
$age deberán ser un número comprendido entre 18 y 99 años
Validando un objeto (YAML)


# validate.yml


Person:
  properties:
    name:
      - NotBlank : ~
    age:
      - Min: 18
      - Max: 99
Validando un objeto (YAML)
Validando un objeto (YAML)

use SymfonyComponentValidatorValidator;
Validando un objeto (YAML)

use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
Validando un objeto (YAML)

use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
use SymfonyComponentValidatorMappingClassMetadataFactory;
Validando un objeto (YAML)

use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
use SymfonyComponentValidatorMappingClassMetadataFactory;
use SymfonyComponentValidatorMappingLoaderYamlFileLoader;
Validando un objeto (YAML)

use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
use SymfonyComponentValidatorMappingClassMetadataFactory;
use SymfonyComponentValidatorMappingLoaderYamlFileLoader;


$validator = new Validator(
Validando un objeto (YAML)

use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
use SymfonyComponentValidatorMappingClassMetadataFactory;
use SymfonyComponentValidatorMappingLoaderYamlFileLoader;


$validator = new Validator(
  new ClassMetadataFactory(
Validando un objeto (YAML)

use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
use SymfonyComponentValidatorMappingClassMetadataFactory;
use SymfonyComponentValidatorMappingLoaderYamlFileLoader;


$validator = new Validator(
  new ClassMetadataFactory(
    new YamlFileLoader(__DIR__.'/validate.yml')
Validando un objeto (YAML)

use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
use SymfonyComponentValidatorMappingClassMetadataFactory;
use SymfonyComponentValidatorMappingLoaderYamlFileLoader;


$validator = new Validator(
  new ClassMetadataFactory(
       new YamlFileLoader(__DIR__.'/validate.yml')
  ),
Validando un objeto (YAML)

use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
use SymfonyComponentValidatorMappingClassMetadataFactory;
use SymfonyComponentValidatorMappingLoaderYamlFileLoader;


$validator = new Validator(
  new ClassMetadataFactory(
       new YamlFileLoader(__DIR__.'/validate.yml')
  ),
  new ConstraintValidatorFactory()
Validando un objeto (YAML)

use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
use SymfonyComponentValidatorMappingClassMetadataFactory;
use SymfonyComponentValidatorMappingLoaderYamlFileLoader;


$validator = new Validator(
  new ClassMetadataFactory(
          new YamlFileLoader(__DIR__.'/validate.yml')
     ),
     new ConstraintValidatorFactory()
);
Validando un objeto (YAML)

use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
use SymfonyComponentValidatorMappingClassMetadataFactory;
use SymfonyComponentValidatorMappingLoaderYamlFileLoader;


$validator = new Validator(
  new ClassMetadataFactory(
          new YamlFileLoader(__DIR__.'/validate.yml')
     ),
     new ConstraintValidatorFactory()
);


$person = new Person();
Validando un objeto (YAML)

use SymfonyComponentValidatorValidator;
use SymfonyComponentValidatorConstraintValidatorFactory;
use SymfonyComponentValidatorMappingClassMetadataFactory;
use SymfonyComponentValidatorMappingLoaderYamlFileLoader;


$validator = new Validator(
  new ClassMetadataFactory(
          new YamlFileLoader(__DIR__.'/validate.yml')
     ),
     new ConstraintValidatorFactory()
);


$person = new Person();
$errors = $validator->validate($person);
Console
Facilita la creación de tareas repetitivas
La consola más sencilla
La consola más sencilla



// console.php
La consola más sencilla



// console.php


use SymfonyComponentConsoleApplication;
La consola más sencilla



// console.php


use SymfonyComponentConsoleApplication;


$console = new Application();
La consola más sencilla



// console.php


use SymfonyComponentConsoleApplication;


$console = new Application();
$console->run();
php console.php
php console.php help
php console.php help list
Hola mundo ... para consolas
Hola mundo ... para consolas
use SymfonyComponentConsoleApplication;
Hola mundo ... para consolas
use SymfonyComponentConsoleApplication;
use SymfonyComponentConsoleInputInputArgument;
Hola mundo ... para consolas
use SymfonyComponentConsoleApplication;
use SymfonyComponentConsoleInputInputArgument;


$console = new Application();
Hola mundo ... para consolas
use SymfonyComponentConsoleApplication;
use SymfonyComponentConsoleInputInputArgument;


$console = new Application();
$console
Hola mundo ... para consolas
use SymfonyComponentConsoleApplication;
use SymfonyComponentConsoleInputInputArgument;


$console = new Application();
$console
    ->register('hello')
Hola mundo ... para consolas
use SymfonyComponentConsoleApplication;
use SymfonyComponentConsoleInputInputArgument;


$console = new Application();
$console
    ->register('hello')
    ->setDefinition(array(
Hola mundo ... para consolas
use SymfonyComponentConsoleApplication;
use SymfonyComponentConsoleInputInputArgument;


$console = new Application();
$console
    ->register('hello')
    ->setDefinition(array(
     new InputArgument('name', InputArgument::REQUIRED, 'Nombre'),
Hola mundo ... para consolas
use SymfonyComponentConsoleApplication;
use SymfonyComponentConsoleInputInputArgument;


$console = new Application();
$console
    ->register('hello')
    ->setDefinition(array(
     new InputArgument('name', InputArgument::REQUIRED, 'Nombre'),
    ))
Hola mundo ... para consolas
use SymfonyComponentConsoleApplication;
use SymfonyComponentConsoleInputInputArgument;


$console = new Application();
$console
    ->register('hello')
    ->setDefinition(array(
     new InputArgument('name', InputArgument::REQUIRED, 'Nombre'),
    ))
    ->setDescription('Saluda a una persona')
Hola mundo ... para consolas
use SymfonyComponentConsoleApplication;
use SymfonyComponentConsoleInputInputArgument;


$console = new Application();
$console
    ->register('hello')
    ->setDefinition(array(
     new InputArgument('name', InputArgument::REQUIRED, 'Nombre'),
    ))
    ->setDescription('Saluda a una persona')
    ->setCode(function ($input, $output) {
Hola mundo ... para consolas
use SymfonyComponentConsoleApplication;
use SymfonyComponentConsoleInputInputArgument;


$console = new Application();
$console
    ->register('hello')
    ->setDefinition(array(
     new InputArgument('name', InputArgument::REQUIRED, 'Nombre'),
    ))
    ->setDescription('Saluda a una persona')
    ->setCode(function ($input, $output) {
        $name = $input->getArgument('name');
Hola mundo ... para consolas
use SymfonyComponentConsoleApplication;
use SymfonyComponentConsoleInputInputArgument;


$console = new Application();
$console
    ->register('hello')
    ->setDefinition(array(
     new InputArgument('name', InputArgument::REQUIRED, 'Nombre'),
    ))
    ->setDescription('Saluda a una persona')
    ->setCode(function ($input, $output) {
        $name = $input->getArgument('name');
           $output->writeln(sprintf('Hola <info>%s</info>', $name));
Hola mundo ... para consolas
use SymfonyComponentConsoleApplication;
use SymfonyComponentConsoleInputInputArgument;


$console = new Application();
$console
    ->register('hello')
    ->setDefinition(array(
     new InputArgument('name', InputArgument::REQUIRED, 'Nombre'),
    ))
    ->setDescription('Saluda a una persona')
    ->setCode(function ($input, $output) {
        $name = $input->getArgument('name');
           $output->writeln(sprintf('Hola <info>%s</info>', $name));
    })
Hola mundo ... para consolas
use SymfonyComponentConsoleApplication;
use SymfonyComponentConsoleInputInputArgument;


$console = new Application();
$console
    ->register('hello')
    ->setDefinition(array(
     new InputArgument('name', InputArgument::REQUIRED, 'Nombre'),
    ))
    ->setDescription('Saluda a una persona')
    ->setCode(function ($input, $output) {
        $name = $input->getArgument('name');
           $output->writeln(sprintf('Hola <info>%s</info>', $name));
    })
;
Hola mundo ... para consolas
use SymfonyComponentConsoleApplication;
use SymfonyComponentConsoleInputInputArgument;


$console = new Application();
$console
    ->register('hello')
    ->setDefinition(array(
     new InputArgument('name', InputArgument::REQUIRED, 'Nombre'),
    ))
    ->setDescription('Saluda a una persona')
    ->setCode(function ($input, $output) {
        $name = $input->getArgument('name');
           $output->writeln(sprintf('Hola <info>%s</info>', $name));
    })
;
$console->run();
Hay una manera mejor de hacerlo, Command
Creando un nuevo comando
Creando un nuevo comando
use SymfonyComponentConsoleCommandCommand;
Creando un nuevo comando
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputArgument;
Creando un nuevo comando
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputArgument;

class HelloCommand extends Command
Creando un nuevo comando
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputArgument;

class HelloCommand extends Command
{
Creando un nuevo comando
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputArgument;

class HelloCommand extends Command
{
  public function configure()
Creando un nuevo comando
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputArgument;

class HelloCommand extends Command
{
  public function configure()
  {
Creando un nuevo comando
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputArgument;

class HelloCommand extends Command
{
  public function configure()
  {
    $this->setName('hello');
Creando un nuevo comando
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputArgument;

class HelloCommand extends Command
{
  public function configure()
  {
    $this->setName('hello');
    $this->setDefinition(array(
Creando un nuevo comando
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputArgument;

class HelloCommand extends Command
{
  public function configure()
  {
    $this->setName('hello');
    $this->setDefinition(array(
      new InputArgument('name', InputArgument::REQUIRED, 'Nombre'),
Creando un nuevo comando
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputArgument;

class HelloCommand extends Command
{
  public function configure()
  {
    $this->setName('hello');
    $this->setDefinition(array(
       new InputArgument('name', InputArgument::REQUIRED, 'Nombre'),
    ))
Creando un nuevo comando
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputArgument;

class HelloCommand extends Command
{
  public function configure()
  {
    $this->setName('hello');
    $this->setDefinition(array(
       new InputArgument('name', InputArgument::REQUIRED, 'Nombre'),
    ))
    $this->setDescription('Saluda a una persona')
Creando un nuevo comando
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputArgument;

class HelloCommand extends Command
{
  public function configure()
  {
    $this->setName('hello');
    $this->setDefinition(array(
       new InputArgument('name', InputArgument::REQUIRED, 'Nombre'),
    ))
    $this->setDescription('Saluda a una persona')
  }
Creando un nuevo comando
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputArgument;

class HelloCommand extends Command
{
  public function configure()
  {
    $this->setName('hello');
    $this->setDefinition(array(
       new InputArgument('name', InputArgument::REQUIRED, 'Nombre'),
    ))
    $this->setDescription('Saluda a una persona')
  }

  public function execute($input, $output)
Creando un nuevo comando
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputArgument;

class HelloCommand extends Command
{
  public function configure()
  {
    $this->setName('hello');
    $this->setDefinition(array(
       new InputArgument('name', InputArgument::REQUIRED, 'Nombre'),
    ))
    $this->setDescription('Saluda a una persona')
  }

  public function execute($input, $output)
  {
Creando un nuevo comando
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputArgument;

class HelloCommand extends Command
{
  public function configure()
  {
    $this->setName('hello');
    $this->setDefinition(array(
       new InputArgument('name', InputArgument::REQUIRED, 'Nombre'),
    ))
    $this->setDescription('Saluda a una persona')
  }

  public function execute($input, $output)
  {
    $name = $input->getArgument('name');
Creando un nuevo comando
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputArgument;

class HelloCommand extends Command
{
  public function configure()
  {
    $this->setName('hello');
    $this->setDefinition(array(
       new InputArgument('name', InputArgument::REQUIRED, 'Nombre'),
    ))
    $this->setDescription('Saluda a una persona')
  }

  public function execute($input, $output)
  {
    $name = $input->getArgument('name');
    $output->writeln(sprintf('Hola <info>%s</info>', $name));
Creando un nuevo comando
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputArgument;

class HelloCommand extends Command
{
  public function configure()
  {
    $this->setName('hello');
    $this->setDefinition(array(
       new InputArgument('name', InputArgument::REQUIRED, 'Nombre'),
    ))
    $this->setDescription('Saluda a una persona')
  }

  public function execute($input, $output)
  {
    $name = $input->getArgument('name');
    $output->writeln(sprintf('Hola <info>%s</info>', $name));
  }
Creando un nuevo comando
use SymfonyComponentConsoleCommandCommand;
use SymfonyComponentConsoleInputInputArgument;

class HelloCommand extends Command
{
  public function configure()
  {
    $this->setName('hello');
    $this->setDefinition(array(
       new InputArgument('name', InputArgument::REQUIRED, 'Nombre'),
    ))
    $this->setDescription('Saluda a una persona')
  }

    public function execute($input, $output)
    {
      $name = $input->getArgument('name');
      $output->writeln(sprintf('Hola <info>%s</info>', $name));
    }
}
Creando un nuevo comando
Creando un nuevo comando




use SymfonyComponentConsoleApplication;
Creando un nuevo comando




use SymfonyComponentConsoleApplication;


$console = new Application();
Creando un nuevo comando




use SymfonyComponentConsoleApplication;


$console = new Application();
$console->add(new HelloCommand());
Creando un nuevo comando




use SymfonyComponentConsoleApplication;


$console = new Application();
$console->add(new HelloCommand());
$console->run();
Gracias
@loalf
          Créditos: http://www.flickr.com/photos/normalityrelief/3075723695/

Más contenido relacionado

Destacado

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by HubspotMarius Sescu
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTExpeed Software
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsPixeldarts
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthThinkNow
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfmarketingartwork
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024Neil Kimberley
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)contently
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024Albert Qian
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsKurio // The Social Media Age(ncy)
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Search Engine Journal
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summarySpeakerHub
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next Tessa Mero
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentLily Ray
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best PracticesVit Horky
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project managementMindGenius
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...RachelPearson36
 

Destacado (20)

2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot2024 State of Marketing Report – by Hubspot
2024 State of Marketing Report – by Hubspot
 
Everything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPTEverything You Need To Know About ChatGPT
Everything You Need To Know About ChatGPT
 
Product Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage EngineeringsProduct Design Trends in 2024 | Teenage Engineerings
Product Design Trends in 2024 | Teenage Engineerings
 
How Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental HealthHow Race, Age and Gender Shape Attitudes Towards Mental Health
How Race, Age and Gender Shape Attitudes Towards Mental Health
 
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdfAI Trends in Creative Operations 2024 by Artwork Flow.pdf
AI Trends in Creative Operations 2024 by Artwork Flow.pdf
 
Skeleton Culture Code
Skeleton Culture CodeSkeleton Culture Code
Skeleton Culture Code
 
PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024PEPSICO Presentation to CAGNY Conference Feb 2024
PEPSICO Presentation to CAGNY Conference Feb 2024
 
Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)Content Methodology: A Best Practices Report (Webinar)
Content Methodology: A Best Practices Report (Webinar)
 
How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024How to Prepare For a Successful Job Search for 2024
How to Prepare For a Successful Job Search for 2024
 
Social Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie InsightsSocial Media Marketing Trends 2024 // The Global Indie Insights
Social Media Marketing Trends 2024 // The Global Indie Insights
 
Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024Trends In Paid Search: Navigating The Digital Landscape In 2024
Trends In Paid Search: Navigating The Digital Landscape In 2024
 
5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary5 Public speaking tips from TED - Visualized summary
5 Public speaking tips from TED - Visualized summary
 
ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd ChatGPT and the Future of Work - Clark Boyd
ChatGPT and the Future of Work - Clark Boyd
 
Getting into the tech field. what next
Getting into the tech field. what next Getting into the tech field. what next
Getting into the tech field. what next
 
Google's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search IntentGoogle's Just Not That Into You: Understanding Core Updates & Search Intent
Google's Just Not That Into You: Understanding Core Updates & Search Intent
 
How to have difficult conversations
How to have difficult conversations How to have difficult conversations
How to have difficult conversations
 
Introduction to Data Science
Introduction to Data ScienceIntroduction to Data Science
Introduction to Data Science
 
Time Management & Productivity - Best Practices
Time Management & Productivity -  Best PracticesTime Management & Productivity -  Best Practices
Time Management & Productivity - Best Practices
 
The six step guide to practical project management
The six step guide to practical project managementThe six step guide to practical project management
The six step guide to practical project management
 
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
Beginners Guide to TikTok for Search - Rachel Pearson - We are Tilt __ Bright...
 

Slides componentes

  • 1. Componentes El arma secreta de Symfony #sf2Vigo Javier López | @loalf
  • 2. Javier López Nací en Córdoba, España. Vivo en Londres, Reino Unido. Trabajo en IPC Media (http://ipcmedia.com). Escribo (a veces) en mi blog (http://www.loalf.com). Twitteo como @loalf ... ¿quiéres saber más? http://www.linkedin.com/in/loalf
  • 4. Son un conjunto de librerías autónomas, desacopladas y complementarias que resuelven problemas comunes del desarrollo web
  • 5. 21 Componentes Browserkit EventDispatcher Security ClassLoader Routing HttpFoundation Finder DependencyInjection Config Console CssSelector Locale Form DomCrawler HttpKernel Serializer Process Templating Yaml Validator Translation
  • 6. 21 Componentes Browserkit EventDispatcher Security ClassLoader Routing HttpFoundation Finder DependencyInjection Config Console CssSelector Locale Form DomCrawler HttpKernel Serializer Process Templating Yaml Validator Translation
  • 8. mkdir ComponentPlayground cd ComponentPlayground mkdir vendor cd vendor git clone https://github.com/symfony/symfony
  • 18. autoload.php <?php require_once __DIR__.'/vendor/symfony/src/Symfony/Component/ ClassLoader/UniversalClassLoader.php'; use SymfonyComponentClassLoaderUniversalClassLoader; $loader = new UniversalClassLoader(); $loader->registerNamespaces(array( 'Symfony' => __DIR__.'/vendor/symfony/src', )); $loader->register();
  • 25. ejemplo.php <?php require_once 'autoload.php'; /* * Código del ejemplo */ > php ejemplo.php
  • 26. Yaml
  • 27. Parsea y genera archivos yml
  • 28. parseando archivos YAML #example.yml descripcion: “Usuarios de symfony” usuarios: javi: nombre: “Javi” apellidos: “López” raul: nombre: “Raúl” apellidos: “Fraile”
  • 29. parseando archivos YAML use SymfonyComponentYamlYaml; #example.yml descripcion: “Usuarios de symfony” usuarios: javi: nombre: “Javi” apellidos: “López” raul: nombre: “Raúl” apellidos: “Fraile”
  • 30. parseando archivos YAML use SymfonyComponentYamlYaml; #example.yml $data = Yaml::parse('example.yml'); descripcion: “Usuarios de symfony” usuarios: javi: nombre: “Javi” apellidos: “López” raul: nombre: “Raúl” apellidos: “Fraile”
  • 31. parseando archivos YAML use SymfonyComponentYamlYaml; #example.yml $data = Yaml::parse('example.yml'); descripcion: “Usuarios de symfony” usuarios: print $data['descripcion']; javi: nombre: “Javi” apellidos: “López” raul: nombre: “Raúl” apellidos: “Fraile”
  • 32. parseando archivos YAML use SymfonyComponentYamlYaml; #example.yml $data = Yaml::parse('example.yml'); descripcion: “Usuarios de symfony” usuarios: print $data['descripcion']; javi: nombre: “Javi” foreach( $data['usuarios'] as $usuario) apellidos: “López” raul: nombre: “Raúl” apellidos: “Fraile”
  • 33. parseando archivos YAML use SymfonyComponentYamlYaml; #example.yml $data = Yaml::parse('example.yml'); descripcion: “Usuarios de symfony” usuarios: print $data['descripcion']; javi: nombre: “Javi” foreach( $data['usuarios'] as $usuario) apellidos: “López” { raul: nombre: “Raúl” apellidos: “Fraile”
  • 34. parseando archivos YAML use SymfonyComponentYamlYaml; #example.yml $data = Yaml::parse('example.yml'); descripcion: “Usuarios de symfony” usuarios: print $data['descripcion']; javi: nombre: “Javi” foreach( $data['usuarios'] as $usuario) apellidos: “López” { raul: print $usuario['nombre'] nombre: “Raúl” apellidos: “Fraile”
  • 35. parseando archivos YAML use SymfonyComponentYamlYaml; #example.yml $data = Yaml::parse('example.yml'); descripcion: “Usuarios de symfony” usuarios: print $data['descripcion']; javi: nombre: “Javi” foreach( $data['usuarios'] as $usuario) apellidos: “López” { raul: print $usuario['nombre'] nombre: “Raúl” .' '. apellidos: “Fraile”
  • 36. parseando archivos YAML use SymfonyComponentYamlYaml; #example.yml $data = Yaml::parse('example.yml'); descripcion: “Usuarios de symfony” usuarios: print $data['descripcion']; javi: nombre: “Javi” foreach( $data['usuarios'] as $usuario) apellidos: “López” { raul: print $usuario['nombre'] nombre: “Raúl” .' '. apellidos: “Fraile” $usuario['apellidos'];
  • 37. parseando archivos YAML use SymfonyComponentYamlYaml; #example.yml $data = Yaml::parse('example.yml'); descripcion: “Usuarios de symfony” usuarios: print $data['descripcion']; javi: nombre: “Javi” foreach( $data['usuarios'] as $usuario) apellidos: “López” { raul: print $usuario['nombre'] nombre: “Raúl” .' '. apellidos: “Fraile” $usuario['apellidos']; }
  • 38. parseando archivos YAML use SymfonyComponentYamlYaml; #example.yml $data = Yaml::parse('example.yml'); descripcion: “Usuarios de symfony” usuarios: print $data['descripcion']; - nombre: “Javi” foreach( $data['usuarios'] as $usuario) apellidos: “López” { - print $usuario['nombre'] nombre: “Raúl” .' '. apellidos: “Fraile” $usuario['apellidos']; }
  • 40. generando archivos YAML use SymfonyComponentYamlYaml;
  • 41. generando archivos YAML use SymfonyComponentYamlYaml; $data['descripcion'] = "Usuarios de symfony";
  • 42. generando archivos YAML use SymfonyComponentYamlYaml; $data['descripcion'] = "Usuarios de symfony"; $data['usuarios'][] = array(
  • 43. generando archivos YAML use SymfonyComponentYamlYaml; $data['descripcion'] = "Usuarios de symfony"; $data['usuarios'][] = array( 'nombre' => 'Javi',
  • 44. generando archivos YAML use SymfonyComponentYamlYaml; $data['descripcion'] = "Usuarios de symfony"; $data['usuarios'][] = array( 'nombre' => 'Javi', 'apellidos' => 'Lopez'
  • 45. generando archivos YAML use SymfonyComponentYamlYaml; $data['descripcion'] = "Usuarios de symfony"; $data['usuarios'][] = array( 'nombre' => 'Javi', 'apellidos' => 'Lopez' );
  • 46. generando archivos YAML use SymfonyComponentYamlYaml; $data['descripcion'] = "Usuarios de symfony"; $data['usuarios'][] = array( 'nombre' => 'Javi', 'apellidos' => 'Lopez' ); $data['usuarios'][] = array(
  • 47. generando archivos YAML use SymfonyComponentYamlYaml; $data['descripcion'] = "Usuarios de symfony"; $data['usuarios'][] = array( 'nombre' => 'Javi', 'apellidos' => 'Lopez' ); $data['usuarios'][] = array( 'nombre' => 'Raul',
  • 48. generando archivos YAML use SymfonyComponentYamlYaml; $data['descripcion'] = "Usuarios de symfony"; $data['usuarios'][] = array( 'nombre' => 'Javi', 'apellidos' => 'Lopez' ); $data['usuarios'][] = array( 'nombre' => 'Raul', 'apellidos' => 'Fraile'
  • 49. generando archivos YAML use SymfonyComponentYamlYaml; $data['descripcion'] = "Usuarios de symfony"; $data['usuarios'][] = array( 'nombre' => 'Javi', 'apellidos' => 'Lopez' ); $data['usuarios'][] = array( 'nombre' => 'Raul', 'apellidos' => 'Fraile' );
  • 50. generando archivos YAML use SymfonyComponentYamlYaml; $data['descripcion'] = "Usuarios de symfony"; $data['usuarios'][] = array( 'nombre' => 'Javi', 'apellidos' => 'Lopez' ); $data['usuarios'][] = array( 'nombre' => 'Raul', 'apellidos' => 'Fraile' ); print Yaml::dump($data);
  • 51. generando archivos YAML use SymfonyComponentYamlYaml; $data['descripcion'] = "Usuarios de symfony"; descripcion: “Usuarios de symfony” $data['usuarios'][] = array( usuarios: 'nombre' => 'Javi', 0: 'apellidos' => 'Lopez' nombre: “Javi” ); apellidos: “López” 1: $data['usuarios'][] = array( nombre: “Raúl” 'nombre' => 'Raul', apellidos: “Fraile” 'apellidos' => 'Fraile' ); print Yaml::dump($data);
  • 52. YAML & PHP #example.yml generado: <?php echo date(‘d-m-Y’); ?> descripcion: “Usuarios de symfony” usuarios: javi: nombre: “Javi” apellidos: “López” raul: nombre: “Raúl” apellidos: “Fraile”
  • 53. YAML & PHP #example.yml generado: <?php echo date(‘d-m-Y’); ?> use SymfonyComponentYamlYaml; descripcion: “Usuarios de symfony” usuarios: Yaml::enablePhpParsing(); javi: nombre: “Javi” $data = Yaml::parse('example.yml'); apellidos: “López” raul: print $data['generado']; nombre: “Raúl” apellidos: “Fraile”
  • 55. Herramienta para encontrar archivos y directorios
  • 57. buscando archivos por nombre use SymfonyComponentFinderFinder;
  • 58. buscando archivos por nombre use SymfonyComponentFinderFinder; $files = Finder::create()
  • 59. buscando archivos por nombre use SymfonyComponentFinderFinder; $files = Finder::create() ->name("*.php")
  • 60. buscando archivos por nombre use SymfonyComponentFinderFinder; $files = Finder::create() ->name("*.php") ->name("*.{php,yml}")
  • 61. buscando archivos por nombre use SymfonyComponentFinderFinder; $files = Finder::create() ->name("*.php") ->name("*.{php,yml}") ->name("/.(php|yml)$/")
  • 62. buscando archivos por nombre use SymfonyComponentFinderFinder; $files = Finder::create() ->name("*.php") ->name("*.{php,yml}") ->name("/.(php|yml)$/") ->name("/^w{3,10}$/")
  • 63. buscando archivos por nombre use SymfonyComponentFinderFinder; $files = Finder::create() ->name("*.php") ->name("*.{php,yml}") ->name("/.(php|yml)$/") ->name("/^w{3,10}$/") ->name("foo.php")
  • 64. buscando archivos por nombre use SymfonyComponentFinderFinder; $files = Finder::create() ->name("*.php") ->name("*.{php,yml}") ->name("/.(php|yml)$/") ->name("/^w{3,10}$/") ->name("foo.php") ->in(__DIR__);
  • 65. buscando archivos por nombre use SymfonyComponentFinderFinder; $files = Finder::create() ->name("*.php") ->name("*.{php,yml}") ->name("/.(php|yml)$/") ->name("/^w{3,10}$/") ->name("foo.php") ->in(__DIR__); Referencia sobre Patrones Glob: http://cowburn.info/2010/04/30/glob-patterns/
  • 67. buscando archivos por tamaño use SymfonyComponentFinderFinder;
  • 68. buscando archivos por tamaño use SymfonyComponentFinderFinder; $files = Finder::create()
  • 69. buscando archivos por tamaño use SymfonyComponentFinderFinder; $files = Finder::create() ->size("> 10k")
  • 70. buscando archivos por tamaño use SymfonyComponentFinderFinder; $files = Finder::create() ->size("> 10k") ->size("<= 4mi")
  • 71. buscando archivos por tamaño use SymfonyComponentFinderFinder; $files = Finder::create() ->size("> 10k") ->size("<= 4mi") ->size("2gi")
  • 72. buscando archivos por tamaño use SymfonyComponentFinderFinder; $files = Finder::create() ->size("> 10k") ->size("<= 4mi") ->size("2gi") ->in(__DIR__);
  • 73. buscando archivos por tamaño use SymfonyComponentFinderFinder; $files = Finder::create() ->size("> 10k") ->size("<= 4mi") ->size("2gi") ->in(__DIR__); k = 1000 ki = 1024 m = 1000^2 mi = 1024^2 g = 1000^3 gi = 1024^3
  • 75. buscando archivos por fecha use SymfonyComponentFinderFinder;
  • 76. buscando archivos por fecha use SymfonyComponentFinderFinder; $files = Finder::create()
  • 77. buscando archivos por fecha use SymfonyComponentFinderFinder; $files = Finder::create() ->date("since yesterday")
  • 78. buscando archivos por fecha use SymfonyComponentFinderFinder; $files = Finder::create() ->date("since yesterday") ->date("until 2 days ago")
  • 79. buscando archivos por fecha use SymfonyComponentFinderFinder; $files = Finder::create() ->date("since yesterday") ->date("until 2 days ago") ->date("> now - 2 hours")
  • 80. buscando archivos por fecha use SymfonyComponentFinderFinder; $files = Finder::create() ->date("since yesterday") ->date("until 2 days ago") ->date("> now - 2 hours") ->date(">= 2005-10-15 ")
  • 81. buscando archivos por fecha use SymfonyComponentFinderFinder; $files = Finder::create() ->date("since yesterday") ->date("until 2 days ago") ->date("> now - 2 hours") ->date(">= 2005-10-15 ") ->in(__DIR__);
  • 82. buscando archivos por fecha use SymfonyComponentFinderFinder; $files = Finder::create() ->date("since yesterday") ->date("until 2 days ago") ->date("> now - 2 hours") ->date(">= 2005-10-15 ") ->in(__DIR__); Parámetro es cualquier argumento válido para strtotime()
  • 83. fijando el nivel de profundidad
  • 84. fijando el nivel de profundidad use SymfonyComponentFinderFinder;
  • 85. fijando el nivel de profundidad use SymfonyComponentFinderFinder; $files = Finder::create()
  • 86. fijando el nivel de profundidad use SymfonyComponentFinderFinder; $files = Finder::create() ->depth(0)
  • 87. fijando el nivel de profundidad use SymfonyComponentFinderFinder; $files = Finder::create() ->depth(0) ->depth(>1)
  • 88. fijando el nivel de profundidad use SymfonyComponentFinderFinder; $files = Finder::create() ->depth(0) ->depth(>1) ->depth(<3)
  • 89. fijando el nivel de profundidad use SymfonyComponentFinderFinder; $files = Finder::create() ->depth(0) ->depth(>1) ->depth(<3) ->in(__DIR__);
  • 91. buscando sólo archivos use SymfonyComponentFinderFinder; $files = Finder::create() ->files() ->in(__DIR__);
  • 93. buscando sólo directorios use SymfonyComponentFinderFinder; $files = Finder::create() ->directories() ->in(__DIR__);
  • 95. obteniendo un resultado ordenado use SymfonyComponentFinderFinder;
  • 96. obteniendo un resultado ordenado use SymfonyComponentFinderFinder; $files = Finder::create()
  • 97. obteniendo un resultado ordenado use SymfonyComponentFinderFinder; $files = Finder::create() ->sortByName()
  • 98. obteniendo un resultado ordenado use SymfonyComponentFinderFinder; $files = Finder::create() ->sortByName() ->sortByType()
  • 99. obteniendo un resultado ordenado use SymfonyComponentFinderFinder; $files = Finder::create() ->sortByName() ->sortByType() ->sort(
  • 100. obteniendo un resultado ordenado use SymfonyComponentFinderFinder; $files = Finder::create() ->sortByName() ->sortByType() ->sort( function(SplFileInfo $file1, SplFileInfo $file2){
  • 101. obteniendo un resultado ordenado use SymfonyComponentFinderFinder; $files = Finder::create() ->sortByName() ->sortByType() ->sort( function(SplFileInfo $file1, SplFileInfo $file2){ return $file1->getSize() > $file2->getSize();
  • 102. obteniendo un resultado ordenado use SymfonyComponentFinderFinder; $files = Finder::create() ->sortByName() ->sortByType() ->sort( function(SplFileInfo $file1, SplFileInfo $file2){ return $file1->getSize() > $file2->getSize(); }
  • 103. obteniendo un resultado ordenado use SymfonyComponentFinderFinder; $files = Finder::create() ->sortByName() ->sortByType() ->sort( function(SplFileInfo $file1, SplFileInfo $file2){ return $file1->getSize() > $file2->getSize(); } )
  • 104. obteniendo un resultado ordenado use SymfonyComponentFinderFinder; $files = Finder::create() ->sortByName() ->sortByType() ->sort( function(SplFileInfo $file1, SplFileInfo $file2){ return $file1->getSize() > $file2->getSize(); } ) ->in(__DIR__);
  • 105. archivos php en la carpeta raíz del proyecto
  • 106. archivos php en la carpeta raíz del proyecto use SymfonyComponentFinderFinder;
  • 107. archivos php en la carpeta raíz del proyecto use SymfonyComponentFinderFinder; $files = Finder::create()
  • 108. archivos php en la carpeta raíz del proyecto use SymfonyComponentFinderFinder; $files = Finder::create() ->files()
  • 109. archivos php en la carpeta raíz del proyecto use SymfonyComponentFinderFinder; $files = Finder::create() ->files() ->depth(0)
  • 110. archivos php en la carpeta raíz del proyecto use SymfonyComponentFinderFinder; $files = Finder::create() ->files() ->depth(0) ->name("*.php")
  • 111. archivos php en la carpeta raíz del proyecto use SymfonyComponentFinderFinder; $files = Finder::create() ->files() ->depth(0) ->name("*.php") ->in(__DIR__);
  • 112. imágenes en un contener Amazon S3
  • 113. imágenes en un contener Amazon S3 $s3 = new Zend_Service_Amazon_S3($key, $secret);
  • 114. imágenes en un contener Amazon S3 $s3 = new Zend_Service_Amazon_S3($key, $secret); $s3->registerStreamWrapper("s3");
  • 115. imágenes en un contener Amazon S3 $s3 = new Zend_Service_Amazon_S3($key, $secret); $s3->registerStreamWrapper("s3");
  • 116. imágenes en un contener Amazon S3 $s3 = new Zend_Service_Amazon_S3($key, $secret); $s3->registerStreamWrapper("s3"); $files = Finder::create()
  • 117. imágenes en un contener Amazon S3 $s3 = new Zend_Service_Amazon_S3($key, $secret); $s3->registerStreamWrapper("s3"); $files = Finder::create() ->name('*.{jpg,jpeg,png,gif}')
  • 118. imágenes en un contener Amazon S3 $s3 = new Zend_Service_Amazon_S3($key, $secret); $s3->registerStreamWrapper("s3"); $files = Finder::create() ->name('*.{jpg,jpeg,png,gif}') ->size('< 100K')
  • 119. imágenes en un contener Amazon S3 $s3 = new Zend_Service_Amazon_S3($key, $secret); $s3->registerStreamWrapper("s3"); $files = Finder::create() ->name('*.{jpg,jpeg,png,gif}') ->size('< 100K') ->date('since 1 hour ago')
  • 120. imágenes en un contener Amazon S3 $s3 = new Zend_Service_Amazon_S3($key, $secret); $s3->registerStreamWrapper("s3"); $files = Finder::create() ->name('*.{jpg,jpeg,png,gif}') ->size('< 100K') ->date('since 1 hour ago') ->in('s3://bucket-name');
  • 122. Facilita la ejecución de comandos del sistema
  • 124. ¿está Twitter online? use SymfonyComponentProcessProcess;
  • 125. ¿está Twitter online? use SymfonyComponentProcessProcess; $process = new Process('ping -c 1 twitter.com');
  • 126. ¿está Twitter online? use SymfonyComponentProcessProcess; $process = new Process('ping -c 1 twitter.com'); $process->run();
  • 127. ¿está Twitter online? use SymfonyComponentProcessProcess; $process = new Process('ping -c 1 twitter.com'); $process->run(); if($process->isSuccessful()){
  • 128. ¿está Twitter online? use SymfonyComponentProcessProcess; $process = new Process('ping -c 1 twitter.com'); $process->run(); if($process->isSuccessful()){ print "Twitter esta online";
  • 129. ¿está Twitter online? use SymfonyComponentProcessProcess; $process = new Process('ping -c 1 twitter.com'); $process->run(); if($process->isSuccessful()){ print "Twitter esta online"; }else{
  • 130. ¿está Twitter online? use SymfonyComponentProcessProcess; $process = new Process('ping -c 1 twitter.com'); $process->run(); if($process->isSuccessful()){ print "Twitter esta online"; }else{ print "Twitter esta offline";
  • 131. ¿está Twitter online? use SymfonyComponentProcessProcess; $process = new Process('ping -c 1 twitter.com'); $process->run(); if($process->isSuccessful()){ print "Twitter esta online"; }else{ print "Twitter esta offline"; }
  • 132. ping -c 4 twitter.com
  • 133. calculando tiempos medios de respuesta
  • 134. calculando tiempos medios de respuesta $process = new Process('ping -c 4 twitter.com');
  • 135. calculando tiempos medios de respuesta $process = new Process('ping -c 4 twitter.com'); $process->run();
  • 136. calculando tiempos medios de respuesta $process = new Process('ping -c 4 twitter.com'); $process->run(); if($process->isSuccessful())
  • 137. calculando tiempos medios de respuesta $process = new Process('ping -c 4 twitter.com'); $process->run(); if($process->isSuccessful()) {
  • 138. calculando tiempos medios de respuesta $process = new Process('ping -c 4 twitter.com'); $process->run(); if($process->isSuccessful()) { $output = $process->getOutput();
  • 139. calculando tiempos medios de respuesta $process = new Process('ping -c 4 twitter.com'); $process->run(); if($process->isSuccessful()) { $output = $process->getOutput();
  • 140. calculando tiempos medios de respuesta $process = new Process('ping -c 4 twitter.com'); $process->run(); if($process->isSuccessful()) { $output = $process->getOutput(); $pattern = '/time=(d+.d+) ms/';
  • 141. calculando tiempos medios de respuesta $process = new Process('ping -c 4 twitter.com'); $process->run(); if($process->isSuccessful()) { $output = $process->getOutput(); $pattern = '/time=(d+.d+) ms/'; preg_match_all($pattern, $output, $matches);
  • 142. calculando tiempos medios de respuesta $process = new Process('ping -c 4 twitter.com'); $process->run(); if($process->isSuccessful()) { $output = $process->getOutput(); $pattern = '/time=(d+.d+) ms/'; preg_match_all($pattern, $output, $matches); $average = array_sum($matches[1])/count($matches[1]);
  • 143. calculando tiempos medios de respuesta $process = new Process('ping -c 4 twitter.com'); $process->run(); if($process->isSuccessful()) { $output = $process->getOutput(); $pattern = '/time=(d+.d+) ms/'; preg_match_all($pattern, $output, $matches); $average = array_sum($matches[1])/count($matches[1]);
  • 144. calculando tiempos medios de respuesta $process = new Process('ping -c 4 twitter.com'); $process->run(); if($process->isSuccessful()) { $output = $process->getOutput(); $pattern = '/time=(d+.d+) ms/'; preg_match_all($pattern, $output, $matches); $average = array_sum($matches[1])/count($matches[1]); printf("Avergage time=%.3f ms", $average);
  • 145. calculando tiempos medios de respuesta $process = new Process('ping -c 4 twitter.com'); $process->run(); if($process->isSuccessful()) { $output = $process->getOutput(); $pattern = '/time=(d+.d+) ms/'; preg_match_all($pattern, $output, $matches); $average = array_sum($matches[1])/count($matches[1]); printf("Avergage time=%.3f ms", $average); }else{
  • 146. calculando tiempos medios de respuesta $process = new Process('ping -c 4 twitter.com'); $process->run(); if($process->isSuccessful()) { $output = $process->getOutput(); $pattern = '/time=(d+.d+) ms/'; preg_match_all($pattern, $output, $matches); $average = array_sum($matches[1])/count($matches[1]); printf("Avergage time=%.3f ms", $average); }else{ print "Twitter está offline";
  • 147. calculando tiempos medios de respuesta $process = new Process('ping -c 4 twitter.com'); $process->run(); if($process->isSuccessful()) { $output = $process->getOutput(); $pattern = '/time=(d+.d+) ms/'; preg_match_all($pattern, $output, $matches); $average = array_sum($matches[1])/count($matches[1]); printf("Avergage time=%.3f ms", $average); }else{ print "Twitter está offline"; }
  • 149. mostrando sólo los tiempos use SymfonyComponentProcessProcess;
  • 150. mostrando sólo los tiempos use SymfonyComponentProcessProcess; $process = new Process('ping -c 4 twitter.com');
  • 151. mostrando sólo los tiempos use SymfonyComponentProcessProcess; $process = new Process('ping -c 4 twitter.com'); $process->run(function($type, $buffer) {
  • 152. mostrando sólo los tiempos use SymfonyComponentProcessProcess; $process = new Process('ping -c 4 twitter.com'); $process->run(function($type, $buffer) { if('out' === $type){
  • 153. mostrando sólo los tiempos use SymfonyComponentProcessProcess; $process = new Process('ping -c 4 twitter.com'); $process->run(function($type, $buffer) { if('out' === $type){ $pattern = '/time=(d+.d+) ms/';
  • 154. mostrando sólo los tiempos use SymfonyComponentProcessProcess; $process = new Process('ping -c 4 twitter.com'); $process->run(function($type, $buffer) { if('out' === $type){ $pattern = '/time=(d+.d+) ms/'; if(preg_match_all($pattern, $buffer, $matches)){;
  • 155. mostrando sólo los tiempos use SymfonyComponentProcessProcess; $process = new Process('ping -c 4 twitter.com'); $process->run(function($type, $buffer) { if('out' === $type){ $pattern = '/time=(d+.d+) ms/'; if(preg_match_all($pattern, $buffer, $matches)){; print $matches[0][0]."n";
  • 156. mostrando sólo los tiempos use SymfonyComponentProcessProcess; $process = new Process('ping -c 4 twitter.com'); $process->run(function($type, $buffer) { if('out' === $type){ $pattern = '/time=(d+.d+) ms/'; if(preg_match_all($pattern, $buffer, $matches)){; print $matches[0][0]."n"; }
  • 157. mostrando sólo los tiempos use SymfonyComponentProcessProcess; $process = new Process('ping -c 4 twitter.com'); $process->run(function($type, $buffer) { if('out' === $type){ $pattern = '/time=(d+.d+) ms/'; if(preg_match_all($pattern, $buffer, $matches)){; print $matches[0][0]."n"; } }elseif( 'err' === $type ){
  • 158. mostrando sólo los tiempos use SymfonyComponentProcessProcess; $process = new Process('ping -c 4 twitter.com'); $process->run(function($type, $buffer) { if('out' === $type){ $pattern = '/time=(d+.d+) ms/'; if(preg_match_all($pattern, $buffer, $matches)){; print $matches[0][0]."n"; } }elseif( 'err' === $type ){ print "Twitter esta offline";
  • 159. mostrando sólo los tiempos use SymfonyComponentProcessProcess; $process = new Process('ping -c 4 twitter.com'); $process->run(function($type, $buffer) { if('out' === $type){ $pattern = '/time=(d+.d+) ms/'; if(preg_match_all($pattern, $buffer, $matches)){; print $matches[0][0]."n"; } }elseif( 'err' === $type ){ print "Twitter esta offline"; }
  • 160. mostrando sólo los tiempos use SymfonyComponentProcessProcess; $process = new Process('ping -c 4 twitter.com'); $process->run(function($type, $buffer) { if('out' === $type){ $pattern = '/time=(d+.d+) ms/'; if(preg_match_all($pattern, $buffer, $matches)){; print $matches[0][0]."n"; } }elseif( 'err' === $type ){ print "Twitter esta offline"; } });
  • 162. Facilita la extracción de información de objetos DOM
  • 164. Búsqueda en Twitter use SymfonyComponentDomCrawlerCrawler;
  • 165. Búsqueda en Twitter use SymfonyComponentDomCrawlerCrawler; $uri = 'http://search.twitter.com/search.atom?q=sf2vigo';
  • 166. Búsqueda en Twitter use SymfonyComponentDomCrawlerCrawler; $uri = 'http://search.twitter.com/search.atom?q=sf2vigo'; $crawler = new Crawler();
  • 167. Búsqueda en Twitter use SymfonyComponentDomCrawlerCrawler; $uri = 'http://search.twitter.com/search.atom?q=sf2vigo'; $crawler = new Crawler(); $content = file_get_contents($uri);
  • 168. Búsqueda en Twitter use SymfonyComponentDomCrawlerCrawler; $uri = 'http://search.twitter.com/search.atom?q=sf2vigo'; $crawler = new Crawler(); $content = file_get_contents($uri); $crawler->addXmlContent($content);
  • 169. Búsqueda en Twitter use SymfonyComponentDomCrawlerCrawler; $uri = 'http://search.twitter.com/search.atom?q=sf2vigo'; $crawler = new Crawler(); $content = file_get_contents($uri); $crawler->addXmlContent($content); foreach($crawler->filterXpath('//content') as $node)
  • 170. Búsqueda en Twitter use SymfonyComponentDomCrawlerCrawler; $uri = 'http://search.twitter.com/search.atom?q=sf2vigo'; $crawler = new Crawler(); $content = file_get_contents($uri); $crawler->addXmlContent($content); foreach($crawler->filterXpath('//content') as $node) {
  • 171. Búsqueda en Twitter use SymfonyComponentDomCrawlerCrawler; $uri = 'http://search.twitter.com/search.atom?q=sf2vigo'; $crawler = new Crawler(); $content = file_get_contents($uri); $crawler->addXmlContent($content); foreach($crawler->filterXpath('//content') as $node) { print $node->nodeValue;
  • 172. Búsqueda en Twitter use SymfonyComponentDomCrawlerCrawler; $uri = 'http://search.twitter.com/search.atom?q=sf2vigo'; $crawler = new Crawler(); $content = file_get_contents($uri); $crawler->addXmlContent($content); foreach($crawler->filterXpath('//content') as $node) { print $node->nodeValue; }
  • 173. Enlaces del blog de symfony.com
  • 174. Enlaces del blog de symfony.com use SymfonyComponentDomCrawlerCrawler;
  • 175. Enlaces del blog de symfony.com use SymfonyComponentDomCrawlerCrawler; $uri = 'http://symfony.com/blog';
  • 176. Enlaces del blog de symfony.com use SymfonyComponentDomCrawlerCrawler; $uri = 'http://symfony.com/blog'; $content = file_get_contents($uri);
  • 177. Enlaces del blog de symfony.com use SymfonyComponentDomCrawlerCrawler; $uri = 'http://symfony.com/blog'; $content = file_get_contents($uri); $crawler = new Crawler($content, $uri);
  • 178. Enlaces del blog de symfony.com use SymfonyComponentDomCrawlerCrawler; $uri = 'http://symfony.com/blog'; $content = file_get_contents($uri); $crawler = new Crawler($content, $uri); $nodes = $crawler->filterXPath('//div[@class="box_article"]//a');
  • 179. Enlaces del blog de symfony.com use SymfonyComponentDomCrawlerCrawler; $uri = 'http://symfony.com/blog'; $content = file_get_contents($uri); $crawler = new Crawler($content, $uri); $nodes = $crawler->filterXPath('//div[@class="box_article"]//a'); foreach($nodes->links() as $link)
  • 180. Enlaces del blog de symfony.com use SymfonyComponentDomCrawlerCrawler; $uri = 'http://symfony.com/blog'; $content = file_get_contents($uri); $crawler = new Crawler($content, $uri); $nodes = $crawler->filterXPath('//div[@class="box_article"]//a'); foreach($nodes->links() as $link) {
  • 181. Enlaces del blog de symfony.com use SymfonyComponentDomCrawlerCrawler; $uri = 'http://symfony.com/blog'; $content = file_get_contents($uri); $crawler = new Crawler($content, $uri); $nodes = $crawler->filterXPath('//div[@class="box_article"]//a'); foreach($nodes->links() as $link) { print $link->getUri();
  • 182. Enlaces del blog de symfony.com use SymfonyComponentDomCrawlerCrawler; $uri = 'http://symfony.com/blog'; $content = file_get_contents($uri); $crawler = new Crawler($content, $uri); $nodes = $crawler->filterXPath('//div[@class="box_article"]//a'); foreach($nodes->links() as $link) { print $link->getUri(); }
  • 184. Selectores CSS => Expresiones XPath
  • 186. Convirtiendo CSS a XPath use SymfonyComponentCssSelectorCssSelector;
  • 187. Convirtiendo CSS a XPath use SymfonyComponentCssSelectorCssSelector; print CssSelector::toXPath('div.box_article a');
  • 188. Convirtiendo CSS a XPath use SymfonyComponentCssSelectorCssSelector; print CssSelector::toXPath('div.box_article a'); /*
  • 189. Convirtiendo CSS a XPath use SymfonyComponentCssSelectorCssSelector; print CssSelector::toXPath('div.box_article a'); /* * descendant-or-self::div[
  • 190. Convirtiendo CSS a XPath use SymfonyComponentCssSelectorCssSelector; print CssSelector::toXPath('div.box_article a'); /* * descendant-or-self::div[ * contains(
  • 191. Convirtiendo CSS a XPath use SymfonyComponentCssSelectorCssSelector; print CssSelector::toXPath('div.box_article a'); /* * descendant-or-self::div[ * contains( * concat(' ', normalize- space(@class), ' '),
  • 192. Convirtiendo CSS a XPath use SymfonyComponentCssSelectorCssSelector; print CssSelector::toXPath('div.box_article a'); /* * descendant-or-self::div[ * contains( * concat(' ', normalize- space(@class), ' '), * ' box_article '
  • 193. Convirtiendo CSS a XPath use SymfonyComponentCssSelectorCssSelector; print CssSelector::toXPath('div.box_article a'); /* * descendant-or-self::div[ * contains( * concat(' ', normalize- space(@class), ' '), * ' box_article ' * )
  • 194. Convirtiendo CSS a XPath use SymfonyComponentCssSelectorCssSelector; print CssSelector::toXPath('div.box_article a'); /* * descendant-or-self::div[ * contains( * concat(' ', normalize- space(@class), ' '), * ' box_article ' * ) * ]/descendant::a
  • 195. Convirtiendo CSS a XPath use SymfonyComponentCssSelectorCssSelector; print CssSelector::toXPath('div.box_article a'); /* * descendant-or-self::div[ * contains( * concat(' ', normalize- space(@class), ' '), * ' box_article ' * ) * ]/descendant::a */
  • 196. Enlaces del blog de symfony.com
  • 197. Enlaces del blog de symfony.com use SymfonyComponentDomCrawlerCrawler;
  • 198. Enlaces del blog de symfony.com use SymfonyComponentDomCrawlerCrawler; $uri = 'http://symfony.com/blog';
  • 199. Enlaces del blog de symfony.com use SymfonyComponentDomCrawlerCrawler; $uri = 'http://symfony.com/blog'; $content = file_get_contents($uri);
  • 200. Enlaces del blog de symfony.com use SymfonyComponentDomCrawlerCrawler; $uri = 'http://symfony.com/blog'; $content = file_get_contents($uri); $crawler = new Crawler($content, $uri);
  • 201. Enlaces del blog de symfony.com use SymfonyComponentDomCrawlerCrawler; $uri = 'http://symfony.com/blog'; $content = file_get_contents($uri); $crawler = new Crawler($content, $uri); $nodes = $crawler->filter('div.box_article a');
  • 203. Lleva a cabo tareas de validación
  • 204. Validando que un valor sea no nulo
  • 205. Validando que un valor sea no nulo use SymfonyComponentValidatorConstraintsNotNull;
  • 206. Validando que un valor sea no nulo use SymfonyComponentValidatorConstraintsNotNull; use SymfonyComponentValidatorConstraintsNotNullValidator;
  • 207. Validando que un valor sea no nulo use SymfonyComponentValidatorConstraintsNotNull; use SymfonyComponentValidatorConstraintsNotNullValidator; $validator = new NotNullValidator();
  • 208. Validando que un valor sea no nulo use SymfonyComponentValidatorConstraintsNotNull; use SymfonyComponentValidatorConstraintsNotNullValidator; $validator = new NotNullValidator(); if(!$validator->isValid(null, new NotNull()))
  • 209. Validando que un valor sea no nulo use SymfonyComponentValidatorConstraintsNotNull; use SymfonyComponentValidatorConstraintsNotNullValidator; $validator = new NotNullValidator(); if(!$validator->isValid(null, new NotNull())) {
  • 210. Validando que un valor sea no nulo use SymfonyComponentValidatorConstraintsNotNull; use SymfonyComponentValidatorConstraintsNotNullValidator; $validator = new NotNullValidator(); if(!$validator->isValid(null, new NotNull())) { print $validator->getMessageTemplate();
  • 211. Validando que un valor sea no nulo use SymfonyComponentValidatorConstraintsNotNull; use SymfonyComponentValidatorConstraintsNotNullValidator; $validator = new NotNullValidator(); if(!$validator->isValid(null, new NotNull())) { print $validator->getMessageTemplate(); // "The value should not be null"
  • 212. Validando que un valor sea no nulo use SymfonyComponentValidatorConstraintsNotNull; use SymfonyComponentValidatorConstraintsNotNullValidator; $validator = new NotNullValidator(); if(!$validator->isValid(null, new NotNull())) { print $validator->getMessageTemplate(); // "The value should not be null" }
  • 213. 24 Validadores Blank Max Date NotBlank Min Time Null Url DateTime NotNull Email Locale True IP Language False File Country Choice Image Collection Type Size Callback
  • 214. Usando la clase Validator
  • 215. Usando la clase Validator use SymfonyComponentValidatorValidator;
  • 216. Usando la clase Validator use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory;
  • 217. Usando la clase Validator use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory; use SymfonyComponentValidatorMappingBlackholeMetadataFactory;
  • 218. Usando la clase Validator use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory; use SymfonyComponentValidatorMappingBlackholeMetadataFactory; use SymfonyComponentValidatorConstraints as Asserts;
  • 219. Usando la clase Validator use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory; use SymfonyComponentValidatorMappingBlackholeMetadataFactory; use SymfonyComponentValidatorConstraints as Asserts; $validator = new Validator(
  • 220. Usando la clase Validator use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory; use SymfonyComponentValidatorMappingBlackholeMetadataFactory; use SymfonyComponentValidatorConstraints as Asserts; $validator = new Validator( new BlackholeMetadataFactory,
  • 221. Usando la clase Validator use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory; use SymfonyComponentValidatorMappingBlackholeMetadataFactory; use SymfonyComponentValidatorConstraints as Asserts; $validator = new Validator( new BlackholeMetadataFactory, new ConstraintValidatorFactory
  • 222. Usando la clase Validator use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory; use SymfonyComponentValidatorMappingBlackholeMetadataFactory; use SymfonyComponentValidatorConstraints as Asserts; $validator = new Validator( new BlackholeMetadataFactory, new ConstraintValidatorFactory );
  • 223. Usando la clase Validator use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory; use SymfonyComponentValidatorMappingBlackholeMetadataFactory; use SymfonyComponentValidatorConstraints as Asserts; $validator = new Validator( new BlackholeMetadataFactory, new ConstraintValidatorFactory ); $errors = $validator->validateValue('', new AssertsNotBlank());
  • 224. Usando la clase Validator use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory; use SymfonyComponentValidatorMappingBlackholeMetadataFactory; use SymfonyComponentValidatorConstraints as Asserts; $validator = new Validator( new BlackholeMetadataFactory, new ConstraintValidatorFactory ); $errors = $validator->validateValue('', new AssertsNotBlank()); if($errors->count())
  • 225. Usando la clase Validator use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory; use SymfonyComponentValidatorMappingBlackholeMetadataFactory; use SymfonyComponentValidatorConstraints as Asserts; $validator = new Validator( new BlackholeMetadataFactory, new ConstraintValidatorFactory ); $errors = $validator->validateValue('', new AssertsNotBlank()); if($errors->count()) {
  • 226. Usando la clase Validator use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory; use SymfonyComponentValidatorMappingBlackholeMetadataFactory; use SymfonyComponentValidatorConstraints as Asserts; $validator = new Validator( new BlackholeMetadataFactory, new ConstraintValidatorFactory ); $errors = $validator->validateValue('', new AssertsNotBlank()); if($errors->count()) { print $errors;
  • 227. Usando la clase Validator use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory; use SymfonyComponentValidatorMappingBlackholeMetadataFactory; use SymfonyComponentValidatorConstraints as Asserts; $validator = new Validator( new BlackholeMetadataFactory, new ConstraintValidatorFactory ); $errors = $validator->validateValue('', new AssertsNotBlank()); if($errors->count()) { print $errors; }
  • 228. Usando la clase Validator use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory; use SymfonyComponentValidatorMappingBlackholeMetadataFactory; use SymfonyComponentValidatorConstraints as Asserts; $validator = new Validator( new BlackholeMetadataFactory, new ConstraintValidatorFactory ); $errors = $validator->validateValue('', new AssertsNotBlank()); if($errors->count()) { print $errors; } ConstraintViolationList
  • 229. Validando un objeto (PHP) class Person { public $name; public $age; }
  • 230. Validando un objeto (PHP) class Person { public $name; public $age; } $name no puede ser una cadena vacía $age deberán ser un número comprendido entre 18 y 99 años
  • 232. Validando un objeto (PHP) use SymfonyComponentValidatorValidator;
  • 233. Validando un objeto (PHP) use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory;
  • 234. Validando un objeto (PHP) use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory; use SymfonyComponentValidatorMappingClassMetadataFactory;
  • 235. Validando un objeto (PHP) use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory; use SymfonyComponentValidatorMappingClassMetadataFactory; use SymfonyComponentValidatorMappingLoaderStaticMethodLoader;
  • 236. Validando un objeto (PHP) use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory; use SymfonyComponentValidatorMappingClassMetadataFactory; use SymfonyComponentValidatorMappingLoaderStaticMethodLoader; $validator = new Validator(
  • 237. Validando un objeto (PHP) use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory; use SymfonyComponentValidatorMappingClassMetadataFactory; use SymfonyComponentValidatorMappingLoaderStaticMethodLoader; $validator = new Validator( new ClassMetadataFactory(new StaticMethodLoader() ),
  • 238. Validando un objeto (PHP) use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory; use SymfonyComponentValidatorMappingClassMetadataFactory; use SymfonyComponentValidatorMappingLoaderStaticMethodLoader; $validator = new Validator( new ClassMetadataFactory(new StaticMethodLoader() ), new ConstraintValidatorFactory()
  • 239. Validando un objeto (PHP) use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory; use SymfonyComponentValidatorMappingClassMetadataFactory; use SymfonyComponentValidatorMappingLoaderStaticMethodLoader; $validator = new Validator( new ClassMetadataFactory(new StaticMethodLoader() ), new ConstraintValidatorFactory() );
  • 240. Validando un objeto (PHP) use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory; use SymfonyComponentValidatorMappingClassMetadataFactory; use SymfonyComponentValidatorMappingLoaderStaticMethodLoader; $validator = new Validator( new ClassMetadataFactory(new StaticMethodLoader() ), new ConstraintValidatorFactory() ); $person = new Person();
  • 241. Validando un objeto (PHP) use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory; use SymfonyComponentValidatorMappingClassMetadataFactory; use SymfonyComponentValidatorMappingLoaderStaticMethodLoader; $validator = new Validator( new ClassMetadataFactory(new StaticMethodLoader() ), new ConstraintValidatorFactory() ); $person = new Person(); $errors = $validator->validate($person);
  • 242. Validando un objeto (PHP) use SymfonyComponentValidatorMappingClassMetadata; use SymfonyComponentValidatorConstraint as Asserts; class Person { public $name; public $age; static function loadValidatorMetadata(ClassMetadata $metadata) { $metadata ->addPropertyConstraint('name', new AssertsNotBlank()) ->addPropertyConstraint('age' , new AssertsMin(18)); ->addPropertyConstraint('age' , new AssertsMax(99)); } }
  • 243. Validando un objeto (YAML) class Person { public $name; public $age; }
  • 244. Validando un objeto (YAML) class Person { public $name; public $age; } $name no puede ser una cadena vacía $age deberán ser un número comprendido entre 18 y 99 años
  • 245. Validando un objeto (YAML) # validate.yml Person: properties: name: - NotBlank : ~ age: - Min: 18 - Max: 99
  • 247. Validando un objeto (YAML) use SymfonyComponentValidatorValidator;
  • 248. Validando un objeto (YAML) use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory;
  • 249. Validando un objeto (YAML) use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory; use SymfonyComponentValidatorMappingClassMetadataFactory;
  • 250. Validando un objeto (YAML) use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory; use SymfonyComponentValidatorMappingClassMetadataFactory; use SymfonyComponentValidatorMappingLoaderYamlFileLoader;
  • 251. Validando un objeto (YAML) use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory; use SymfonyComponentValidatorMappingClassMetadataFactory; use SymfonyComponentValidatorMappingLoaderYamlFileLoader; $validator = new Validator(
  • 252. Validando un objeto (YAML) use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory; use SymfonyComponentValidatorMappingClassMetadataFactory; use SymfonyComponentValidatorMappingLoaderYamlFileLoader; $validator = new Validator( new ClassMetadataFactory(
  • 253. Validando un objeto (YAML) use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory; use SymfonyComponentValidatorMappingClassMetadataFactory; use SymfonyComponentValidatorMappingLoaderYamlFileLoader; $validator = new Validator( new ClassMetadataFactory( new YamlFileLoader(__DIR__.'/validate.yml')
  • 254. Validando un objeto (YAML) use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory; use SymfonyComponentValidatorMappingClassMetadataFactory; use SymfonyComponentValidatorMappingLoaderYamlFileLoader; $validator = new Validator( new ClassMetadataFactory( new YamlFileLoader(__DIR__.'/validate.yml') ),
  • 255. Validando un objeto (YAML) use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory; use SymfonyComponentValidatorMappingClassMetadataFactory; use SymfonyComponentValidatorMappingLoaderYamlFileLoader; $validator = new Validator( new ClassMetadataFactory( new YamlFileLoader(__DIR__.'/validate.yml') ), new ConstraintValidatorFactory()
  • 256. Validando un objeto (YAML) use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory; use SymfonyComponentValidatorMappingClassMetadataFactory; use SymfonyComponentValidatorMappingLoaderYamlFileLoader; $validator = new Validator( new ClassMetadataFactory( new YamlFileLoader(__DIR__.'/validate.yml') ), new ConstraintValidatorFactory() );
  • 257. Validando un objeto (YAML) use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory; use SymfonyComponentValidatorMappingClassMetadataFactory; use SymfonyComponentValidatorMappingLoaderYamlFileLoader; $validator = new Validator( new ClassMetadataFactory( new YamlFileLoader(__DIR__.'/validate.yml') ), new ConstraintValidatorFactory() ); $person = new Person();
  • 258. Validando un objeto (YAML) use SymfonyComponentValidatorValidator; use SymfonyComponentValidatorConstraintValidatorFactory; use SymfonyComponentValidatorMappingClassMetadataFactory; use SymfonyComponentValidatorMappingLoaderYamlFileLoader; $validator = new Validator( new ClassMetadataFactory( new YamlFileLoader(__DIR__.'/validate.yml') ), new ConstraintValidatorFactory() ); $person = new Person(); $errors = $validator->validate($person);
  • 260. Facilita la creación de tareas repetitivas
  • 261. La consola más sencilla
  • 262. La consola más sencilla // console.php
  • 263. La consola más sencilla // console.php use SymfonyComponentConsoleApplication;
  • 264. La consola más sencilla // console.php use SymfonyComponentConsoleApplication; $console = new Application();
  • 265. La consola más sencilla // console.php use SymfonyComponentConsoleApplication; $console = new Application(); $console->run();
  • 269. Hola mundo ... para consolas
  • 270. Hola mundo ... para consolas use SymfonyComponentConsoleApplication;
  • 271. Hola mundo ... para consolas use SymfonyComponentConsoleApplication; use SymfonyComponentConsoleInputInputArgument;
  • 272. Hola mundo ... para consolas use SymfonyComponentConsoleApplication; use SymfonyComponentConsoleInputInputArgument; $console = new Application();
  • 273. Hola mundo ... para consolas use SymfonyComponentConsoleApplication; use SymfonyComponentConsoleInputInputArgument; $console = new Application(); $console
  • 274. Hola mundo ... para consolas use SymfonyComponentConsoleApplication; use SymfonyComponentConsoleInputInputArgument; $console = new Application(); $console ->register('hello')
  • 275. Hola mundo ... para consolas use SymfonyComponentConsoleApplication; use SymfonyComponentConsoleInputInputArgument; $console = new Application(); $console ->register('hello') ->setDefinition(array(
  • 276. Hola mundo ... para consolas use SymfonyComponentConsoleApplication; use SymfonyComponentConsoleInputInputArgument; $console = new Application(); $console ->register('hello') ->setDefinition(array( new InputArgument('name', InputArgument::REQUIRED, 'Nombre'),
  • 277. Hola mundo ... para consolas use SymfonyComponentConsoleApplication; use SymfonyComponentConsoleInputInputArgument; $console = new Application(); $console ->register('hello') ->setDefinition(array( new InputArgument('name', InputArgument::REQUIRED, 'Nombre'), ))
  • 278. Hola mundo ... para consolas use SymfonyComponentConsoleApplication; use SymfonyComponentConsoleInputInputArgument; $console = new Application(); $console ->register('hello') ->setDefinition(array( new InputArgument('name', InputArgument::REQUIRED, 'Nombre'), )) ->setDescription('Saluda a una persona')
  • 279. Hola mundo ... para consolas use SymfonyComponentConsoleApplication; use SymfonyComponentConsoleInputInputArgument; $console = new Application(); $console ->register('hello') ->setDefinition(array( new InputArgument('name', InputArgument::REQUIRED, 'Nombre'), )) ->setDescription('Saluda a una persona') ->setCode(function ($input, $output) {
  • 280. Hola mundo ... para consolas use SymfonyComponentConsoleApplication; use SymfonyComponentConsoleInputInputArgument; $console = new Application(); $console ->register('hello') ->setDefinition(array( new InputArgument('name', InputArgument::REQUIRED, 'Nombre'), )) ->setDescription('Saluda a una persona') ->setCode(function ($input, $output) { $name = $input->getArgument('name');
  • 281. Hola mundo ... para consolas use SymfonyComponentConsoleApplication; use SymfonyComponentConsoleInputInputArgument; $console = new Application(); $console ->register('hello') ->setDefinition(array( new InputArgument('name', InputArgument::REQUIRED, 'Nombre'), )) ->setDescription('Saluda a una persona') ->setCode(function ($input, $output) { $name = $input->getArgument('name'); $output->writeln(sprintf('Hola <info>%s</info>', $name));
  • 282. Hola mundo ... para consolas use SymfonyComponentConsoleApplication; use SymfonyComponentConsoleInputInputArgument; $console = new Application(); $console ->register('hello') ->setDefinition(array( new InputArgument('name', InputArgument::REQUIRED, 'Nombre'), )) ->setDescription('Saluda a una persona') ->setCode(function ($input, $output) { $name = $input->getArgument('name'); $output->writeln(sprintf('Hola <info>%s</info>', $name)); })
  • 283. Hola mundo ... para consolas use SymfonyComponentConsoleApplication; use SymfonyComponentConsoleInputInputArgument; $console = new Application(); $console ->register('hello') ->setDefinition(array( new InputArgument('name', InputArgument::REQUIRED, 'Nombre'), )) ->setDescription('Saluda a una persona') ->setCode(function ($input, $output) { $name = $input->getArgument('name'); $output->writeln(sprintf('Hola <info>%s</info>', $name)); }) ;
  • 284. Hola mundo ... para consolas use SymfonyComponentConsoleApplication; use SymfonyComponentConsoleInputInputArgument; $console = new Application(); $console ->register('hello') ->setDefinition(array( new InputArgument('name', InputArgument::REQUIRED, 'Nombre'), )) ->setDescription('Saluda a una persona') ->setCode(function ($input, $output) { $name = $input->getArgument('name'); $output->writeln(sprintf('Hola <info>%s</info>', $name)); }) ; $console->run();
  • 285. Hay una manera mejor de hacerlo, Command
  • 286. Creando un nuevo comando
  • 287. Creando un nuevo comando use SymfonyComponentConsoleCommandCommand;
  • 288. Creando un nuevo comando use SymfonyComponentConsoleCommandCommand; use SymfonyComponentConsoleInputInputArgument;
  • 289. Creando un nuevo comando use SymfonyComponentConsoleCommandCommand; use SymfonyComponentConsoleInputInputArgument; class HelloCommand extends Command
  • 290. Creando un nuevo comando use SymfonyComponentConsoleCommandCommand; use SymfonyComponentConsoleInputInputArgument; class HelloCommand extends Command {
  • 291. Creando un nuevo comando use SymfonyComponentConsoleCommandCommand; use SymfonyComponentConsoleInputInputArgument; class HelloCommand extends Command { public function configure()
  • 292. Creando un nuevo comando use SymfonyComponentConsoleCommandCommand; use SymfonyComponentConsoleInputInputArgument; class HelloCommand extends Command { public function configure() {
  • 293. Creando un nuevo comando use SymfonyComponentConsoleCommandCommand; use SymfonyComponentConsoleInputInputArgument; class HelloCommand extends Command { public function configure() { $this->setName('hello');
  • 294. Creando un nuevo comando use SymfonyComponentConsoleCommandCommand; use SymfonyComponentConsoleInputInputArgument; class HelloCommand extends Command { public function configure() { $this->setName('hello'); $this->setDefinition(array(
  • 295. Creando un nuevo comando use SymfonyComponentConsoleCommandCommand; use SymfonyComponentConsoleInputInputArgument; class HelloCommand extends Command { public function configure() { $this->setName('hello'); $this->setDefinition(array( new InputArgument('name', InputArgument::REQUIRED, 'Nombre'),
  • 296. Creando un nuevo comando use SymfonyComponentConsoleCommandCommand; use SymfonyComponentConsoleInputInputArgument; class HelloCommand extends Command { public function configure() { $this->setName('hello'); $this->setDefinition(array( new InputArgument('name', InputArgument::REQUIRED, 'Nombre'), ))
  • 297. Creando un nuevo comando use SymfonyComponentConsoleCommandCommand; use SymfonyComponentConsoleInputInputArgument; class HelloCommand extends Command { public function configure() { $this->setName('hello'); $this->setDefinition(array( new InputArgument('name', InputArgument::REQUIRED, 'Nombre'), )) $this->setDescription('Saluda a una persona')
  • 298. Creando un nuevo comando use SymfonyComponentConsoleCommandCommand; use SymfonyComponentConsoleInputInputArgument; class HelloCommand extends Command { public function configure() { $this->setName('hello'); $this->setDefinition(array( new InputArgument('name', InputArgument::REQUIRED, 'Nombre'), )) $this->setDescription('Saluda a una persona') }
  • 299. Creando un nuevo comando use SymfonyComponentConsoleCommandCommand; use SymfonyComponentConsoleInputInputArgument; class HelloCommand extends Command { public function configure() { $this->setName('hello'); $this->setDefinition(array( new InputArgument('name', InputArgument::REQUIRED, 'Nombre'), )) $this->setDescription('Saluda a una persona') } public function execute($input, $output)
  • 300. Creando un nuevo comando use SymfonyComponentConsoleCommandCommand; use SymfonyComponentConsoleInputInputArgument; class HelloCommand extends Command { public function configure() { $this->setName('hello'); $this->setDefinition(array( new InputArgument('name', InputArgument::REQUIRED, 'Nombre'), )) $this->setDescription('Saluda a una persona') } public function execute($input, $output) {
  • 301. Creando un nuevo comando use SymfonyComponentConsoleCommandCommand; use SymfonyComponentConsoleInputInputArgument; class HelloCommand extends Command { public function configure() { $this->setName('hello'); $this->setDefinition(array( new InputArgument('name', InputArgument::REQUIRED, 'Nombre'), )) $this->setDescription('Saluda a una persona') } public function execute($input, $output) { $name = $input->getArgument('name');
  • 302. Creando un nuevo comando use SymfonyComponentConsoleCommandCommand; use SymfonyComponentConsoleInputInputArgument; class HelloCommand extends Command { public function configure() { $this->setName('hello'); $this->setDefinition(array( new InputArgument('name', InputArgument::REQUIRED, 'Nombre'), )) $this->setDescription('Saluda a una persona') } public function execute($input, $output) { $name = $input->getArgument('name'); $output->writeln(sprintf('Hola <info>%s</info>', $name));
  • 303. Creando un nuevo comando use SymfonyComponentConsoleCommandCommand; use SymfonyComponentConsoleInputInputArgument; class HelloCommand extends Command { public function configure() { $this->setName('hello'); $this->setDefinition(array( new InputArgument('name', InputArgument::REQUIRED, 'Nombre'), )) $this->setDescription('Saluda a una persona') } public function execute($input, $output) { $name = $input->getArgument('name'); $output->writeln(sprintf('Hola <info>%s</info>', $name)); }
  • 304. Creando un nuevo comando use SymfonyComponentConsoleCommandCommand; use SymfonyComponentConsoleInputInputArgument; class HelloCommand extends Command { public function configure() { $this->setName('hello'); $this->setDefinition(array( new InputArgument('name', InputArgument::REQUIRED, 'Nombre'), )) $this->setDescription('Saluda a una persona') } public function execute($input, $output) { $name = $input->getArgument('name'); $output->writeln(sprintf('Hola <info>%s</info>', $name)); } }
  • 305. Creando un nuevo comando
  • 306. Creando un nuevo comando use SymfonyComponentConsoleApplication;
  • 307. Creando un nuevo comando use SymfonyComponentConsoleApplication; $console = new Application();
  • 308. Creando un nuevo comando use SymfonyComponentConsoleApplication; $console = new Application(); $console->add(new HelloCommand());
  • 309. Creando un nuevo comando use SymfonyComponentConsoleApplication; $console = new Application(); $console->add(new HelloCommand()); $console->run();
  • 310. Gracias @loalf Créditos: http://www.flickr.com/photos/normalityrelief/3075723695/

Notas del editor

  1. En esta primera charla del d&amp;#xED;a me gustar&amp;#xED;a cumplir dos objetivos\n1. Instalar y configurar el framework\n2. (M&amp;#xE1;s importante) Entender qu&amp;#xE9; es symfony y todo lo que lo rodea\n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n
  53. \n
  54. \n
  55. \n
  56. \n
  57. \n
  58. \n
  59. \n
  60. \n
  61. \n
  62. \n
  63. \n
  64. \n
  65. \n
  66. \n
  67. \n
  68. \n
  69. \n
  70. \n
  71. \n
  72. \n
  73. \n
  74. \n
  75. \n
  76. \n
  77. \n
  78. \n
  79. \n
  80. \n
  81. \n
  82. \n
  83. \n
  84. \n
  85. \n
  86. \n
  87. \n
  88. \n
  89. \n
  90. \n
  91. \n
  92. \n
  93. \n
  94. \n
  95. \n
  96. \n
  97. \n
  98. \n
  99. \n
  100. \n
  101. \n
  102. \n
  103. \n
  104. \n
  105. \n
  106. \n
  107. \n
  108. \n
  109. \n
  110. \n
  111. \n
  112. \n
  113. \n
  114. \n
  115. \n
  116. \n
  117. \n
  118. \n
  119. \n
  120. \n
  121. \n
  122. \n
  123. \n
  124. \n
  125. \n
  126. \n
  127. \n
  128. \n
  129. \n
  130. \n
  131. \n
  132. \n
  133. \n
  134. \n
  135. \n
  136. \n
  137. \n
  138. \n
  139. \n
  140. \n
  141. \n
  142. \n
  143. \n
  144. \n
  145. \n
  146. \n
  147. \n
  148. \n
  149. \n
  150. \n
  151. \n
  152. \n
  153. \n
  154. \n
  155. \n
  156. \n
  157. \n
  158. \n
  159. \n
  160. \n
  161. \n
  162. \n
  163. \n
  164. \n
  165. \n
  166. \n
  167. \n
  168. \n
  169. \n
  170. \n
  171. \n
  172. \n
  173. \n
  174. \n
  175. \n
  176. \n
  177. \n
  178. \n
  179. \n
  180. \n
  181. \n
  182. \n
  183. \n
  184. \n
  185. \n
  186. \n
  187. \n
  188. \n
  189. \n
  190. \n
  191. \n
  192. \n
  193. \n
  194. \n
  195. \n
  196. \n
  197. \n
  198. \n
  199. \n
  200. \n
  201. \n
  202. \n
  203. \n
  204. \n
  205. \n
  206. \n
  207. \n
  208. \n
  209. \n
  210. \n
  211. \n
  212. \n
  213. \n
  214. \n
  215. \n
  216. \n
  217. \n
  218. \n
  219. \n
  220. \n
  221. \n
  222. \n
  223. \n
  224. \n
  225. \n
  226. \n
  227. \n
  228. \n
  229. \n
  230. \n
  231. \n
  232. \n
  233. \n
  234. \n
  235. \n
  236. \n
  237. \n
  238. \n
  239. \n
  240. \n
  241. \n
  242. \n
  243. \n
  244. \n
  245. \n
  246. \n
  247. \n
  248. \n
  249. \n
  250. \n
  251. \n
  252. \n
  253. \n
  254. \n
  255. \n
  256. \n
  257. \n
  258. \n
  259. \n
  260. \n
  261. \n
  262. \n
  263. \n
  264. \n
  265. \n
  266. \n
  267. \n
  268. \n
  269. \n
  270. \n
  271. \n
  272. \n
  273. \n
  274. \n
  275. \n
  276. \n
  277. \n
  278. \n
  279. \n
  280. \n
  281. \n
  282. \n
  283. \n
  284. \n
  285. \n
  286. \n
  287. \n
  288. \n
  289. \n
  290. \n
  291. \n
  292. \n
  293. \n
  294. \n
  295. \n
  296. \n
  297. \n
  298. \n
  299. \n
  300. \n
  301. \n
  302. \n
  303. \n
  304. \n
  305. \n
  306. \n
  307. \n
  308. \n
  309. \n
  310. \n
  311. \n
  312. \n
  313. \n
  314. \n
  315. \n
  316. \n
  317. \n
  318. \n
  319. \n
  320. \n
  321. \n
  322. \n
  323. \n
  324. \n
  325. \n
  326. \n
  327. \n
  328. \n