Вы находитесь на странице: 1из 90

Frameworks de desarrollo

Symfony
Clase 5

Javier Eguíluz
javier.eguiluz@gmail.com
Esta obra dispone de una licencia de tipo Creative
Commons Reconocimiento‐No comercial‐ Compartir 
bajo la misma licencia 3.0 

Se prohíbe explícitamente el uso de este material en 
actividades de formación comerciales

http://creativecommons.org/licenses/by‐nc‐sa/3.0/es/
This work is licensed under a Creative Commons
Attribution‐Noncommercial‐Share Alike 3.0 

The use of these slides in commercial courses or


trainings is explicitly prohibited

http://creativecommons.org/licenses/by‐nc‐sa/3.0/es/
Capítulo 20

Plugins
Plugins
"forma de agrupar y distribuir un 
subconjunto de archivos de tu proyecto "

• Clases • Tareas
• Helpers • Esquemas de datos
• Configuración • CSS
• Rutas • JavaScript
Estructura de 
archivos
sfJobeetPlugin/
config/
• sfJobeetPluginConfiguration.class.php
• schema.yml
• routing.yml

modules/
job/
actions/
config/
templates/
sfJobeetPlugin/
lib/
Jobeet.class.php
helper/
filter/
form/
model/
task/
web/
$ mkdir plugins/sfJobeetPlugin/config/
$ mv config/schema.yml plugins/sfJobeetPlugin/config/schema.yml

plugins/sfJobeetPlugin/config/ schema.yml
propel:
_attributes:
package: plugins.sfJobeetPlugin.lib.model
... apps/frontend/config/ routing.yml

change_language:
url: /change_language
param: { module: sfJobeetLanguage, action: 
changeLanguage }

localized_homepage:
url: /:sf_culture/
param: { module: sfJobeetJob, action: index }
requirements:
sf_culture: (?:fr|en)

homepage:
url: /
param: { module: sfJobeetJob, action: index }
apps/frontend/config/ settings.yml

all:
.settings:
enabled_modules:
‐ default
‐ sfJobeetAffiliate
‐ sfJobeetApi
‐ sfJobeetCategory
‐ sfJobeetJob
‐ sfJobeetLanguage
config/ProjectConfiguration.class.php

public function setup() {


$this‐>enableAllPluginsExcept(array(
'sfDoctrinePlugin',
'sfCompat10Plugin'
));
}

public function setup() {


$this‐>enablePlugins(array(
'sfPropelPlugin',
'sfGuardPlugin',
'sfFormExtraPlugin',
'sfJobeetPlugin'
));
}
Utilizando los plugins
1. ./symfony plugin:install sfGuardPlugin

2. sfGuardPlugin‐3.1.3.tgz (plugins/)
3. svn:externals (plugins/)
Publicando tu plugin
http://www.symfony‐project.org/plugins
README
Instrucciones de instalación. Formato Markdown

LICENSE
La eliges tu. El sitio oficial sólo muestra los 
plugins con licencias MIT, BSD, LGPL y PHP

package.xml
La definición del paquete. Sigue el formato PEAR
plugins/sfJobeetPlugin/package.xml
<?xml version="1.0" encoding="UTF‐8"?>
<package packagerversion="1.4.1" version="2.0"
xmlns="http://pear.php.net/dtd/package‐2.0"
xmlns:tasks="http://pear.php.net/dtd/tasks‐1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema‐instance"
xsi:schemaLocation="http://pear.php.net/dtd/tasks‐1.0 http://pear.php.net/dtd/tasks‐1.0.xsd
http://pear.php.net/dtd/package‐2.0 http://pear.php.net/dtd/package‐2.0.xsd"
>
<name>sfJobeetPlugin</name>
<channel>plugins.symfony‐project.org</channel>
<summary>A job board plugin.</summary>
<description>A job board plugin.</description>
<lead>
<name>Fabien POTENCIER</name>
<user>fabpot</user>
<email>fabien.potencier@symfony‐project.com</email>
<active>yes</active>
</lead>
<date>2008‐12‐20</date>
...
plugins/sfJobeetPlugin/package.xml
...

<version>
<release>1.0.0</release>
<api>1.0.0</api>
</version>

<stability>
<release>stable</release>
<api>stable</api>
</stability>

<license uri="http://www.symfony‐project.com/license">
MIT license
</license>

<notes />

...
plugins/sfJobeetPlugin/package.xml

...

<contents>
<!‐‐ CONTENT ‐‐>
</contents>

<dependencies>
<!‐‐ DEPENDENCIES ‐‐>
</dependencies>

<phprelease>
</phprelease>

<changelog>
<!‐‐ CHANGELOG ‐‐>
</changelog>
</package>
plugins/sfJobeetPlugin/package.xml

<contents>
<dir name="/">
<file role="data" name="README" />
<file role="data" name="LICENSE" />

<dir name="config">
<file role="data" name="config.php" />
<file role="data" name="schema.yml" />
</dir>

<!‐‐ ... ‐‐>
</dir>
</contents>
plugins/sfJobeetPlugin/package.xml
<dependencies>
<required>
<php>
<min>5.0.0</min>
</php>
<pearinstaller>
<min>1.4.1</min>
</pearinstaller>
<package>
<name>symfony</name>
<channel>pear.symfony‐project.com</channel>
<min>1.2.0</min>
<max>1.3.0</max>
<exclude>1.3.0</exclude>
</package>
</required>
</dependencies> 
<dependencies> plugins/sfJobeetPlugin/package.xml
<required>
<php>
<min>5.0.0</min>
</php>
<pearinstaller>
<min>1.4.1</min>
</pearinstaller>
<package>
<name>symfony</name>
<channel>pear.symfony‐project.com</channel>
<min>1.2.0</min>
<max>1.3.0</max>
<exclude>1.3.0</exclude>
</package>
<package>
<name>sfFooPlugin</name>
<channel>plugins.symfony‐project.org</channel>
<min>1.0.0</min>
<max>1.2.0</max>
<exclude>1.2.0</exclude>
</package>
</required>
</dependencies> 
plugins/sfJobeetPlugin/package.xml
<changelog>
<release>
<version>
<release>1.0.0</release>
<api>1.0.0</api>
</version>
<stability>
<release>stable</release>
<api>stable</api>
</stability>
<license uri="http://www.symfony‐project.com/license">
MIT license
</license>
<date>2008‐12‐20</date>
<license>MIT</license>
<notes>
* fabien: First release of the plugin
</notes>
</release>
</changelog> 
Capítulo 21

El día del diseño
[1] Sensio
[2] P'unk Avenue
[3] centre{source}
[4] OrangeD
[5] Mathijs Beks / qube
[6] Eduardo Martinez Cobos
[7] Christophe Nguyen
Studio Mitsuné
[8] centre{source}
Capítulo 22

La cache
Creando un nuevo 
entorno
apps/frontend/config/settings.yml

prod:
.settings:
cache: on

dev:
.settings:
cache: off

test:
.settings:
cache: off
dev

prod

cli
cache
web/frontend_cache.php
if (!in_array(@$_SERVER['REMOTE_ADDR'], array('127.0.0.1', '::1'))) {
die('Not allowed');
}

require_once(dirname(__FILE__).
'/../config/'.
'ProjectConfiguration.class.php');

$configuration = ProjectConfiguration::getApplicationConfiguration(
'frontend',
'cache',
nombre del 
true); 
entorno
sfContext::createInstance($configuration)‐>dispatch(); 
apps/frontend/config/settings.yml
cache:
.settings:
error_reporting: <?php echo (E_ALL | E_STRICT)."\n" ?>
web_debug:       on
cache:      on
etag:            off

config/databases.yml
cache:
propel:
class: sfPropelDatabase
param:
classname: DebugPDO
Configurando la 
cache
apps/frontend/config/cache.yml
default:
enabled:     off
with_layout: false
lifetime:    86400
Guardando páginas 
en la cache
plugins/sfJobeetJob/modules/sfJobeetJob/config/cache.yml

index:
enabled:     on
with_layout: true
plugins/sfJobeetJob/modules/sfJobeetJob/config/cache.yml

new:
enabled:     on

index:
enabled:     on

all:
with_layout: true
Borrando la cache
$ ./symfony cc

$ ./symfony cc ‐‐type=template ‐‐env=cache


Guardando acciones 
en la cache
plugins/sfJobeetJob/modules/sfJobeetJob/config/cache.yml

new: new:
enabled:     on enabled:     on
index: index:
enabled:     on enabled:     on
all: all:
with_layout: true with_layout: false
Guardando parciales 
y componentes en la 
cache
_language:
enabled:on

_list:
enabled:on
Guardando 
formularios en la 
cache
plugins/sfJobeetJob/lib/form/PluginJobeetJobForm.class.php

abstract class PluginJobeetJobForm extends BaseJobeetJobForm


{
public function __construct(BaseObject $object = null, 
$options = array(), 
$CSRFSecret = null) {
parent::__construct($object, $options, false);
}
// ...
}
plugins/sfJobeetJob/modules/sfJobeetLanguage/actions/components.class.php

class sfJobeetLanguageComponents extends sfComponents {


public function executeLanguage(sfWebRequest $request) {
$this‐>form = new sfFormLanguage(
$this‐>getUser(),
array('languages' => array('en', 'fr'))
);
unset($this‐>form[$this‐>form‐>getCSRFFieldName()]);
}
}
plugins/sfJobeetJob/modules/sfJobeetLanguage/actions/actions.class.php

class sfJobeetLanguageActions extends sfActions {


public function executeChangeLanguage(sfWebRequest $request) {
$form = new sfFormLanguage(
$this‐>getUser(),
array('languages' => array('en', 'fr'))
);
unset($form[$this‐>form‐>getCSRFFieldName()]);
}
}
plugins/sfJobeetJob/modules/sfJobeetJob/config/cache.yml
index:
enabled:  on
lifetime: 600

plugins/sfJobeetJob/modules/sfJobeetJob/actions/actions.class.php

public function executePublish(sfWebRequest $request) {


...
if ($cache = $this‐>getContext()‐>getViewCacheManager())
{
$cache‐>remove('sfJobeetJob/index?sf_culture=*');
$cache‐>remove('sfJobeetCategory/show?id='.
$job‐>getJobeetCategory()‐>getId());
}
...
}
sfContext::getInstance()‐>
getRouting() getRequest()
getResponse() getController()
getStorage() getConfiguration()
getUser() getI18N()
getLogger() getDatabaseConnection()

http://www.symfony‐project.org/api/1_2/sfContext
Capítulo 23

Pasando a 
producción
Preparando el 
servidor de 
producción
check_configuration.php
Aceleradores PHP
Guardan en una cache el "bytecode" 
generado al compilar los scripts de PHP. 
Así no se procesa ni compila el código 
fuente del script en cada petición
Sin acelerador

código  parsear compilar ejecutar


fuente
Con acelerador bytecode
cache
Primera  ejecución

código  parsear compilar ejecutar


fuente
Siguientes ejecuciones

bytecode
cache
1. Instalar ($ pecl install APC)

2. Configurar:
apc.enabled = 1
apc.shm_segments = 1
apc.shm_size = 30
apc.stat = 1

3. Reiniciar Apache
Las librerías de 
Symfony
config/ProjectConfiguration.class.php

require_once dirname(__FILE__).
'/../lib/vendor/'.
'symfony/lib/autoload/'.
'sfCoreAutoload.class.php';
Archivo comprimido (symfony‐1.2.4.tgz)
1. Eliminar archivos anteriores de lib/vendor/
2. Descomprimir el archivo en lib/vendor/

Subversion
$ svn propedit svn:externals lib/vendor/

# symfony http://svn.symfony‐project.com/tags/RELEASE_1_2_1/
# symfony http://svn.symfony‐project.com/branches/1.2
lib/vendor/
symfony/
symfony_test/
config/ProjectConfiguration.class.php
require_once dirname(__FILE__).
'/../lib/vendor/'.
'symfony_test/lib/autoload/'.
'sfCoreAutoload.class.php';
Ajustando la 
configuración
$ ./symfony configure:database "..." usuario pass

$ ./symfony plugin:publish‐assets

apps/frontend/config/settings.yml
all:
.actions:
error_404_module: default
error_404_action: error404
Modificando la 
estructura de 
directorios
config/ProjectConfiguration.class.php

class ProjectConfiguration extends sfProjectConfiguration {


public function setup() {
$this‐>setWebDir(
$this‐>getRootDir().'/public_html'
);
}
}

class ProjectConfiguration extends sfProjectConfiguration {


public function setup() {
$this‐>setCacheDir('/tmp/symfony_cache');
$this‐>setLogDir('/tmp/symfony_logs');
}
}
Las factorías
sfResponse

getResponse()
miRespuesta
factories.yml

otraRespuesta
apps/frontend/config/factories.yml

response:
class: sfWebResponse
param:
logging:           %SF_LOGGING_ENABLED%
charset:           %SF_CHARSET%
send_http_headers: true
apps/frontend/config/factories.yml
request:
class: sfWebRequest
param:
logging:           %SF_LOGGING_ENABLED%
path_info_array:   SERVER
path_info_key:     PATH_INFO
relative_url_root: ~
formats:
txt:  text/plain
js:   [application/javascript, 
application/x‐javascript, 
text/javascript]
css:  text/css
json: [application/json, application/x‐json]
xml:  [text/xml, application/xml, application/x‐xml]
rdf:  application/rdf+xml
atom: application/atom+xml
apps/frontend/config/factories.yml

storage:
class: sfSessionStorage
param:
session_name: symfony
apps/frontend/config/factories.yml

storage:
class: sfPDOSessionStorage
param:
session_name: jobeet
db_table:     session
database:     propel
db_id_col:    id
db_data_col:  data
db_time_col:  time
apps/frontend/config/factories.yml

user:
class: myUser
param:
timeout: 1800
apps/frontend/config/factories.yml

prod:
logger:
class:   sfNoLogger
param:
level:   err
loggers: ~
apps/frontend/config/factories.yml

logger:
class: sfFileLogger
param:
level: error
file:  %SF_LOG_DIR%/%SF_APP%_%SF_ENVIRONMENT%.log

%SF_APP% = sfConfig::get('sf_app')
Instalando 
aplicaciones
Subir todo al servidor de producción
salvo los siguientes directorios:

cache/
log/
web/uploads/
config/properties.ini
[production]
host=www.jobeet.org
port=22
user=jobeet
dir=/var/www/jobeet/
type=rsync
pass= 

$ ./symfony project:deploy production
SSH + rsync
$ ./symfony project:deploy production ‐‐go

config/rsync_exclude.txt
.svn
/web/uploads/*
/cache/*
/log/*
/web/*_dev.php
Capítulo 24

Un repaso a 
Symfony
• ¿Qué es Symfony? • Seguridad

• El modelo • Formularios

• La vista • i18n y l10n

• El controlador • Pruebas

• Configuración • Plugins

• Depuración • Tareas

• Objetos

Вам также может понравиться