Archive of articles classified as' "programacion"

Back home

Get Facebook access_token

2Nov11

I’m going to try to document the experience of creating an access_token so my app. can post messages on my Facebook Page. As a summary, I have the following elements:

1) Facebook Page

This is the Doonish Facebook Page. It’s a page that describes the project and that try to get as many fans as possible.

2) Facebook Application

In the other side I’ve created an application for allowing the remote post to my page. This is application that will do that.

What I want to do is promote each day a new question from doonish into my Doonish Facebook Page.

 

How to automatically post in a Facebook Page?

1) Get application “access_token”

The first step is to get application “token_id” so we can post to the Facebook Page.

https://www.facebook.com/dialog/oauth?
    client_id={facebook-app-id}&
    redirect_uri={your-url}&
    scope=manage_pages&
    response_type=token

That will return with something like the following:

access_token={your-access-token}

2) Find the page “access_token”

Then, using the above token, you can go to the following location:

https://graph.facebook.com/me/accounts?
    access_token={your-access-token}

And you will see something like the following:

{
    "data": [
    {
        "name": "{your-page}",
        "access_token": "{page-token-id}",
        "category": "Website",
        "id": "{page-id}"
    },
    ...
    ]
}

3) Write the actual script

Whith the above “page-token-id” you can then write a PHP snippet that can do something like the following:

/**
 * Promote
 *
 * This method will automatically post a message on the facebook wall.
 *
 * @param integer $questionId The id of the question that we want to 
 *     promte.
 */
public function promote($questionId)
{
    $message = $this->generateMessage($questionId);
 
    $facebook = new Facebook(
        array(
            'appId'  => $this->facebookConfig['app_id'],
            'secret' => $this->facebookConfig['secret'],
            'scope'  => $this->facebookConfig['scope'],
            'cookie' => $this->facebookConfig['cookie'],
            'acceptUrl' => $this->facebookConfig['acceptUrl']
        )
    );
 
    $status = $facebook->api(
        '/' . $this->facebookConfig['page_id'] .'/feed',
        'post',
        array(
            'access_token' => $this->facebookConfig['token_id'],
            'message' => $message,
            'cb' => ','
        )
    );
}

Hope this code is useful for someone, it took me a while to figure out the right way to do it. I’ve used Facebook PHP SDK and I’ve got all the information from the Authentication page from Facebook Developers.

No Comments

Some good and bad things from PHP

28Oct11

As a PHP developer I recognise that I’m not as opinated as I should be. When someone asks me “Why I’ve choose PHP” I just say that it’s because it was the first language I’ve deep into and I’ve keep developing myself into PHP (it’s what it allows me to develop more in less time). Once you know a language and you have enough knowledge is interesting to move into other languages so you can open your mind and get a better understanding of your preferred language (exactly like learning another spoken language). I hope I can learn any other language soon ;)

I’m going to summarize some pros and cons from PHP as a interesting excersise for myself:

Advantages:

  • Documentation: At the beginning is difficult to get use to (like any other documentation) but when you are into it, it’s pretty handy. My usual searches on google are “php array functions” or “php string functions”. A good point is allowing the comments from the users, some of them really interesting.
  • Easy to start: It’s easy to install WAMP (on Windows) or using php on cli with *NIX. There are lots of tutorials and all-known open source projects to look at the source code to learn more (WordPress, Drupal, etc.). Furthermore, you can got a cheap host easily.
  • Web optimized: Really easy to access to GET and POST variables and by default there is a direct map between the file and the URL. This kind of things make it easy to learn.
  • Right model: Requests are isolated from other requests and if it goes wrong, that is too isolated, which means that you can leak memory, have terrible bugs or infinite loops and you will not kill your server beause Apache is on top of that.
  • Scaling: Is relative common knowledge to scale PHP, you can search on Internet and you will find lots of tutorials, tips, etc.

Disadvantages:

  • Error handling: There is more than a single way to handling errors: trigger_error(), Exceptions and returning codes. Not having a unique and organized way make libraries mix all of this methods and sometimes makes it difficult to trap.
  • Too many falses: Not having a typed variables makes all this expressions evaluate as false: null, false, empty string, zero, the string containing ’0′ and empty array.
  • Initialization: There is a lot of things that can be modified on the php.ini and it could change from server to server. Not a big pain but should be aware.
  • Returning arrays: If a function returns an array you have to assign it to a variable before accessing an element, you can’t just add an index after the function call.
  • No multiple inheritance: PHP doesn’t support multiple inheritance.
  • Evolving language: The fact that it’s evolving and having new features in each release has other constraints: “register_globals” (“script.php?auth=1″ sets $auth as TRUE by default), “magic_quotes” (that’s not for security and people is relying on that) and “PHP4′s object reference model” (where references didn’t point to the object, they were pointing to the variable).
  • Others: Lack of case sensitivity (“$variable” is the same than “$VaRiaBLe”), needle and haystack vs haystack and needle in different array methods, having to use “array()” instead of just “[]“.
No Comments

Configurar l’idioma Català a Linux

30Jul10

Estic fent algunes probes per a mostrar les dates a PHP en Català. Al meu servidor local tot funcionava correctament, pero al passar-ho al servidor remot ha deixat de funcionar.

El codi font es el següent (en PHP):

setlocale(LC_ALL, $lang . "_ES.UTF-8");
echo strftime("%A %e de %B del %Y a " . $translate->_("las") . " %H:%M", strtotime($time));

En castellà funcionaba correctament, pero al passar-ho al català no funciona.

Per a que funcioni, he hagut de fer la següent modificació: Obrir el fitxer /var/lib/locales/supported.d/local i afegir la darrera línea.

es_ES.UTF-8 UTF-8
ca_ES.UTF-8 UTF-8

Despres de desar el fitxer, he executat la següent comanda:

sudo dpkg-reconfigure locales

I ja ha funcionat, ja puc veure la data tant en català com en castellà :) !

No Comments

Error messages in Zend Form .ini file

24Jul10

I was searching the way to customize the validator error messages in Zend Form using the .ini file.

Finally I found two useful links:

  1. Rob Allen answering in StackOverflow
  2. One guy asking a similar question in Nabble

I copy here the content of my form.ini:

; apellido
elements.apellido.type = "text"
elements.apellido.options.label = "Apellido"
elements.apellido.options.description = "Introduce tu apellido"
elements.apellido.options.validators.notempty.validator = "NotEmpty"
elements.apellido.options.validators.notempty.options.messages.isEmpty = "Campo requerido"
elements.apellido.options.validators.notempty.breakChainOnFailure = true
elements.apellido.options.validators.strlen.validator = "StringLength"
elements.apellido.options.validators.strlen.options.min = "1"
elements.apellido.options.validators.strlen.options.max = "100"
elements.apellido.options.required = true

Some useful tips that you might know:

  • If you don’t put the “options.required = true” the “NotEmpty” validator doesn’t work.
  • If you don’t put the “breakChainOnFailure = true” the form will carry on executing other validators.
  • You can search in the Zend Framework source code for the messages that you can overwrite. Look at: “Zend/Validate/*” files.

I wish it will be useful for somebody =) !

2 Comments

Iterar sobre array en PHP y Javascript

26May10

¡Porfin lo encontré!

En PHP hacemos el típico foreach:

foreach($array as $key => $value) {
echo "clave = " + $key;
echo "valor = " + $value;
}

Y en Javascript también se puede hacer del siguiente modo:

for(i in array) {
alert("clave = " + i);
alert("value = " + array[i]);
}
No Comments

Función de swap sin variable aux

3May10

Este es el típico problema que te ponen a veces para probar tu habilidad como programador.

Tienes que hacer una función para cambiar los valores de dos variables sin usar una variable auxiliar.

La función que a todos se nos ocurre és:

function swap($a, $b) {
   $tmp = $a;
   $a = $b;
   $b = $tmp;
}

Pero esta no cumple el enunciado. Una posible función que si cumple el enunciado es la siguiente:

function swap($a, $b) {
   $a = $a + $b;
   $b = $a - $b;
   $a = $a - $b;
}

Edición 05/07/2010:

Juan Antonio Galán, mediante los comentarios me hace llegar esta solución:

function swap($a, $b) {
   list($a, $b) = array($b, $a);
}

Y Víctor me comenta esta otra:

function swap($a, $b) {
   $a ^= $b ^= $a ^= $b;
}

Muchas gracias por vuestra aportación ;) !

2 Comments

Por qué Zend Framework?

26Dec09

El otro día recibí un comentario de un lector de mi blog y me preguntaba:

Pau, por que  Zend Framework? Vi que hace un tiempo habías hecho un post sobre CakePHP.

Voy a dar la respuesta a este comentario en forma de post. Es cierto que había escrito un post sobre CakePHP. Un amigo (Xavier Orduña) me lo presentó y lo probé. Entonces aún no conocí­a ningún framework de desarrollo y, al topar por primera vez con Cake, me pareció una manera muy rápida de agilizar el desarrollo de una aplicación web.

Un tiempo más tarde, y sin haber profundizado con Cake, probé Zend Framework. También me lo recomendó otro amigo (Claudio Cossio) y tengo que confesar que me gustó más que Cake.

Ya llevo un tiempo desarrollando con Zend y después de un par de proyectos, puedo sacar las siguientes conclusiones. Antes advierto que no soy un experto en frameworks, he tocado mas o menos en profundidad Zend, he jugado con CakePHP y Django (para Python) y me han hablado muy bien de Symphony, así que ya aviso que mi punto de vista va a estar desviado.

  1. Documentación correcta: Acostumbro a consultar su documentación a menudo y está bastante bien, con ejemplos bastante bien explicados y sobretodo prácticos.
  2. Sencillo: Es relativamente sencillo de montar una aplicación básica con Zend Framework. Si luego quieres ir un poco más allá ya en cuanto a complejidad, ya vas a tener que mirarte la documentación.
  3. Completitud de módulos: Tiene módulos para casi todo. Una vez empiezas a programar con él, cada vez que revisas los módulos encuentras alguno que te va a ser útil.
  4. Zend está detrás: El hecho de que Zend, la compañía que desarrolla PHP está detrás de este framework me da una cierta seguridad de que será mantenido y que dará soporte por mucho tiempo.
  5. Patrones de base de datos: Me encanta el patrón de diseño que usa ZF para acceso a la base de datos: Table Data Gateway y Row Data Gateway. Me imagino que la mayoría de frameworks deben usar cosas parecidas, pero la manera en que lo resuelve Zend Framework es especialmente cómoda para el programador.

Por último, cito las palabras del amigo Carlos Buenosvinos en una de las discusiones del Grupo de programadores PHP Barcelona, en respuesta a “¿Qué framework PHP usáis?“:

Has de considerar, la comunidad, la continuidad, performance, si está basado en componentes o no (migrar o nueva aplicación desde 0), contenido en la red, libros (material didáctico), oferta de desarrolladores (en el caso de que quieras contratar), funcionalidades totales, funcionalidades que se adaptan a tus requerimientos, funcionalidades que le faltan para tu aplicación, si tienes desarrolladores en tu equipo que ya conozcan algún framework, soporte con PHP 5.3 (compatibilidad hacia atrás, sin compatibilidad, …), etc. No te dejes llevar por modas, como siempre, la respuesta es depende.

Pues nada, saludos y disfruten de las vacaciones de navidad (quien las tenga!).

No Comments

Truco mnemotécnico para CSS

25Sep09

Siempre que tengo que poner el margin o el padding a un div tengo dos opciones:

a) La forma lenta y segura:

div.ejemplo {
     padding-top: 1px;
     padding-bottom: 2px;
     padding-left: 3px;
     padding-right: 4px;
}

b) La forma corta:

div.ejemplo {
     padding: 1px 4px 2px 3px;
}

El problema para mí es acordarme del orden de los 4 atributos que siguen a “padding”. Lo que muchas veces hacía era añadir la siguiente línea (o simplemente me lo pegaba con un postit en la pared para tenerlo a mano):

div.ejemplo {
     /* padding: up right down left */
     padding: 1px 4px 2px 3px;
}

Pues aquí un truquillo bien absurdo que se me ha ocurrido a mi mismo (es decir, no lo he sacado de internet):

El orden de los atributos es en el mismo que las agujas del reloj (cada 15 min)

2 Comments

Funcion date() de PHP con timestamp

24Sep09

Si tienes en una tabla un atributo del tipo “timestamp” (es un formato de fecha, por ejemplo 2009-09-24 18:06:13) puedes updatear el valor con la siguiente instrucción:

   $row->last_access = date("c");

En vez de esta:

   $row->last_access = date("Y-m-d H:i:s");

No te va a hacer faltarecordar el dichoso formato de “Y-m-d H:i:s”.

-

Nota: Hoy hace un año justo que Miguel y yo nos fuimos de Erasmos a Reading, que tiempos!

No Comments

99 bottles of beer (Code Golf)

29Jun09

Grácias a Gerard, un compañero de la facultad, he conocido Code Golf. La filosofía es sacar un output con el mínimo golpes de tecla posible (es decir, gana alquel que consiga el output con el menor tamaño de fichero).

Me ha picado y he probado con el 99 bottles of beer. He estado un rato y no he conseguido bajar de 276 bytes. El récord está en 172 para PHP.

code-golf-99-bottles-of-beer_1246291675957

Si a alguien le pica el gusanillo y se anima que me avise.

1 Comment