Partage
  • Partager sur Facebook
  • Partager sur Twitter

[sf2]visualiser des images et des vidéos

Sujet résolu
    21 août 2012 à 11:20:03

    Bonjour,

    J'aurais voulu avoir votre avis, comment peut on visualiser les images et le videos uploadé sous symfony2.

    Concrètement faut écrire du code PHP5 pour cela en respectant la séparation MVC !!

    Vous me conseillez d'écrire le code dans le modèle (entité) ou dans Repository de l'entité ou le faire directement dans le contrôleur ?

    Je n'ai aucune idée comment commencer !! avez vous des tutos ?

    Merci pour votre aide
    • Partager sur Facebook
    • Partager sur Twitter
      21 août 2012 à 11:43:24

      Salut !

      L'entité n'est pas le bon endroit, car elle ne doit que stocker des informations et éventuellement faire de menus calculs (l'âge depuis la date de naissance, par exemple). Le controller ne fait que récupérer les données et les envoyer au client. Pour moi, c'est le travail de la vue de formater ces données. Pour ma part, j'ai fait des fonctions qui rendent l'objet sous forme de code HTML, en prenant ses propriétés.

      Un petit instant, je te fournis mon code pour traiter des images, tu pourras t'en inspirer.

      Je ne connaissais pas le principe des extensions de types de formulaire, à l'époque. C'est bien plus propre, je vous conseille d'aller regarder ça ;)
      <?php
      
      namespace YSoft\MediaBundle\Service;
      
      use Symfony\Component\HttpFoundation\File\Exception\UnexpectedTypeException;
      
      class YSoftMediaTwigExtension extends \Twig_Extension
      {
      
          public function getFunctions()
          {
              return array(
                  'html_file'         => new \Twig_Function_Method($this, 'renderFile'),
                  'html_image'        => new \Twig_Function_Method($this, 'renderImage'),
              );
          }
      
          public function getName()
          {
              return 'ysoft_media.html.helper';
          }
      
          /**
           * Render a file as HTML
           *
           * @param string|YSoft\MediaBundle\Entity\File $file
           *  The path to the file, relative to the website root, or the file object
           *  itself
           * @param array $options
           *  An array of additionnal parameters or values to infer those given in
           *  the object/with the first parameter.
           * @throws \UnexpectedTypeException
           * @throws \InvalidArgumentException
           * @return string
           */
          public function renderFile($file, array $options = array())
          {
              $href = NULL;
              // Checking type of first parameter
              if ($file instanceof \YSoft\MediaBundle\Entity\File) {
                  $href = (string) $file;    
              } else if (is_string($file)) {
                  $href = $file;
              } else {
                  throw new UnexpectedTypeException($file, 'YSoft\MediaBundle\Entity\File or String');
              }
              if ($href == NULL)
                  throw new \InvalidArgumentException(
                      'First argument must not be empty'
                  );
      
              $attributes = '';
              /* Looping on the options given. mainly, the options are
               * attribute_name => value pairs, but those that infers on the default
               * ones must be treated somehow else */ 
              foreach ($options as $name => $value) {
                  if (preg_match('`^&`', $name) || preg_match('`&$`', $name))
                      continue;
                  $attributes .= ' ' . $name . '="';
                  if (is_array($value)) {
                      $attributes .= implode($value, ' ');
                  } else {
                      $attributes .= $value;
                  }
                  $attributes .= $value . '"';
              }
      
              // Handling the extension and extension inference
              if (isset($options['&ext'])) {
                  $ext = strrchr($href, '.');
                  $start = substr($href, 0, -strlen($ext));
                  $href = $start . $options['&ext'] . $ext;
              }
              /* We retrieve the file name this way, as we can handle both object
               * and string given in two lines without test */ 
              $temp = strrchr($src, '/');
              $file_name = substr($src, $temp + 1);
      
              $html = '<a href="'
              . (isset($options['&href']) ? $options['&href'] : '') . $href
              . (isset($options['href&']) ? $options['href&'] : '')
              . $attributes . '>' . $file_name . '</a>';
      
              return $html;
          }
      
          /**
           * Render an image as HTML
           *
           * @param string|YSoft\MediaBundle\Entity\Picture $picture
           *  The path to the picture, relative to the website root, or the picture
           *  object itself
           * @param array $options
           * @throws \UnexpectedTypeException
           * @throws \InvalidArgumentException
           * @return string
           */
          public function renderImage($picture, array $options = array())
          {
              $src = NULL;
              $html = '';
              // Checking type of first parameter
              if ($picture instanceof \YSoft\MediaBundle\Entity\Picture) {
                  $src = (string) $picture;
                  if ($temp = $picture->getPictureTitle())
                      $options['title'] = $temp;
                  if ($temp = $picture->getAlt())
                      $options['alt'] = $temp;
              } else if (is_string($picture)) {
                  $src = $picture;
              } else {
                  throw new UnexpectedTypeException($picture, 'YSoft\MediaBundle\Entity\Picture or string');
              }
              if ($src == NULL)
                  throw new \InvalidArgumentException(
                      'First argument must not be empty'
                  );
      
              /* Shorthand fot two options at once, the type is to be handled
               * separately. To avoit code duplication, the class and &ext options
               * are set and then handled as in renderFile */  
              if (isset($options['type'])) {
                  if (isset($options['class'])) {
                      if (is_array($options['class']))
                          $options['class'][] = $options['type'];
                      else if (is_string($options['class']))
                          $options['class'] .= ' ' . $options['type'];
                  } else {
                      $options['class'] = $options['type'];
                  }
                  if (!strstr($src, \YSoft\MediaBundle\Entity\Picture::UPLOAD_DIR))
                      $options['&ext'] = '_' . $options['type'];
                  unset($options['type']);
              }
              // Handling the extension and extension inference
              if (isset($options['&ext'])) {
                  $ext = strrchr($src, '.');
                  $start = substr($src, 0, -strlen($ext));
                  $src = $start . $options['&ext'] . $ext;
                  unset($options['&ext']);
              }
      
              $attributes = '';
              /* Looping on the options given. mainly, the options are
               * attribute_name => value pairs, but those that infers on the default
               * ones must be treated somehow else */
              foreach ($options as $name => $value) {
                  if (preg_match('`^&`', $name)
                          || preg_match('`&$`', $name)
                          || ($name == 'alt')
                          || ($name == 'title'))
                      continue;
                  $attributes .= ' ' . $name . '="';
                  if (is_array($value)) {
                      $attributes .= implode($value, ' ');
                  } else {
                      $attributes .= $value;
                  }
                  $attributes .= '"';
              }
      
              $html .= '<img src="'
                  . (isset($options['&src']) ? $options['&src'] : '') . $src
                  . (isset($options['src&']) ? $options['src&'] : '')
                  . '" alt="' . (isset($options['alt'])
                          ? (isset($options['&alt']) ? $options['&alt'] : '')
                                  . $options['alt']
                                  . (isset($options['alt&']) ? $options['alt&'] : '')
                          : NULL)
                  . '" title="' . (isset($options['title'])
                          ? (isset($options['&title']) ? $options['&title'] : '')
                              . $options['title']
                              . (isset($options['title&']) ? $options['title&'] : '')
                          : NULL)
                  . '"' . $attributes . ' />';
      
              return $html;
          }
      }
      

      <?php
      
      namespace YSoft\MediaBundle\Entity;
      
      use Symfony\Component\HttpFoundation\File\UploadedFile;
      
      /**
       * YSoft\MediaBundle\Entity\Picture
       */
      class Picture extends File
      {
          /**
           * The directory where to upload the pictures
           */
          const UPLOAD_DIR = '/pictures';
      
          /**
           * Default extension for files for which the framework
           * can't guess it
           */
          const DEFAULT_EXTENSION = 'jpg';
      
          /**
           * @var integer $id
           */
          protected $id;
      
          /**
           * @var text $alt
           */
          protected $alt;
      
          /**
           * @var text $picture_title
           */
          protected $picture_title;
      
          /**
           * !Not a persisted property!
           * @var string $locale
           */
          protected $locale;
      
          /**
           * Get file name
           *
           * @param type
           * @return text
           */
          public function getFileName($type = NULL)
          {
              if (($type !== NULL) && $this->file_path) {
                  $ext = strrchr($this->file_name, '.');
                  $start = substr($this->file_name, 0, -strlen($ext));
                  return $start . '_' . $type . $ext;
              } else {
                  return $this->file_name;
              }
          }
      
          /**
           * Set alt
           *
           * @param text $alt
           */
          public function setAlt($alt)
          {
              $this->alt = $alt;
          }
      
          /**
           * Get alt
           *
           * @return text
           */
          public function getAlt()
          {
              return $this->alt;
          }
      
          /**
           * Set picture title
           *
           * @param text $pictureTitle
           */
          public function setPictureTitle($pictureTitle)
          {
              $this->picture_title = $pictureTitle;
          }
      
          /**
           * Get picture title
           *
           * @return text
           */
          public function getPictureTitle()
          {
              return $this->picture_title;
          }
      
          /**
           * Sets the locale for current object
           *
           * @param string $locale
           */
          public function setLocale($locale)
          {
              $this->locale = $locale;
          }
      
          /* (non-PHPdoc)
           * @see YSoft\MediaBundle\Entity.File::getDefaultFileName()
           */
          /**
           * {@inheritdoc}
           */
          protected function getDefaultFileName($extension = self::DEFAULT_EXTENSION)
          {
              return 'picture_' . uniqid() . '.' . $extension; 
          }
      }
      

      <?php
      
      namespace YSoft\MediaBundle\Entity;
      
      use Doctrine\ORM\Event\LifecycleEventArgs;
      
      use Symfony\Component\HttpFoundation\File\UploadedFile;
      
      /**
       * YSoft\MediaBundle\Entity\Picture
       */
      class File
      {
          /**
           * The base folder where where to store uploads
           * @var string
           */
          const ROOT_UPLOAD_DIR = '/web';
      
          /**
           * The directory where to upload the files
           * @var string
           */
          const UPLOAD_DIR = '/files';
      
          /**
           * Default extension for files for which the framework
           * can't guess it
           * @var string
           */
          const DEFAULT_EXTENSION = 'bin';
      
          /**
           * @var integer $id
           */
          protected $id;
      
          /**
           * !Not a persisted property!
           * @var UploadedFile $file
           */
          protected $file;
      
          /**
           * @var text $filename
           */
          protected $file_name;
      
          /**
           * @var text $filepath
           */
          protected $file_path;
      
      
          /**
           * Get id
           *
           * @return integer
           */
          public function getId()
          {
              return $this->id;
          }
      
          /**
           * Set file
           *
           * @var Symfony\Component\HttpFoundation\File\UploadedFile $file
           */
          public function setFile($file)
          {
              $this->file = $file;
          }
      
          /**
           * Get file
           *
           * @return Symfony\Component\HttpFoundation\File\UploadedFile
           */
          public function getFile()
          {
              /* Note that the file is taken relatively to the web root. The initial
               * slash for the path of the picture is to be removed, else the server
               * will return a 500 error */
              return (($this->file_path == NULL) && ($this->file_name != NULL)
                      ? new UploadedFile(
                              $this->getUploadRootDir() . '/' . $this->file_name,
                              $this->file_name)
                      : NULL);
          }
      
          /**
           * Set file name
           *
           * @param text $filename
           */
          public function setFileName($fileName)
          {
              /*if ($ext = strrchr($fileName, '.'))
                  $this->file_name = substr($fileName, 0, -strlen($ext));
              else*/
                  $this->file_name = $fileName;
          }
      
          /**
           * Get file name
           *
           * @return text
           */
          public function getFileName()
          {
              return $this->file_name;
          }
      
          /**
           * Set file path
           *
           * @param text $filepath
           */
          public function setFilePath($filePath)
          {
              $this->file_path = $filePath;
          }
      
          /**
           * Get file path
           *
           * @return text
           */
          public function getFilePath()
          {
              return $this->file_path;
          }
      
          /**
           * The string representation for the entity
           *
           * @return text
           */
          public function __toString() {
              $class = get_called_class();
              return ($this->file_path
                      ? $this->file_path
                      : ($class::UPLOAD_DIR . '/')) . $this->file_name;
          }
      
          /**
           * The string representation for a URN.
           * This is similar to __toString, but you can give it the type of the
           * picture you want to display
           *
           * @param string $type
           * @return string
           */
          public function getURN($type = null)
          {
              $class = get_called_class();
              return ($this->file_path
                      ? $this->file_path
                      : ($class::UPLOAD_DIR . '/')) . $this->getFileName($type);
          }
      
          // Functions adapted from http://symfony.com/doc/2.0/cookbook/doctrine/file_uploads.html#basic-setup
          public function getAbsolutePath()
          {
              return ($this->file_path === NULL ? $this->getUploadRootDir() . '/' : $this->file_path) . $this->file_name;
          }
      
          protected function getUploadRootDir()
          {
              // the absolute directory path where uploaded documents should be saved
              $class = get_called_class();
              return __DIR__ . '/../../../..' . self::ROOT_UPLOAD_DIR . $class::UPLOAD_DIR;
          }
      
          /**
           * Computes a default name 
           * @param string $extension
           * @return string
           */
          protected function getDefaultFileName($extension)
          {
              $class = get_called_class();
              return uniqid() . '.' . ($extension
                      ? $extension
                      : $class::DEFAULT_EXTENSION); 
          }
      
          /**
           * Sets the file name, needed to store the file when not using transloadit
           * @ORM\prePersist
           * @ORM\preUpdate
           */
          public function preUpload()
          {
              if ($this->file !== NULL) {
                  $extension = $this->file->guessExtension();
                  if ($this->file_name == NULL)
                      $this->setFilename($this->getDefaultFileName($extension));
              }
          }
      
          /**
           * Handles the eventual upload of the file.
           * If we have no file, the file_path and file_name are set by transloadit.
           * Else, the  file_path must be set to '' (empty string) and the name
           * generated if not given
           * @ORM\postPersist
           * @ORM\postUpdate
           */
          public function upload()
          {
              if ($this->file === NULL) {
                  return;
              }
      
              /* You must throw an exception here if the file cannot be moved – so
               * that the entity is not persisted to the database – which the
               * UploadedFile::move() method does automatically */
              $class = get_called_class();
              $this->file
                      ->move($this->getUploadRootDir(),
                              $class::UPLOAD_DIR . '/' . $this->file_name);
              $this->file_path = '';
              unset($this->file);
          }
      
          /**
           * Remove the file from the server if it was hosted on it.
           * The commented out parts are suspected to work with Symfony>2.1
           * @ORM\PreRemove()
           * @ORM\PostRemove()
           */
          public function removeUpload(/*LifecycleEventArgs $eventArgs*/)
          {
              /*$self = $eventArgs->getEntity();
              if ($self->file_path) {
                  unlink($self->getAbsolutePath());
              }*/
              if ($this->file_path) {
                  unlink($this->getAbsolutePath());
              }
          }
      }
      

      Ah, et il faut déclarer YSoftMediaBundleTwigExtension comme un service
      twig.extension.ysoft_media.helper:
              class: %ysoft_media.twig.helper.class%
              tags:
                  - { name: twig.extension, alias: ysoft_media.html.helper }
      

      Après quoi, dans tes vues, tu fais {{ html_image(myImage)|raw }}, et c'est bon.

      -
      Edité par Ymox 14 juin 2013 à 8:06:15

      • Partager sur Facebook
      • Partager sur Twitter
        21 août 2012 à 13:58:00

        Merci il est intéressant le code de ton bundle ! merci bcp !!



        J'ai réussi à reprendre ton code suivent ce que je veux, mais j'ai déclarer le service dans : /Resources/config/services.yml j'ai cette erreur :

        ParameterNotFoundException: The service "twig.extension.app_river.helper" has a dependency on a non-existent parameter "suisse_river.twig.helper.class".

        Peux tu m'aider !!
        • Partager sur Facebook
        • Partager sur Twitter
          8 septembre 2012 à 14:36:34

          A mettre en lien avec ce sujet

          -
          Edité par Ymox 1 avril 2013 à 15:33:37

          • Partager sur Facebook
          • Partager sur Twitter

          [sf2]visualiser des images et des vidéos

          × Après avoir cliqué sur "Répondre" vous serez invité à vous connecter pour que votre message soit publié.
          × Attention, ce sujet est très ancien. Le déterrer n'est pas forcément approprié. Nous te conseillons de créer un nouveau sujet pour poser ta question.
          • Editeur
          • Markdown