Mamedu
Últimas entradas en Artículos
Solve real-world shell scripting problems with over 110 simple but incredibly effective recipes Sarath Lakshman Lectura muy recomendada, sobre las cosas que podemos hacer con bash. Pongo unos ejemplos que he destacado:   Modificar la extensión de los archivos de JPG a jpg rename *.JPG *.jpg Moficar según una expresión regular rename 's/ /_/g' * Buscar resultados en un diccionario #!/bin/bash#Filename: aspellcheck.shword=$1output=`echo "$word" | aspell list`
Un ejemplo de clase para tratar con ficheros de configuración en PHP y sus respectivos tests PHPUnit

Contenido de GcmConfig.php

  1. <?php
  2.  
  3. /**
  4.  * @file GcmConfig.php
  5.  * @author Eduardo Magrané
  6.  *
  7.  * @internal
  8.  * Created 21/01/10
  9.  * Revision SVN $Id: GcmConfig.php 140 2010-01-22 15:54:59Z eduardo $
  10.  * Copyright Copyright (c) 2010, Eduardo Magrané
  11.  *
  12.  * This source code is released for free distribution under the terms of the
  13.  * GNU General Public License as published by the Free Software Foundation.
  14.  */
  15.  
  16. /**
  17.  * @class GcmConfig
  18.  *
  19.  * @brief Lectura y edición de archivos de configuración
  20.  *
  21.  * Esta clase nos permite leer archivos de configuración nativos de php y
  22.  * a la vez la edición de su contenido con formularios php.
  23.  *
  24.  * Inspirado en @see http://www.jourmoly.com.ar/introduccion-a-mvc-con-php-segunda-parte/
  25.  *
  26.  * Uso:
  27.  *
  28.  * Formato para el archivo que contiene las variables de configuración TGC.php:
  29.  *
  30.  * <pre>
  31.  * <?php
  32.  * $TGC[v1]="variable1";
  33.  * $TGC[v2]="variable2";
  34.  * $TGC[v3]="variable3";
  35.  * ?>
  36.  * </pre>
  37.  *
  38.  * Formato para archivo de descripciones TGC_es.php:
  39.  *
  40.  * <pre>
  41.  * <?php
  42.  * $TGC_DESC[v1]="descripcion_variable1";
  43.  * $TGC_DESC[v2]="descripcion_variable2";
  44.  * $TGC_DESC[v3]="descripcion_variable3";
  45.  * $TGC_DESC[v4]="descripcion_variable4";
  46.  * $TGC_DESC[v5]="descripcion_variable5";
  47.  * $TGC_DESC[v6]="descripcion_variable6";
  48.  * ?>
  49.  * </pre>
  50.  *
  51.  * <pre>
  52.  * $config = new GcmConfig('config/TGC.php');
  53.  * $variable1 = $config->get('v1');
  54.  * $config->set('v1','NUEVO VALOR PARA v1');
  55.  * $config->setDescripcion('v1','NUEVO VALOR PARA DESCRIPCION v1');
  56.  * $config->del('v4');
  57.  * </pre>
  58.  *
  59.  * La clase recibe la ruta del archivo que contiene las variables, a partir de la ruta
  60.  * se deduce el nombre de la variable, que sera el del archivo sin '.php'.
  61.  *
  62.  * Los ficheros de idiomas contendran su especificación en el nombre, ejemplo: TGC_es.php
  63.  *
  64.  * @version 0.1
  65.  */
  66.  
  67. class GcmConfig {
  68.  
  69. private $variables; ///< Variables del archivo de configuración
  70. private $descripciones; ///< Descripciones de las variables
  71. private $archivo; ///< Ruta de archivo que contiene el array con las variables
  72. private $nombre_array; ///< Nombre del array que contiene las variables;
  73.  
  74. private $variables_modificadas = FALSE; ///< Para saber si hubo modificaciones para guardar
  75. private $descripciones_modificadas = FALSE; ///< Para saber si hubo modificaciones para guardar
  76.  
  77. /**
  78.   * Array para saber si ya se recogieron las descripciones de los diferentes idiomas
  79.   */
  80.  
  81. private $descripciones_recogidas = FALSE;
  82.  
  83. public $idioma = 'es'; ///< Idioma de las descripciones por defecto
  84.  
  85. function __construct($archivo) {
  86.  
  87. $this->archivo = $archivo;
  88.  
  89. if ( !file_exists($this->archivo) ) {
  90. throw new Exception("Archivo de configuración ".$this->Archivo." no existe");
  91. }
  92.  
  93. $this->nombre_array = str_replace('.php','',basename($this->archivo));
  94.  
  95. include ($this->archivo);
  96.  
  97. /* Los valores del array del archivo son introducidos en $this->variables */
  98.  
  99. eval( '$this->variables = $'.$this->nombre_array.';');
  100.  
  101. }
  102.  
  103. /** Presentamos variables para debug */
  104.  
  105. function debug() {
  106.  
  107. $salida = "\nVariables: ";
  108. $salida .= print_r($this->variables,TRUE);
  109. $salida .= "\nDescripciones: ";
  110. $salida .= print_r($this->descripciones,TRUE);
  111.  
  112. return $salida;
  113.  
  114. }
  115.  
  116. /**
  117.   * Recuperamos descripciones en caso de ser necesario
  118.   *
  119.   * @param $idioma Idioma de las descripciones
  120.   */
  121.  
  122. function recoger_descripciones($idioma = NULL) {
  123.  
  124. $idioma = ( $idioma ) ? $idioma : $this->idioma ;
  125.  
  126. if ( $this->descripciones_recogidas[$idioma] == TRUE ) {
  127. return;
  128. }
  129.  
  130. $this->descripciones_recogidas[$idioma] = TRUE;
  131.  
  132. include (dirname($this->archivo).'/'.$this->nombre_array.'_'.$idioma.'.php');
  133.  
  134. /* Los valores del array del archivo son introducidos en $this->variables */
  135.  
  136. eval( '$this->descripciones['.$idioma.'] = $'.$this->nombre_array.'_DESC;');
  137.  
  138. }
  139.  
  140. /** Devolver array con las variables */
  141.  
  142. function variables() { return $this->variables; }
  143.  
  144. /** Devolver array con las descripciones */
  145.  
  146. function descripciones($idioma = NULL) {
  147.  
  148. $idioma = ( $idioma ) ? $idioma : $this->idioma ;
  149.  
  150. return $this->descripciones[$idioma];
  151.  
  152. }
  153.  
  154. /** Con set vamos guardando nuestras variables. */
  155.  
  156. function set($variable, $valor) {
  157.  
  158. $this->variables_modificadas = TRUE;
  159.  
  160. $this->variables[$variable] = $valor;
  161.  
  162. }
  163.  
  164. /** Guardar valor para descripción */
  165.  
  166. function setDescripcion($variable, $descripcion, $idioma = NULL) {
  167.  
  168. $idioma = ( $idioma ) ? $idioma : $this->idioma ;
  169.  
  170. $this->recoger_descripciones($idioma);
  171.  
  172. $this->descripciones_modificadas[$idioma] = TRUE;
  173.  
  174. $this->descripciones[$idioma][$variable] = $descripcion;
  175.  
  176. }
  177.  
  178. /** Con get('nombre_de_la_variable') recuperamos un valor */
  179.  
  180. function get($variable) {
  181.  
  182. if(isset($this->variables[$variable])) {
  183. return $this->variables[$variable];
  184. } else {
  185. return FALSE;
  186. }
  187.  
  188. }
  189.  
  190. /** Con getDescripcion('nombre_de_la_variable') recuperamos la descripción */
  191.  
  192. function getDescripcion($variable, $idioma = NULL) {
  193.  
  194. $idioma = ( $idioma ) ? $idioma : $this->idioma ;
  195.  
  196. /* Si no tenemos las descripciones hay que recuperarlas */
  197.  
  198. if ( !$this->descripciones_recogidas[$idioma] ) { $this->recoger_descripciones($idioma); }
  199.  
  200. if(isset($this->descripciones[$idioma][$variable])) {
  201. return $this->descripciones[$idioma][$variable];
  202. } else {
  203. return FALSE;
  204. }
  205.  
  206. }
  207.  
  208. /**
  209.   * Borrar variable
  210.   *
  211.   * @param $variable Variable a borrar
  212.   */
  213.  
  214. function del($variable) {
  215.  
  216. $this->variables_modificadas = TRUE;
  217.  
  218. unset($this->variables[$variable]);
  219.  
  220. /* Borramos descripciones en todos los idiomas */
  221.  
  222. /* Buscar ficheros de idiomas */
  223.  
  224. $fidiomas = glob(dirname($this->archivo).'/'.$this->nombre_array.'_*.php');
  225.  
  226. /* Recorrer cada idioma para eliminarlo */
  227.  
  228. foreach( $fidiomas as $f ) {
  229. $idioma = str_replace(dirname($this->archivo).'/'.$this->nombre_array.'_','',$f);
  230. $idioma = str_replace('.php','',$idioma);
  231. $this->delDescripcion($variable, $idioma);
  232. }
  233.  
  234. return TRUE;
  235.  
  236. }
  237.  
  238. /**
  239.   * Borrar descripción
  240.   *
  241.   * @param $variable Variable a borrar su descripción
  242.   */
  243.  
  244. function delDescripcion($variable, $idioma = NULL) {
  245.  
  246. $idioma = ( $idioma ) ? $idioma : $this->idioma ;
  247.  
  248. $this->recoger_descripciones($idioma);
  249.  
  250. $this->descripciones_modificadas[$idioma] = TRUE;
  251.  
  252. unset($this->descripciones[$idioma][$variable]);
  253. return TRUE;
  254.  
  255. }
  256.  
  257. /** Guardar cambios de variables en archivo */
  258.  
  259. function guardar_variables() {
  260.  
  261. $this->escribirArchivos($this->archivo, $this->variables, $this->nombre_array);
  262.  
  263. return TRUE;
  264.  
  265. }
  266.  
  267. /** Guardar cambios de descripciones en archivo */
  268.  
  269. function guardar_descipciones($idioma = NULL) {
  270.  
  271. $idioma = ( $idioma ) ? $idioma : $this->idioma ;
  272.  
  273. /* Miramos si han habido cambios antes de escribir archivo sino nos crearia un
  274.   * archivo sin contenido
  275.   */
  276.  
  277. if ( $this->descripciones_modificadas[$idioma] != TRUE ) {
  278. return TRUE;
  279. }
  280.  
  281. $archivo_descripciones = dirname($this->archivo).'/'.$this->nombre_array.'_'.$idioma.'.php';
  282.  
  283. $this->escribirArchivos($archivo_descripciones, $this->descripciones[$idioma], $this->nombre_array.'_DESC');
  284.  
  285. return TRUE;
  286.  
  287. }
  288.  
  289. /** Pasar contenido a archivos php */
  290.  
  291. function escribirArchivos($archivo, $datos, $nombre_array) {
  292.  
  293. if (is_writable($archivo)) {
  294.  
  295. if (!$file = fopen($archivo, "w")) {
  296. throw new Exception("No se puede escribir en ".$archivo);
  297. return FALSE;
  298. }
  299.  
  300. fputs($file, "<?php\n");
  301.  
  302. while (list($clave, $val)=each($datos)){
  303.  
  304. if ( is_array($val)) { // si es un array
  305.  
  306. while (list($claveArray, $valorArray)=each($val)) {
  307.  
  308. $valorArray=str_replace('\'','\\\'',$valorArray); // Tratamiento de las comillas
  309. if (fputs($file, '$'."$nombre_array"."['".$clave."'][]='".$valorArray."';\n") === FALSE ) {
  310. throw new Exception("No se puede escribir en ".$archivo);
  311. return FALSE;
  312. }
  313. }
  314.  
  315. } else { // No es un array
  316.  
  317. $val=str_replace('\'','\\\'',$val); // Tratamiento de las comillas
  318. if (fputs($file, '$'."$nombre_array"."['".$clave."']='".$val."';\n") === FALSE ) {
  319. throw new Exception("No se puede escribir en ".$archivo);
  320. return FALSE;
  321. }
  322.  
  323. }
  324. }
  325. fputs($file, "?>");
  326. fclose($file);
  327. }
  328.  
  329. return TRUE;
  330.  
  331. }
  332.  
  333. /** Antes de terminar guardar cambios si los han habido */
  334.  
  335. function __destruct() {
  336.  
  337. if ( $this->variables_modificadas ) { $this->guardar_variables(); }
  338.  
  339. /* Recorremos array de descripciones_modificadas para saber cuales hay que actualizar */
  340.  
  341. if ( !empty($this->descripciones_modificadas) ) {
  342.  
  343. foreach ( $this->descripciones_modificadas as $i => $dm ) {
  344. if ( $dm ) { $this->guardar_descipciones($i); }
  345. }
  346.  
  347. }
  348.  
  349. }
  350.  
  351. }
  352.  
  353.  
  354. ?>
  355.  
Uso del patron Factory para no crear diferentes instancias sobre el mismo archivo.

Contenido de GcmConfigFactory.php

  1. <?php
  2.  
  3. /**
  4.  * @file GcmConfigFactory.php
  5.  * @brief Patron Factory para la clase GcmConfig
  6.  *
  7.  * @author Eduardo Magrané
  8.  *
  9.  * @internal
  10.  * Created 22/01/10
  11.  * Revision SVN $Id: GcmConfigFactory.php 140 2010-01-22 15:54:59Z eduardo $
  12.  * Copyright Copyright (c) 2010, Eduardo Magrané
  13.  *
  14.  * This source code is released for free distribution under the terms of the
  15.  * GNU General Public License as published by the Free Software Foundation.
  16.  */
  17.  
  18.  
  19. /**
  20.  * @class GcmConfigFactory
  21.  * @brief Patron Factory para la clase GcmConfig
  22.  *
  23.  * Para asegurarnos que recogemos la misma instancia para cada fichero de
  24.  * configuración
  25.  *
  26.  * @version 0.1
  27.  */
  28.  
  29. require_once('GcmConfig.php');
  30.  
  31. class GcmConfigFactory {
  32.  
  33. public static function GetGcmConfig($archivo) {
  34.  
  35. $key = md5(serialize($archivo));
  36.  
  37. if ( ! ($GLOBALS['GcmConfig'][$key] instanceof GcmConfig) ) {
  38.  
  39. $GLOBALS['GcmConfig'][$key] = new GcmConfig($archivo);
  40.  
  41. }
  42.  
  43. return $GLOBALS['GcmConfig'][$key];
  44.  
  45. }
  46.  
  47. }
  48.  
  49. ?>
  50.  
Y aquí los Tests para PHPUnit correspondientes.

Contenido de TestGcmConfig.php

  1. <?php
  2.  
  3. /**
  4.  * @file Test phpUnit para GcmConfig
  5.  */
  6.  
  7. DEFINE(ARCHIVO,'/tmp/TGC.php');
  8. DEFINE(ARCHIVO_DESC,'/tmp/TGC_es.php');
  9.  
  10. /* construimos archivo para pruebas */
  11.  
  12. $contenido = "\n".'<?php ';
  13. $contenido .= "\n".'$TGC[v1]="variable1";';
  14. $contenido .= "\n".'$TGC[v2]="variable2";';
  15. $contenido .= "\n".'$TGC[v3]="variable3";';
  16. $contenido .= "\n".'$TGC[v4]="variable4";';
  17. $contenido .= "\n".'$TGC[v5]="variable5";';
  18. $contenido .= "\n".'$TGC[v6]="variable6";';
  19. $contenido .= "\n".'?>';
  20.  
  21. file_put_contents(ARCHIVO, $contenido);
  22.  
  23. $contenido = "\n".'<?php ';
  24. $contenido .= "\n".'$TGC_DESC[v1]="descripcion_variable1";';
  25. $contenido .= "\n".'$TGC_DESC[v2]="descripcion_variable2";';
  26. $contenido .= "\n".'$TGC_DESC[v3]="descripcion_variable3";';
  27. $contenido .= "\n".'$TGC_DESC[v4]="descripcion_variable4";';
  28. $contenido .= "\n".'$TGC_DESC[v5]="descripcion_variable5";';
  29. $contenido .= "\n".'$TGC_DESC[v6]="descripcion_variable6";';
  30. $contenido .= "\n".'?>';
  31.  
  32. file_put_contents(ARCHIVO_DESC, $contenido);
  33.  
  34. require_once 'PHPUnit/Framework.php';
  35.  
  36. require(dirname(__FILE__).'/GcmConfig.php');
  37.  
  38. class TestGcmConfig extends PHPUnit_Framework_TestCase{
  39.  
  40. public $config;
  41. public $archivo;
  42. public $archivo_descripcion;
  43.  
  44. function __construct() {
  45.  
  46. $this->archivo = ARCHIVO;
  47. $this->archivo_descripcion = ARCHIVO_DESC;
  48.  
  49. $this->config = new GcmConfig($this->archivo);
  50.  
  51. }
  52.  
  53. /** Comprobando valor de la primera variable */
  54.  
  55. function testVerValores() {
  56.  
  57. $this->assertEquals($this->config->get('v1'), 'variable1');
  58. $this->assertEquals($this->config->getDescripcion('v6'), 'descripcion_variable6');
  59.  
  60. $nuevo_valor = 'Nuevo valor para v1';
  61. $this->config->set('v1',$nuevo_valor);
  62. $this->assertEquals($this->config->get('v1'), $nuevo_valor);
  63.  
  64. $nuevo_valor = 'Nuevo valor para v1';
  65. $this->config->setDescripcion('v1',$nuevo_valor);
  66. $this->assertEquals($this->config->getDescripcion('v1'), $nuevo_valor);
  67.  
  68. $this->assertTrue($this->config->del('v4'));
  69.  
  70. $this->assertTrue($this->config->delDescripcion('v4'));
  71.  
  72. $this->config->setDescripcion('v1','MODIFICADA');
  73.  
  74. }
  75.  
  76.  
  77. }
  78. ?>
  79.  

Contenido de TestGcmConfigFactory.php

  1. <?php
  2.  
  3. /**
  4.  * @file Test phpUnit para GcmConfigFactory
  5.  */
  6.  
  7. DEFINE(ARCHIVO,'/tmp/TGC.php');
  8. DEFINE(ARCHIVO_DESC,'/tmp/TGC_es.php');
  9.  
  10. /* construimos archivo para pruebas */
  11.  
  12. $contenido = "\n".'<?php ';
  13. $contenido .= "\n".'$TGC[v1]="variable1";';
  14. $contenido .= "\n".'$TGC[v2]="variable2";';
  15. $contenido .= "\n".'$TGC[v3]="variable3";';
  16. $contenido .= "\n".'$TGC[v4]="variable4";';
  17. $contenido .= "\n".'$TGC[v5]="variable5";';
  18. $contenido .= "\n".'$TGC[v6]="variable6";';
  19. $contenido .= "\n".'?>';
  20.  
  21. file_put_contents(ARCHIVO, $contenido);
  22.  
  23. $contenido = "\n".'<?php ';
  24. $contenido .= "\n".'$TGC_DESC[v1]="descripcion_variable1";';
  25. $contenido .= "\n".'$TGC_DESC[v2]="descripcion_variable2";';
  26. $contenido .= "\n".'$TGC_DESC[v3]="descripcion_variable3";';
  27. $contenido .= "\n".'$TGC_DESC[v4]="descripcion_variable4";';
  28. $contenido .= "\n".'$TGC_DESC[v5]="descripcion_variable5";';
  29. $contenido .= "\n".'$TGC_DESC[v6]="descripcion_variable6";';
  30. $contenido .= "\n".'?>';
  31.  
  32. file_put_contents(ARCHIVO_DESC, $contenido);
  33.  
  34. require_once 'PHPUnit/Framework.php';
  35.  
  36. require(dirname(__FILE__).'/GcmConfigFactory.php');
  37.  
  38. class TestGcmConfigFactory extends PHPUnit_Framework_TestCase{
  39.  
  40. public $config;
  41. public $archivo;
  42. public $archivo_descripcion;
  43.  
  44. function __construct() {
  45.  
  46. $this->archivo = ARCHIVO;
  47. $this->archivo_descripcion = ARCHIVO_DESC;
  48.  
  49. $this->config = GcmConfigFactory::getGcmConfig($this->archivo);
  50.  
  51. }
  52.  
  53. /** Comprobando valor de la primera variable */
  54.  
  55. function testCambiarValores() {
  56.  
  57. $this->assertEquals($this->config->get('v1'), 'variable1');
  58. $this->assertEquals($this->config->getDescripcion('v6'), 'descripcion_variable6');
  59.  
  60. $nuevo_valor = 'Nuevo valor para v1';
  61. $this->config->set('v1',$nuevo_valor);
  62. $this->assertEquals($this->config->get('v1'), $nuevo_valor);
  63.  
  64. $nuevo_valor = 'Nuevo valor para v1';
  65. $this->config->setDescripcion('v1',$nuevo_valor);
  66. $this->assertEquals($this->config->getDescripcion('v1'), $nuevo_valor);
  67.  
  68. $this->assertTrue($this->config->del('v4'));
  69.  
  70. $this->assertTrue($this->config->delDescripcion('v4'));
  71.  
  72. $this->config->setDescripcion('v1','MODIFICADA');
  73.  
  74. echo "<pre>" ; print_r($GLOBALS) ; echo "</pre>"; // DEV
  75. }
  76.  
  77.  
  78. }
  79. ?>
  80.  
...
aICtGX hdfdbka
How much is a First Class stamp?
I'd like to order some foreign currency
I'd like a phonecard, please
Please call back later
We work together
How long are you planning to stay here?
Could I make an appointment to see ?

Usuario:

Contraseña:


ojo.gif
www.mamedu.com
Webmaster