Noviembre 10, 2009 - 1:48 pm - Posted by Juan Pablo Romero Bernal
The command line interface (known as cli) is a good tool for most developers, due ten fingers make more things than two. In fact, when we develop web applicactions using the Symfony framework several tasks are made through the command line, for instance: model generation, creation of database schemas, cache clear and so on. This tasks simplify the work in a significant way (if you are a symfony user, you know what i’m talking about).
Of course, this functionality is offered for the php command line interface (the php-cli), that sometimes is not enough to execute some actions such as: watch the object state, perform database inserts (and the typical crud operations), call methods in a interactive way, etc,. I know that some people says: the php cli has a interactive mode (-a option), but i think it is very limited. Talking with others developers, the php interpreter needs an interactive terminal (like python) and it keeps to work with our symfony projects.
The good new is that the facebook team has released (under BSD license) an interactive shell for php interpreter (as their own creators says: ” … ironically written in python”) called phpsh and it’s a great work !. I’ve perform some tests to integrate it with Symfony and i think, it can be a great tool for support and debugging.
Some simple examples:
After we installed phpsh (see the README file), we can work with php sentences and use the common functions:
test$ phpsh
Starting php
type 'h' or 'help' to see instructions & features
php> echo "Hello world"
Hello world
php> $a = 2+3; echo $a
5
php> $f = array('one' => 1, 'two' => 2, 'three' => 3);
php> foreach ($f as $n) { echo $n; }
123
php> foreach ($f as $n) { echo $n."\n"; }
1
2
3
php> foreach ($f as $n) {
... echo $n."\n";
... }
1
2
3
php> echo count($f);
3
Well, but right now, i’ll show you something more interesting: a symfony application using the interactive shell. It not requires additional configuration, just load a file: the frontal controller of your app (in the web directory), for example:
test$ phpsh web/index.php
Starting php with extra includes: ['web/index.php']
.......................
php>
To hide the html output, we can create a copy of this file and avoid the call to dispatch method:
require_once(dirname(__FILE__).'/config/ProjectConfiguration.class.php');
$configuration = ProjectConfiguration::getApplicationConfiguration('frontend','prod', false);
sfContext::createInstance($configuration);
Now, load again (i’ve called shell.php):
test$ phpsh shell.php
Starting php with extra includes: ['shell.php']
type 'h' or 'help' to see instructions & features
php> $c = CityPeer::doSelect(new Criteria);
php> foreach ($c as $city) {
... echo $city."\n";
... }
Barranquilla
Bogota
Berlin
Medellin
php>
As you can see, it can be access to the model classes (i’m sorry with doctrine users) and the Symfony classes. For example, if my file app.yml looks like:
all:
results_per_page: 15
sf_phpmailer:
mailer: true
smtp_auth: true
smtp_secure: "ssl"
host: "smtp.example.com"
port: 600
username: "user"
password: "password"
from: "nobody@example.com"
from_name: "NoBody"
test$ phpsh shell.php
Starting php with extra includes: ['shell.php']
type 'h' or 'help' to see instructions & features
php> $conf = sfConfig::get('app_sf_phpmailer_port');php> echo $conf;
600
php> echo sfConfig::get('app_results_per_page');
15
php>
Well, it’s easy and very interesting. I hope work in detail and make more experiments. That’s all folks !.
Etiquetas: Php, Symfony | Comente »
Noviembre 9, 2009 - 1:23 am - Posted by Juan Pablo Romero Bernal
Para algunos desarrolladores nos es muy cómodo trabajar desde la línea de comandos, ya que diez dedos hacen más que dos. De hecho cuando se desarrollan aplicaciones con Symfony, el uso de la terminal de comandos es fundamental para muchas tareas (generación del modelo, creación de esquemas de base de datos, limpiar la cache, etc,.) que simplifican el trabajo significativamente.
Desde luego, todo esto es gracias a la interfaz en línea de comandos del ínterprete php (más conocido como php-cli), que en algunos casos se queda corto para ejecutar algunas pruebas: ver el estado de un objeto, insertar datos en la base de datos, probar métodos de manera interactiva, etc,. Sé que algunos dirán que php-cli tiene un modo interactivo, pero en realidad desde mi punto de vista es muy limitado. Sería muy interesante contar con algo similar a la terminal interactiva de python y desde luego que se pueda trabajar con nuestros proyectos en Symfony.
Lo mejor de todo, es que la gente de facebook liberó bajo licencia BSD una shell interactiva para php y como sus mismos credadores dicen: “… irónicamente escrita en python ….”; se llama phpsh y realmente es un gran trabajo. He realizado algunas pruebas de integración con Symfony y creo que puede ser de gran apoyo para pruebas y aún más para las personas que están aprendiendo a trabajar con el framework.
A continuación van algunos de los sencillos experimentos realizados:
Una vez se haya instalado phpsh (leer el README), podemos trabajar con sentencias de php y usar las funciones:
test$ phpsh
Starting php
type 'h' or 'help' to see instructions & features
php> echo "Hola mundo"
Hola mundo
php> $a = 2+3; echo $a
5
php> $f = array('uno' => 1, 'dos' => 2, 'tres' => 3);
php> foreach ($f as $n) { echo $n; }
123
php> foreach ($f as $n) { echo $n."\n"; }
1
2
3
php> foreach ($f as $n) {
... echo $n."\n";
... }
1
2
3
php> echo count($f);
3
Bien, pero ahora viene algo un poco más interesante: usar a través del shell interactivo nuestra aplicación hecha en Symfony.
No requiere ninguna configuración especial, simplemente cargar un archivo y listo; se trata del controlador frontal de nuestra aplicación (alguno de los que se encuentra en web), así:
test$ phpsh web/index.php
Starting php with extra includes: ['web/index.php']
.......................
php>
Para obviar la salida html, podemos crear una copia de ese archivo y evitar la llamada al método dispatch(), así:
require_once(dirname(__FILE__).'/config/ProjectConfiguration.class.php');
$configuration = ProjectConfiguration::getApplicationConfiguration('frontend','prod', false);
sfContext::createInstance($configuration);
Ahora, de nuevo lo cargamos (ese archivo lo he llamado shell.php):
test$ phpsh shell.php
Starting php with extra includes: ['shell.php']
type 'h' or 'help' to see instructions & features
php> $c = CiudadPeer::doSelect(new Criteria);
php> foreach ($c as $ciudad) {
... echo $ciudad."\n";
... }
Barranquilla
Bogota
Constantinopla
Medellin
php>
Como se puede ver, puedo acceder a las clases de mi modelo (disculpas a los usuarios de Doctrine) y desde luego a las clases que nos proporciona Symfony, por ejemplo si mi archivo apps/frontend/config/app.yml es:
all:
resultados_por_pagina: 15
sf_phpmailer:
mailer: true
smtp_auth: true
smtp_secure: "ssl"
host: "smtp.mihost"
port: 600
username: "miusuario"
password: "miclave"
from: "nosesabe@example.com"
from_name: "Anonimo"
test$ phpsh shell.php
Starting php with extra includes: ['shell.php']
type 'h' or 'help' to see instructions & features
php> $conf = sfConfig::get('app_sf_phpmailer_port');
php> echo $conf;
600
php> echo sfConfig::get('app_resultados_por_pagina');
15
php>
Bueno, esos han sido los experimentos que he alcanzado a realizar. Espero trabajar más en detalle y publicar los resultados. Hasta una próxima.
Etiquetas: Php, Python, Symfony, Web | 2 Comentarios »