Archive for the Programming and Scripting Category

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>

Sometimes when programming, you have to debug your application. Yes, even when using Adobe Flex. The problem (and on the other hand, the good thing) is, that living in a Linux world makes you the one responsible for enabling every feature you need.

In this case, as mentioned, the feature I needed was to enable the trace() method for debugging Flex applications. To achieve this is actually quite simple. You just have to create a file in your home folder, named mm.cfg. When enabled, tracing is done automatically to the file $HOME/.macromedia/Flash_Player/Logs/flashlog.txt (you can, however, modify this location in the mm.cfg file).

The content of a simple, yet functional mm.cfg file sample is given below.

TraceOutPutFileName=$HOME/.macromedia/Flash_Player/Logs/flashlog.txt
ErrorReportingEnable=1
TraceOutputFileEnable=1

There is one more caveat though. The trace() method only works when viewing your flash application in a debugging-enabled
version of the Flash Player (or the flash plugin in mozilla).

As an added bonus, there is a plugin for Firefox, Flash Tracer, that will display a sidebar with the output of the trace() calls. This can be quite handy so not to have to open a terminal just for viewing the log file.

Now that you know the truth, off you go, and happy debugging!

A screenshot of Pida As we have often said, we are very fond of vim here at Easytech. Even though it is an incredible editor I sometimes miss some features of editors like GEdit, Coda or TextMate. I don’t miss too many things, but some things are simpler when you have a good GUI. One example is browsing files and managing several open buffers. Another is SVN integration (another tool we use here).

After a while looking at ways to integrate Vim into GTK applications and when I was just about to start a project myself I found the solution to my ‘itch’: Pida. Pida is basically an IDE for Python. The really cool thing about it is that it allows you to choose which editor to use. You get the only two real choices: Vi or Emacs.

In addition to having the editor window with all the powerful editing capabilities of Vi or Emacs you get a side panel which has a list of buffers to edit, a list of projects and a view of the filesystem of the selected project. This way you can easily navigate the filesystem of your project and the open files. If you are using SVN then the state of each file is also displayed and you have a popup menu so it’s easy to do SVN operations on files or directories. By installing a plugin you can also watch pending tickets if you use Trac (which we do). Finally, the icing of the cake is that the applications is written using Python and GTK (PyGTK + Glade to be more specific) and with its plugin system its very easy to extend. If you like programming with Vi then Pida is definitively for you. Check it here: http://pida.co.uk/

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…)

A problem which often arises when writing Drupal themes, modules, etc. is making sure there are no ‘hard-coded’ paths in our code. To help new users on their quest to writing quality Drupal code I list here the most used API functions to get paths in a portable way:

  • global $base_url - A global variable which stores your sites URL, typically http://www.<your_site>.com. This variable is set in your settings.php configuration file. This is not very portable and maybe in the future Drupal has a function for this.
  • base_path() - Returns the base URL path of the Drupal installation. At the very least, this will always default to /. This is used, for example when you want to add a resource relative to your base_url. For example like so: drupal_set_html_head(’<style type=”text/css” media=”all”>@import “‘. base_path() . drupal_get_path(’module’, ’system’) .’/system.css”;</style>’);
  • conf_path() - Based on your sites URL tries to find the most appropiate settings.php (site configuration file). To read how it works see Drupals API documentation
  • drupal_get_path($type, $name) - Returns the path to a system item (module, theme, etc.). The $type argument can be ‘theme’, ‘theme_engine’ or ‘module’ and $name the name of the item for which you want the path. To get an absolute path you need to prefix the $DOCUMENT_ROOT (the document root of your drupal installation).
  • path_to_theme() - This points to your theme’s path on the local filesystem. Usually $DOCUMENT_ROOT/themes/<your_theme> or $DOCUMENT_ROOT/sites/<your_site>/themes/<your_theme>
  • path_to_engine() - Returns the path to the currently selected engine.

To learn a bit more search for this terms in the API search box or ‘use the source, Luke!’.

A pesar de su empinada curva de aprendizaje, el editor de texto Vim es la elección de varios de los desarrolladores en Easytech, por su poder, simpleza y customización.

Como lo usamos para casi todo tipo de edición, desde modificar un archivo de configuración hasta programar una aplicación, se nos ocurrió buscar maneras de personalizarlo para incrementar su potencial.

Resultó que Vim 7 ya trae consigo actualizaciones muy prácticas para programadores. Algunas otras las agregaremos a modo de Plugins, con una mínima configuración, como se detalla a continuación:

(more…)