Archive of articles classified as' "php"

Back home

How to name interfaces / abstract classes with namespaces

14Nov11

I’m building a new library with the aim to parse venues from Internet (code on Github). Well, aside from the purpose or usage of the library I’m using this project development to try to write the domain oriented code and by the way I’m facing some arquitectural problems.

Basically, in the past the most common convention for naming interfaces or abstract classes was the following:

For the interface (lib/domain/venue/interface.php):

interface venues_domain_venue_interface {}

And for the abstract (lib/domain/venue/abstract.php):

abstract class venues_domain_venue_abstract {}

Now, I want to port this code to PHP 5.3 Namespace format. The translation is not that direct, note that “abstract” and “interface” are reserver keywords and I can not use then to name my clases.

For the interface (lib/Domain/Venue/Interface.php):

use Venues\Domain\Venue;
 
interface Interface {}

And for the abstract (lib/Domain/Venue/Abstract.php):

use Venues\Domain\Venue;
 
abstract class Abstract {}

That will simply break with a PHP Parse Error because the “Interface” or “Abstract” are reserver keywords.

Researching on Internet I’ve found the following options:

 

1. Prepend the domain name

For the interface (lib/Domain/Venue/VenueInterface.php):

use Venues\Domain\Venue;
 
interface VenueInterface {}

And for the abstract (lib/Domain/Venue/VenueAbstract.php):

use Venues\Domain\Venue;
 
abstract class VenueAbstract {}

 

2. Append the domain name

For the interface (lib/Domain/Venue/InterfaceVenue.php):

use Venues\Domain\Venue;
 
interface InterfaceVenue {}

And for the abstract (lib/Domain/Venue/AbstractVenue.php):

use Venues\Domain\Venue;
 
abstract class AbstractVenue {}

 

3. Prepending “I” or “A”

For the interface (lib/Domain/Venue/IVenue.php):

use Venues\Domain\Venue;
 
interface IVenue {}

And for the abstract (lib/Domain/Venue/AVenue.php):

use Venues\Domain\Venue;
 
abstract class AVenue {}

 

4. Append “Class”

For the interface (lib/Domain/Venue/InterfaceClass.php):

use Venues\Domain\Venue;
 
interface InterfaceClass {}

And for the abstract (lib/Domain/Venue/VenueClass.php):

use Venues\Domain\Venue;
 
abstract class VenueClass {}

 

References:

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

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

PHP Conference 2009

15Oct09

La gente de PHP Barcelona se han animado, como cada año, a montar una la PHP Conference 2009, una conferéncia relacionada con PHP que se celebrará el 30 y 31 de Octubre en el Citilab, en Cornellà. Como podéis ver, el planning parece muy interesante.

Seguramente asistiré, como mínimo el sábado. Para los amantes del Facebook han creado el evento. Si os habéis decidido a venir apuntaros e invitar a todos vuestros colegas.

http://www.facebook.com/event.php?eid=150863109670

De cara a la promoción podéis seguir también a su twitter:

http://twitter.com/phpbarcelona

Han empezado a usar el topic #phpbcn2009 si alguno se anima a hablar de la conference usándolo más promoción para el evento de una manera sana y gratuita.

¡Espero veros ahí!

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

Modificar TITLE desde el código (HTML)

16May09

Por temas de SEO necesito modificar el título de cada página dentro del código, es decir, fuera del <header></header>.

He encontrado esta solución:

<?php
$nombre_titulo="Este es el titulo";
?>
<script language="javascript">
window.document.title = "<?php echo $nombre_titulo; ?>"
</script>

Alguien usa otra manera más cómoda?

3 Comments