Foros del Web » Programando para Internet » PHP » Frameworks y PHP orientado a objetos »

[SOLUCIONADO] Como logro esto en php [Class]

Estas en el tema de Como logro esto en php [Class] en el foro de Frameworks y PHP orientado a objetos en Foros del Web. hola vi que en PDO se podia llamar a metodos de esta forma: @import url("http://static.forosdelweb.com/clientscript/vbulletin_css/geshi.css"); Código PHP: Ver original # Query         ...
  #1 (permalink)  
Antiguo 15/03/2013, 00:40
 
Fecha de Ingreso: septiembre-2012
Ubicación: Buenos aires
Mensajes: 110
Antigüedad: 11 años, 6 meses
Puntos: 9
Pregunta Como logro esto en php [Class]

hola vi que en PDO se podia llamar a metodos de esta forma:

Código PHP:
Ver original
  1. # Query
  2.             $Query  = $this->_db->query("SELECT * FROM Eventos ORDER BY id DESC LIMIT 3");
  3.            
  4.             return $Query->fetch();

lo que me imagino que se puede hacer asi:

Código PHP:
Ver original
  1. return  $this->_db->query("SELECT * FROM Eventos ORDER BY id DESC LIMIT 3")->fetch();

estoy queriendo hacer una clase donde puedas definir los thumbs de esta forma:

Código PHP:
Ver original
  1. $thumbs = new thumbs($name);
  2. $thumbs->generate()->width(1000);
  3. $thumbs->generate()->height(200);
  4. $thumbs->generate()->auto(300);
  5. $thumbs->generate()->height(400)->width(200);
esto es posible? como se logra?
  #2 (permalink)  
Antiguo 15/03/2013, 01:25
 
Fecha de Ingreso: septiembre-2011
Mensajes: 219
Antigüedad: 12 años, 7 meses
Puntos: 31
Respuesta: Como logro esto en php [Class]

Se denomina encadenar metodos, podes buscarlo en google o tomar este codigo como referencia, no es funcional porque obviamente le faltan cosas para generar un thumb y algunas validaciones, pero te sirve para entender como encadenar. El secreto esta en "return $this;"

Y por si a alguien no le queda, es un mero ejemplo, no es algo funcional. Es para ilustrar la idea.

Código PHP:
Ver original
  1. <?php
  2.  
  3. Class Thumbs{
  4.  
  5.     private $path;
  6.     private $width = 50;
  7.     private $height = 50;
  8.  
  9.     /**
  10.      *
  11.      */
  12.     function __construct($path = null){
  13.         if(isset($path)){
  14.             $this->thumb = $path;
  15.         }
  16.     }
  17.  
  18.     /**
  19.      *
  20.      */
  21.     public function width($w = null){
  22.         $this->width = $w;
  23.         return $this;
  24.     }
  25.  
  26.     /**
  27.      *
  28.      */
  29.     public function height($h = null){
  30.         $this->height = $h;
  31.         return $this;
  32.     }
  33.  
  34.  
  35.     /**
  36.      *
  37.      */
  38.     public function generate($file){
  39.         $w = $this->width;
  40.         $h = $this->height;
  41.         $path = $this->path;
  42.         $file = $this->file;
  43.  
  44.         /*
  45.         * codigo para generar el thumb
  46.         * con las medidas generadas a
  47.         * travez de encadenamiento
  48.         */
  49.  
  50.         return $something;
  51.     }
  52.  
  53. }
  54.  
  55. ?>

Con una clase así, podes hacer lo siguiente:

Código PHP:
Ver original
  1. $thumb = new Thumbs('imagen.jpg'); // inicio la clase
  2. // reescribo todos los parametros
  3. $procesada = $thumb->width(150)->height(150)->generate('mi_nuevo_thumb.jpg');
  4. // o dejando los valores por defecto
  5. $procesada = $thumb->generate('mi_nuevo_thumb.jpg');

Espero te sirva como base para que lo deseas hacer.
Saludos.
  #3 (permalink)  
Antiguo 15/03/2013, 10:58
 
Fecha de Ingreso: septiembre-2012
Ubicación: Buenos aires
Mensajes: 110
Antigüedad: 11 años, 6 meses
Puntos: 9
Respuesta: Como logro esto en php [Class]

Buenisimo!! muchas gracias :D
  #4 (permalink)  
Antiguo 15/03/2013, 22:27
 
Fecha de Ingreso: septiembre-2012
Ubicación: Buenos aires
Mensajes: 110
Antigüedad: 11 años, 6 meses
Puntos: 9
Respuesta: Como logro esto en php [Class]

Implemente lo que me dijiste, pero [no se si sera por esto.] me da un error con la carpeta a donde iria el thumbnail, retorne la url de la carpeta destino y es perfecta a lo que no entiendo por que no se podria guardar...

La clase:
-----------
<?
class Thumbnails{

# Forma de uso
# $thumb = new Thumbnails($file);
# $thumb->width($size)->height($size)->generate($path);
# $thumb->width($size)->generate($path);
# $thumb->height($size)->generate($path);
# $thumb->auto($size)->generate($path);

// ----- Variables -----
private $types = 'jpg,jpeg,png,gif,wbmp';
private $thumb = NULL;
private $error = NULL;

// ----- Constructor -----
public function __construct($file){

# Asignaciones
$this->thumb = array();

# Inicializar
$this->init($file);

}


// ----- Inicializador -----
private function init($file){

# Detectando formato.
$Type = explode('.',$file);
$this->thumb['type'] = strtolower(end($Type));

# Creando imagen segun formato.
if($this->thumb['type']=='jpg' || $this->thumb['type']=='jpeg'){

# Asignando
$this->thumb['type'] = 'jpeg';
$this->thumb['src'] = ImageCreateFromJPEG($file);

}elseif($this->thumb['type']=='png'){

# Creando imagen.
$this->thumb['src'] = ImageCreateFromPNG($file);

}elseif($this->thumb['type']=='gif'){

# Creando imagen.
$this->thumb['src'] = ImageCreateFromGIF($file);

}elseif($this->thumb['type']=='wbmp'){

# Creando imagen.
$this->thumb['src'] = ImageCreateFromWBMP($file);

}else{

# Informe de error
$this->error = 'El formato no es soportada.';

}

# Asignando tamaños.
$this->thumb['size_w'] = imagesx($this->thumb['src']);
$this->thumb['size_h'] = imagesy($this->thumb['src']);

# Asignando calidad.
$this->thumb['quality'] = 100;

}

// ----- Height -----
public function height($size=98){

# Alto
$this->thumb['thumb_h'] = $size;

# Ancho
@$this->thumb['thumb_w'] = ( $this->thumb['thumb_h'] / $this->thumb['size_h'] ) * $this->thumb['size_w'];

# Encadenamiento medoto.
return $this;
}

// ----- Width -----
public function width($size=98){

# Ancho.
$this->thumb['thumb_w'] = $size;

# Alto.
@$this->thumb["thumb_h"] = ($this->thumb["thumb_w"]/$this->thumb["size_w"])*$this->thumb["size_h"];

# Return this
return $this;

}

// ----- Automatico -----
public function auto($size=98){

# Si la imagen es más ancha que larga.
if($this->thumb['size_w'] >= $this->thumb['size_h']){

# Ancho.
$this->thumb['thumb_w'] = $size;

# Alto.
@$this->thumb["thumb_h"] = ($this->thumb["thumb_w"]/$this->thumb["size_w"])*$this->thumb["size_h"];

}else{

# Alto
$this->thumb['thumb_h'] = $size;

# Ancho
@$this->thumb['thumb_w'] = ( $this->thumb['thumb_h'] / $this->thumb['size_h'] ) * $this->thumb['size_w'];

}

# Encadena metodos
return $this;

}

// ----- Calidad -----
public function quality($quality = 100){

# Calidad.
$this->thumb['quality'] = $quality;

# Encadenar metodo
return $this;

}

// ----- Generate -----
public function generate($path = '/'){

# Carpeta.
if(!is_writable($path)){

#$this->error = 'No se puede guardar la imagen en esta locacion.';
$this->error = '<a href="'.$path.'">ruta</a>';

}

# Errores.
if($this->error!==NULL){

echo $this->error;
exit();

}

# Destino.
$this->thumb['destino'] = ImageCreateTrueColor($this->thumb['thumb_w'],$this->thumb['thumb_h']);
@imagecopyresized($this->thumb["destino"],$this->thumb['src'],0,0,0,0,$this->thumb['thumb_w'],$this->thumb['thumb_h'],$this->thumb['size_w'],$this->thumb['size_h']);

# Guardar imagen
if($this->thumb['type']=='jpg' || $this->thumb['type']=='jpeg') {

# Guarda imagen jpeg
imageJPEG($this->thumb['destino'],"$path",$this->thumb["quality"]);

}elseif($this->thumb['type']=='png'){

# Guarda imagen png
imagePNG($this->thumb['destino'],"$path");

}elseif($this->thumb['type']=='gif'){

# Guarda gif
imageGIF($this->thumb['destino'],"$path");

}elseif($this->thumb['type']=='wbmp'){

# Guarda wbmp
imageWBMP($this->thumb['destino'],"$path");

}



}

}

?>









la forma de uso
--------------------------
# Thumbnails
$Thumb = new Thumbnails('archivos/'.$File);
$Thumb->width(250)->generate('archivos/thumb/'.$File);


Me retorna que no se puede guardar la imagen en esa locacion :v osea que no se puede guardar :/

Etiquetas: class, oop, php, poo
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 05:48.