Crear archivos batch en symfony
por tryke en Dic.17, 2008, dentro Symfony
Crear archivos batch con symfony considero que es una de las tareas menos documentadas dentro del framework.
En este post veremos un ejemplo de como hacer un proceso batch para enviar un mailing a todos los usuarios con nuestro boletin.
En primer lugar ejecutaremos el comando init-batch de symfony para que cree el archivo batch.
-
symfony init-batch default [yourBatchName] [yourApplicationName]
El comando crea automaticamente un archivo en el directorio batch de nuestro proyecto.
-
<?php
-
-
/**
-
* yourBatchName batch script
-
*
-
* Here goes a brief description of the purpose of the batch script
-
*
-
* @package yourProject
-
* @subpackage batch
-
* @version $Id$
-
*/
-
-
define('SF_ROOT_DIR', realpath(dirname(__file__).'/..'));
-
define('SF_APP', 'yourApplicationName');
-
define('SF_ENVIRONMENT', 'dev');
-
define('SF_DEBUG', 1);
-
-
require_once(SF_ROOT_DIR.DIRECTORY_SEPARATOR.'apps'.DIRECTORY_SEPARATOR.SF_APP.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'config.php');
-
-
// initialize database manager
-
//$databaseManager = new sfDatabaseManager();
-
//$databaseManager->initialize();
-
-
// batch process here
-
?>
Como podemos observar por defecto te crea un comentario con las llamadas necesarias para inicializar nuestro acceso a la base de datos.
En primer lugar deberemos crearnos un modulo para el envio de emails, a este modulo nosotros lo hemos llamado “email” y la acción “boletin” es la encargada de realizar el envio. En la acción de este modulo leeremos el parametro “usuario_id” que será el que identifica el usuario receptor del mensaje.
actions.class.php
-
<?php
-
class emailActions extends sfActions
-
{
-
public function executeBoletin()
-
{
-
$this->i18n = $this->getContext()->getI18N();
-
$this->usuario = UsuarioPeer::retrieveByPK($this->getRequestParameter('usuario_id'));
-
if (!$this->usuario) {
-
return sfView::NONE;
-
}
-
if (!$this->usuario->getMailavisos()) {
-
return sfView::NONE;
-
}
-
$this->i18n->setCulture($this->usuario->getCulture());
-
-
$this->mail = new sfMail();
-
$this->setMailer('sendmail');
-
$this->setCharset('utf-8');
-
$this->setContentType('text/html');
-
-
$this->mail->setSender('no-reply@miweb.com', 'miweb.com');
-
$this->mail->setFrom('no-reply@miweb.com', 'miweb.com');
-
$this->mail->addAddress($this->usuario->getEmail());
-
$this->mail->setSubject($this->i18n->__('Boletin semanal', null, 'email'));
-
}
-
}
-
?>
Por otro lado montamos el template que será el que contiene el cuerpo del mensaje con el boletin a enviar.
boletinSuccess.php
-
<?php echo sprintf('%s <b>%s</b>', __('Hola', null, 'email'), $usuario->getNombre() ); ?><br>
-
<?php echo __('Este es tu boletin semanal', null, 'email') ?>
Para finalizar solo tenemos que retocar el fichero batch que hemos creado anteriormente para que lea de la base de datos todos los usuarios y vaya enviando el boletin.
batch_boletin.php
-
<?php
-
/**
-
* yourBatchName batch script
-
*
-
* Here goes a brief description of the purpose of the batch script
-
*
-
* @package yourProject
-
* @subpackage batch
-
* @version $Id$
-
*/
-
set_time_limit(0);
-
-
define('SF_ROOT_DIR', realpath(dirname(__file__).'/..'));
-
define('SF_APP', 'yourApplicationName');
-
define('SF_ENVIRONMENT', 'dev');
-
define('SF_DEBUG', 1);
-
define('SF_LOG_DEBUG', 'crit');
-
-
require_once(SF_ROOT_DIR.DIRECTORY_SEPARATOR.'apps'.DIRECTORY_SEPARATOR.SF_APP.DIRECTORY_SEPARATOR.'config'.DIRECTORY_SEPARATOR.'config.php');
-
-
// initialize database manager
-
$databaseManager = new sfDatabaseManager();
-
$databaseManager->initialize();
-
-
// batch process here
-
sfLogger::getInstance()->log('Inicio envio boletin (' . date('Y-m-d H:m:i') . ')…', SF_LOG_DEBUG);
-
-
$c = new Criteria();
-
$usuarios = UsuarioPeer::doSelect($c);
-
-
foreach ($usuarios as $s) {
-
sfContext::getInstance()->getRequest()->setParameter('usuario_id', $s->getId()); //Pasa el usuario por parametro
-
sfContext::getInstance()->getController()->sendEmail('email', 'boletin'); //Envia el email al usuario
-
sfLogger::getInstance()->log('envio boletin: ' . $s->getId(), SF_LOG_DEBUG); //Añado una linea en el log
-
sleep(rand(0,4)); //Espera un máximo de 4s por envio para evitar ser catalogado como spam
-
}
-
-
sfLogger::getInstance()->log('Fin envio boletin (' . date('Y-m-d H:m:i') . ')…', SF_LOG_DEBUG);
-
?>
Si quisieramos podriamos poner nuestro archivo batch_boletin en el cron del servidor para que se ejecutará semanalmente.
Responder
Necesitas estar loginado para hacer un comentario.