Archive for the PHP Category

A Nautilus shell

We do a lot of development in PHP here at Easytech. Many times you need to test a bit of PHP code. If you played around with python you surely used the python shell. Fortunately the people at Facebook have created a similar shell for PHP (ironically written in python!). You can find it here: http://www.phpsh.org/. From there you can access the GIT repository or download a tgz or zip file.

Currently I couldn’t find a DEB package for Ubuntu. If you want to install it just follow the following steps (you need python installed)

$ cd ~/Devel/PHP (o donde lo quieran tirar)
$ wget http://github.com/facebook/phpsh/tarball/master
$ tar zxvf facebook-phpsh-*
$ cd facebook-phpsh-*
$ sudo python setup.py install

thats it! To test some PHP weirdness…

$ phpsh
Starting php
type ‘h’ or ‘help’ to see instructions & features
php> var_dump( 1 == ‘1′ )
bool(true)
 
php>

Very often when I review other peoples PHP code I come across an old problem: generating a list of comma separated values from a list of things. This happens often when you want to, say, write an SQL query with a WHERE field IN (a,b,c,…,x) and you have an array with a, b, etc.

Another example is when you want to create an include path by concatenating a list of directories with the PATH_SEPARATOR. Yet another example is when you want to build a path concatenating them with the DIRECTORY_SEPARATOR.

The usual code to accomplish looks something like this:

<?php
     // loop through list an generate string
    $line = ;
    foreach( $list as $el ) {
        $line .= $el . ‘,’;
    }

    $line = substr( $line, 0, strlen( $line ) - 1 );
?>
 

(more…)

If you are developing a module for Drupal you might need to use tabs to simplify a bit a screen which has too much functionality. Typically a settings page that might need too many options to comfortably fit on a single screen. Since I had to search and experiment a bit to find out how to do it I decided to write a short post with my findings. In this article I assume you have a basic understanding on writing Drupal modules.

(more…)

Today I needed to generate source code documentation for a webservice APIs we are in coding. One of the guys in the office suggested I take a look at Zend_Reflection. It turns out its quite simple to write PHP code to parse source files and extract the documentation from them. I took a little time to write this sample program.

This program is quite simple: it has a single class called TestClass with one method: addIntegers(). Below this class I wrote a little code which parses the file and then outputs the information. You can use this and a templating system to generate doc. I used it to write the documentation so that we can easily add it to our Wiki.

The script I wrote parses the documentation style used in Zend Framework. Here’s a sample class:

<?php

/**
 * This is a sample test class.
 *
 * This class has only one method: addIntegers() which adds
 * two integers. Its a sample class for our test.
 *
 */

class TestClass
{
    /**
     * This method adds two integers.
     *
     * This method adds the two given integers and returns
     * its sum. If only one integer is given it sums zero.
     *
     * @param int $number1  The first integer
     * @param int $number2  The second integer
     * @return int The sum of $number1 and $number2.
     *
     */

    public function addIntegers( $number1, $number2 = 0 ) {
         return $number1 + $number2;
    }
}

 

Read the rest of the post to see how to easily parse this code…
(more…)

ZF
In the Oracle world, a lot of the code of an application is stored in procedures inside the database. This gives the best possible performance since the data never leaves the database avoiding data to be sent to and from the client. Code in stored procedures in Oracle is written using the PL/SQL language.

On the other hand, writing web applications is best done in scripting languages like PHP or Python. In addition, it is always recommended to use some type of framework. In PHP you can use CakePHP, Symfony, Codeigniter or, the one we are currently using: Zend Framework.

Calling PL/SQL code from PHP can be tricky sometimes, specially when the PL/SQL procedure has input and output parameters. In this posting I will show you how to call a procedure from the PHP using Zend Framework. I will assume you have some experience using Zend Framework, specially the Database module (Zend_db).

Lets start by creating in the database a simple PL/SQL procedure. Log into sqlplus or sqldeveloper and create the following package and package body:

CREATE OR REPLACE package test_pk AS
  /* Return a greeting message. */
  procedure say_hello(
    name       IN VARCHAR2,
    greeting   OUT NOCOPY VARCHAR2
  );
end test_pk;
/

CREATE OR REPLACE
package body test_pk AS
  /* Return a greeting message. */
  procedure say_hello(
    name       IN VARCHAR2,
    greeting   OUT NOCOPY VARCHAR2)
  IS
    lResult   VARCHAR2(40) := ;
  begin
    lResult := ‘Hello, ‘ || name;
    greeting := lResult;
  end;
end test_pk;

This code will create a procedure say_hello which receives two parameters: as input, name and an output variable, greeting. The procedure will write in the out parameter ‘Greeting, XXXXX‘ where XXXXX will be replaced by the name input parameter.

Now lets see how we can call the PL/SQL code from PHP. Take a look at the following code:

<?php

  // SQL which will call the PL/SQL code.
  $sql = ‘begin test_pk.say_hello(:p1, :p2); end;’;

  // we create a statement with the DB connection
  // and the SQL code.
  $statement = new Zend_Db_Statement_Oracle( $db, $sql );

  // create output variable. Reserve enough space for answer
  $greeting = sprintf( "%20s", );

  // write params (notice the ‘&’!)
  $params = array(
    ‘p1′=> ‘Cesar’,
    ‘p2′=> &$greeting
  );

  // execute the PL/SQL code
  $statement->execute( $params );

  // display results
  var_dump( $params );

To execute the code you need a database connection called $db. When you run this PHP code you will get:

  array(2) {
    ["p1"]=>
      string(5) "Cesar"
    ["p2"]=>
      &string(12) "Hello, Cesar"
  }

It is important to note a couple of things:

  1. In Zend Framework you must use named parameters since positional parameters are not supported when using the Oracle adapter.
  2. You must reserve space for our output. The best way is to create a string with enough blank spaces for the longest possible answer. You will get the following message if its too short: ORA-06502: PL/SQL: numeric or value error: character string buffer too small
  3. When you add output variable you must do so by reference (notice the ‘&’ sign in the $params array).

Hope this helps someone!

Supongamos que tenemos un array con los indices separados por underscore “_”, y necesitamos transformar esos indices a camelCase, esto puede surgir por la necesidad que los nombres de nuestro codigo sigan el standar de la gente de Zend, cuando obtenemos un array de la base de datos, esos datos vienen con la normalizacion de la base, que generalmente es CAMEL_CASE, esto es un problema porque cuando queramos leer los datos de esa tabla tenemos que hacer algo como $row['CAMEL_CASE'], y no va con nuestro “Standar de buenas practicas”, si es por este motivo o algun otro podes usar esta funcion que transforma los indicies de CAMEL_CASE a camelCase. Es la forma mas optima que encontre, si alguno puede aportar algo mejor, podemos optimizarla mas, y conseguir mejores  resultados.

<?php
class Me_Utils_Array
{
  /**
  * Recibe un array, donde las keys, son palabras con el formato PALABRA_SEGUNDA_TERCERA,
  * y devuelve un array con identicos valores, pero las key con el formato de camelCase
  *
  * @param array $unformatArray
  * @return array $camelCaseArray
  */
  public static function keyArrayToCamelCase( $unformatArray )
  {
    $unformatArray = array_change_key_case( $unformatArray, CASE_LOWER );
    $camelCaseArray = array();
    foreach( $unformatArray as $originalKey => $value ) {
      $key = str_replace( ' ', '', ucwords( preg_replace('/[^A-Z^a-z^0-9]+/', ' ', $originalKey )));
      $key[0] = strtolower($key[0]);
      $camelCaseArray[ $key ] = $value;
    }
    return $camelCaseArray;
  }
}
?>

y la usamos de la siguiente forma

<?php

  $row = array( 'FIRST_NAME' => 'Nestor', 'LAST_NAME' => 'Kirchner');
  $rowNormalized = Me_Utils_Array::keyArrayToCamelCase( $row );
  print_r( $rowNormalized );

  // Array ( [firstName] => Nestor [lastName] => Kirchner )

Cuando generamos un View, y queremos darle un formato en particular tenemos que agregar una llamada desde nuestro templates a la función views_embed_view, pasando por parámetros el nombre de la vista, el display_id.

<?php echo views_embed_view( 'nombre_vista' , $display_id = 'default' ); ?>

Cuando hacemos esta llamada nos genera un html con el contenido de la vista. Si queremos darle un formato html especial tenemos que generar un archivo con el nombre view_view–nombre_vista.tpl.phpA esta función llega un objeto con el nombre $view->result, que contiene todo el contenido de nuestra vista.

Por ejemplo si quisieramos mostrar el contenido de la vista en una listado con el title y el teaser, el código seria el siguiente.

<ul class="destacados_libros">
  <?php if (!empty($title)): ?>
  <li class="top_titulo"><?php print $title; ?></li>
  <?php endif; ?>
  <?php foreach ($view->result as $row): ?>
    <li><?php echo $row->node_revisions_teaser; ?></li>
    <li><?php echo $row->node_title;?></li>
  <?php endforeach; ?>
</ul>

Photoshop Slice tool Graphic designers, when creating websites, will often give programmers the Photoshop (PSD) files of the screens and, if they have enough experience designing for the web, they will ’slice’ the design. Basically what they’ll do is mark a rectangular region (a ’slice’) of the image that will then be used in the HTML of the page. Often a single page is composed of many such slices. When the designer is happy with his work he will save in one shot all the slices and provide the programmer with the slices and PSD files in case he needs to modify anything later on. If you buy templates from templating sites such as Template Monster you will receive the HTML, slices and PSD files.

Here in Easytech we mostly use The Gimp to read and modify PSD files. The Gimp can read and write PSD files with no problem, preserving layout information, etc. Unfortunately, it has no slice support and completely ignores all slice information stored on the PSD file. After looking a while for an alternative I was disapointed I couldn’t find one. What I did find is a little document which describes an old PSD file format and a C# parser which understands the Slices section of the PSD file. With this information and a hex editor and some sample PSD files I was able to write a little PHP script which basically outputs a list of convert statements which can be used to slice an image.

To use the script:

1. Download the script by clicking HERE.
2. Open the PSD file with The Gimp and save it as a PNG
3. Run this script on the PSD file
4. Run the resulting converts on the PNG file to slice it up

This code is quite simple and was written over a weekend so its quite rudimentary. It has almost no error checking and is more a proof of principle. If later on I need something more sophisticated this code will provide a good starting point.

The first thing I should probably do is split the program into two smaller programs: one to write an XML document describing the slices and a second program that processes this document and writes the convert statements. In addition I should probably create a couple of Classes to make the code more re-usable. Maybe later… for the moment have fun with it!

While working on the administration section of a medium to large site, you may need to allow different roles to create and edit different content. Typically you want Role X to be able to create and view some content types only. The creation part is easy: go to the Access control section and give Role X the Create and Edit permission for the content types you want this role to be able to create and edit. The next thing you’ll want to do is give the role a way to list all nodes for the content type it is allowed to view/edit and be able to administer these nodes. The logical thing would be to give the role access to the admin/content/node by giving this role the administer nodes permission. The problem is that the filter for this screen will show you nodes of all types regardless of what the role should be able to edit! This hack will guide you to another trick: creating a views page for Role X to be able to administer the nodes he should have access to. Read on for the rest of this hack.

A page to edit and create content types

 

(more…)

A missing feature in Drupal is the ability to preview changes made to the home page. If you have a custom page as your home and you promote several pieces of content to it there is no way for you to preview how it will look. If the content breaks the layout or doesn’t look as good as you expect it to do then you’ll have to make several changes to fine-tune your home. Wouldn’t it be great if you could get a preview of your home and when you are satisfied with the all the changes hit a publish button to see all your changes commit at once? Well you can! Read on to see how.

(more…)