Xinc. Continuous Integration

22 marzo 2008 at 13:52

Fecha Filed in Computers
Tags Tags: ,

Continuous integration is a software engineering practice, which helps to integrate changes frequently in a project. It speeds up the delivery of software by decreasing integration times. It’s very important when the project is being developed by more than one person. CruiseControl is a free CI server and probably the most used. Xinc (Xinc Is Not Cruisecontrol) is an alternative free CI server made specially for PHP. The Xinc development is led by Arno Schneider, a german developer currently living in Barcelona. Arno made a wonderful presentation at the Barcelona PHP Conference celebrated last month:


We can install Xinc easily with PEAR.

sudo pear channel-discover pear.xinc.eu
sudo pear install --alldeps xinc/Xinc
sudo pear run-scripts xinc/Xinc

When we run the scripts, we can configure some parameters like:

 1. Directory to keep the Xinc config files: /etc/xinc
 2. Directory to keep the Xinc Projects and Status information: /var/xinc
 3. Directory to keep the Xinc log files: /var/log
 4. Directory to install the Xinc start/stop daemon: /etc/init.d
 5. Do you want to install the SimpleProject example: yes
 6. Directory to install the Xinc web-application: /var/www/xinc
 7. IP of Xinc web-application: 127.0.0.1
 8. Port of Xinc web-application: 8080

Once the installation is complete, we need to include /etc/xinc/www.conf in our apache virtual hosts. We also have to have mod-rewrite enabled.

Comments Comments (1) Xinc. Continuous Integration Permalink Votar: Positive 3 Negative 0

XSL Cache by The New York Times

11 enero 2008 at 11:10

Fecha Filed in Computers
Tags Tags: , , , ,

The XSL Cache extension is a mod of PHP’s XSL extension developed by the NYTimes. This extension caches the parsed XSL stylesheet representation in sites that constantly the same transform is applied. The code is already working with a few applications on the New York Times’ website.

The installation is very easy. Just run the following commands:

phpize
./configure --with-xslcache=
 –with-xsl-exsl-dir=</path><path to libexslt>
make
sudo make install
</path>

Then you have only to add the line extension=xslcache.so to php.ini file and restart the web server. I’ve been doing some tests with XSL Cache and I got good results. The following code shows how to load a stylesheet and then use it to transform a parsed XML document:

<?php
$xsltpath = '/home/harrisj/example.xsl';

$xslt = new xsltCache;
$xslt->importStyleSheet($xsltpath);
$xml = DOMDocument::loadXML($source_doc);
print $xslt->transformToXML($xml);
?>

XSL Cache Logo

Link | XSL Cache Project

Comments Comments (1) XSL Cache by The New York Times Permalink Votar: Positive 0 Negative 0

Benchmark Lucene en PHP vs Lucene en Java

30 agosto 2007 at 00:21

Fecha Filed in Computers
Tags Tags: , , , ,

Lucene in ActionLucene es una librería opensource de recuperación de información, usada generalmente para la programación de motores de búsqueda. Fue originalmente implementada en Java por Doug Cutting, aunque ha sido portada a otros lenguajes de programación como C, C++, Python, Perl, Ruby, PHP, … Para PHP existe Zend Search Lucene, un motor de búsqueda de propósito general escrito íntegramente en PHP5. Zend Search Lucene almacena sus índices en el sistema de archivos, evitando la necesidad de un servidor de bases de datos. Nos permite una ranked searching (los mejores resultados aparecerán los primeros), diversas potentes consultas (consultas de frases, consultas por proximidad, consultas por rango, …) y búsquedas por campos específicos (por título, autor, contenidos, …).

Zend Search Lucene puede ser una opción estupenda para integrarlo en un proyecto escrito en PHP (nos olvidaríamos de la conexión puente entre Java y PHP), aunque investigando un poco en temas de eficiencia me he topado con un artículo donde el autor hace un pequeño benchmark para comparar Zend Search Lucene y Lucene en Java. Se llega a las siguientes conclusiones:

  • La indexación usando Zend Search Lucene es mucho más lenta que con Java Lucene. En el benchmark se indexó 30.000 resultados con Zend Search Lucene en 1883 segundos (aproximadamente media hora).
  • El índice creado por Zend Search Lucene es totalmente compatible con Java Lucene, por lo que un índice creado por uno puede ser leído por otro y viceversa.
  • La búsqueda con Zend Search Lucene es mucho más lenta que con Java Lucene. El tiempo para 100 búsquedas fue:
    jayant@jayantbox:~/myprogs/java$ java searcher
    Total : 30000 docs
    t2-t1 : 231 milliseconds
    
    jayant@jayantbox:~/myprogs/php$ php -q searcher.php
    Total 30000 docs
    total time : 15 seconds
    

    Aún así se pensó que tal vez el código en PHP devolvía los documentos que se estaba buscando, por lo que se hizo un cambio en el código donde se extraían todos los documentos tanto en PHP como en Java. Sin embargo el tiempo empleado por el código en PHP fue mucho mayor:

    jayant@jayantbox:~/myprogs/java$ java searcher
    Total : 30000 docs
    t2-t1 : 2128 milliseconds
    
    jayant@jayantbox:~/myprogs/php$ php -q searcher.php
    Total 30000 docs
    total time : 63 seconds
    

    El código de búsqueda en PHP usado para Lucene fue el siguiente:

    <?
    *
     * searcher.php
     * On 2007-06-06
     * By jayant
     *
     */
    include("Zend/Search/Lucene.php");
    
    $index = new Zend_Search_Lucene("/tmp/myindex");
    echo "Total ".$index->numDocs()." docsn";
    $query = "java";
    $s = time();
    for($i = 0; $i < 100; $i++)
    {
     $hits = $index->find($query);
    // retrieve all documents. Comment this code if you
    // dont want to retrieve documents
     foreach($hits as $hit)
       $doc = $hit->getDocument();
    }
    $total = time() - $s;
    echo "total time : $total s";
    ?>
    

    Y el código de búsqueda en Java usado para Lucene fue este:

    /*
     *      searcher.java
     *      On 2007-06-06
     * By jayant
     *
     */
    
    import org.apache.lucene.search.*;
    import org.apache.lucene.queryParser.*;
    import org.apache.lucene.analysis.*;
    import org.apache.lucene.analysis.standard.*;
    import org.apache.lucene.document.*;
    
    public class searcher {
    
     public static void main (String args[]) throws Exception
     {
      IndexSearcher s = new IndexSearcher("/tmp/myindex");
      System.out.println("Total : "+s.maxDoc()+" docs");
      QueryParser q = new QueryParser("content",new StandardAnalyzer());
      Query qry = q.parse("java");
    
      long t1 = System.currentTimeMillis();
      for(int x=0; x < 100; x++)
      {
       Hits h = s.search(qry);
    // retrieve all documents. Comment this code
    // if you dont want to retrieve documents
       for(int y=0; y < h.length(); y++)
       {
        Document d = h.doc(y);
       }
    
      }
      long t2 = System.currentTimeMillis();
      System.out.println("t2-t1 : "+(t2-t1)+" ms");
     }
    }
    

Más información | Whatever….

Comments Comments (2) Benchmark Lucene en PHP vs Lucene en Java Permalink Votar: Positive 0 Negative 0

API de Xurrency disponible

07 agosto 2007 at 18:03

Fecha Filed in Internet, Computers, Bussiness 2.0
Tags Tags: , , , ,

XurrencyAunque ya lleva bastante tiempo terminada, hoy encuentro un hueco y lanzo la API de Xurrency. Ahora puedes integrar datos en tu sitio o aplicación web directamente desde Xurrency. Como ya comenté en un principio, la API está basada en SOAP, así que podrás usarla en diferentes lenguajes de programación (multiplataforma). Para PHP, sugiero usa la libreria NuSOAP, una colección libre de clases que permiten a los usuarios enviar y recibir mensajes SOAP.

Actualmente los métodos disponibles son los siguientes:

  • string getName(string $code)
  • string getZone(string $code)
  • string getURL(string $code)
  • int getNumCurrencies()
  • int isCurrency(string $code)
  • array getCurrencies()
  • array getValues(string $code)
  • array getValuesInverse(string $code)
  • float getValue(float $amount, string $base, string $target)

El uso de la API con NuSOAP es tan sencillo como el siguiente ejemplo, donde se muestra el nombre de la divisa con código eur.

        require('lib/nusoap.php'); 

        $cliente = new soapclient('http://xurrency.com/api.wsdl', 'wsdl');
	$err = $cliente->getError();
	if($err)
	   exit();
        $proxy  = $cliente->getProxy();
        $resultado = $proxy->getName('eur');

        if (!$cliente->getError())
          echo $resultado;
        else
          echo $cliente->getError();

Además, he publicado una lista sandbox que muestra las salidas de todos los métodos que ofrece la API.

Más información | API Xurrency

Comments Comments (1) API de Xurrency disponible Permalink Votar: Positive 0 Negative 0

Bye, bye PHP4

19 julio 2007 at 12:24

Fecha Filed in Computers
Tags Tags: ,

Support GoPHP5.orgAlgo offline ando este mes, debido a causas personales. El pasado 13 de Julio se anunció una noticia que tenía en mente comentar, y es que PHP4 nos dice adiós tras algo más de 7 años después de su lanzamiento (Mayo de 2000). Aún así se continuará con las actualizaciones de problemas críticos hasta el día 8 de Agosto de 2008. PHP4 le deja el paso a PHP5, una versión con tres años, mucho más madura, rápida, estable y con muchas mejoras respecto a su anterior versión. Uno de sus principales es la inclusión del motor Zend II, que aporta un nuevo modelo de objetos.

Desde el sitio web oficial de PHP (PHP.net) recomiendan usar el resto de año para adaptar todas las aplicaciones a PHP5. Hay muchos sitios donde prestan ayudas y guías para realizar la migración como Go PHP5. Además, se puede encontrar manual para realizar la migración en el sitio web oficial de PHP, así como la disposición de información adicional para migrar de PHP 5.0 a PHP 5.1 y de PHP 5.1 a PHP 5.2. Cabe decir que en muchos casos habrá que recodificar bastante para aprovecharnos de todo el potencial que nos ofrece PHP5.

Más información | PHP.net

Comments Comments (0) Bye, bye PHP4 Permalink Votar: Positive 0 Negative 0

Librería para PostgreSQL en PHP

04 julio 2007 at 20:13

Fecha Filed in Computers
Tags Tags: , , ,

PostgreSQLPara un proyectillo en el que estoy ligado, he tenido que escribir una pequeña librería para usar PostgreSQL en PHP. Usa funciones propias del core de PHP para manejar el SGBD PostgreSQL, así que deben de estar instaladas para poder usar la librería. Consta de un solo fichero que contiene una clase llamada DBlite_PostgreSQL. El constructor de la clase recibe como parámetros un único array donde se debe de especificar los datos de la conexión. Un ejemplo sería el siguiente:

$opciones = array(
    'user'        => 'usuario',
    'passwd'   => 'password',
    'db'           => 'base de datos',
    'server'     => '127.0.0.1'
);

Con este array de datos ya podríamos crear una instancia de la clase DBlite_PostgreSQL de la siguiente manera:

$db =& new DBlite_PostgreSQL($opciones);

Así de sencillo. La clase ofrece una serie de métodos suficiente para poder trabajar cómodamente. Entre otros, podría citar:

  • query($statement): Realiza una consulta a la base de datos
  • all(): Devuelve los datos de una consulta en un array
  • fields(): Devuelve los campos de una tabla
  • next(): Devuele el siguiente elemento de una tabla
  • get($field): Devuelve los datos de un campo concreto
  • getError(): Devuelve el último error

Archivo | DBlitePostreSQL

Comments Comments (4) Librería para PostgreSQL en PHP Permalink Votar: Positive 4 Negative 0