SlideShare una empresa de Scribd logo
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
Aquí se cuajó todo:
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
¿De dónde viene esto?
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
Librerías comunes para todos
los proyectos de la agencia
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
wolfwolker JL_Lasopaolacaracola
araquemario almacbe frankey90 driera_comraulo79
gerfignaedytebfodavegmiguelvilata
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
wolfwolker JL_Lasopaolacaracola
araquemario almacbe frankey90 driera_comraulo79
gerfignaedytebfodavegmiguelvilata
Germán Figna
gerfigna
Alfonso Machado
almacbe
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
Sobreescritura y extensión
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
● Bundles
● Controladores
● Templates
● Rutas
● Traducciones
● Validaciones
● Servicios
● Formularios
● Entidades
● Configuraciones
● Resources
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
¿Por qué atender en esta charla?
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
¿Cuál es la motivación?
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
Es lo mismo que hacen
FOSUserBundle, SymfonyCMF o
SonataProject
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
¡Vamos allá!
SOBREESCRITURA Y EXTENSIÓN DE
VALIDACIONES, FORMULARIOS y ENTIDADES.
UN CASO PRÁCTICO
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
UserBundle EcommerceBundle
simple shopping cart
Cart
- user
- createdAt
- ...
CartLine
- cart
- purchasable
- quantity
- ...
Purchasable
- name
- price
- ...
Product
- media
- size
- ...
Ticket
- date
- ...
Book
- isbn
- ...
User
- username
- ...
Vendor
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
Purchasable
- name
- price
- ...
Product
- media
- size
- ...
Book
- isbn
- ...
UserBundle EcommerceBundle
simple shopping cart
Cart
- user
- createdAt
- ...
CartLine
- cart
- purchasable
- quantity
- ...
Ticket
- date
- ...
User
- username
- ...
AppBundle
User
- username
- city
Cart
- user
- createdAt
- ...
CartLine
- cart
- purchasable
- quantity
VendorApp
UserBundle EcommerceBundle
simple shopping cart
CÓMO CREAR THIRD PARTY BUNDLES DE SYMFONY COMPLETAMENTE EXTENSIBLES Y SOBREESCRIBIBLES
Cart
- user
- createdAt
- ...
CartLine
- cart
- purchasable
- quantity
- ...
Purchasable
- name
- price
- ...
Product
- media
- size
- ...
Ticket
- date
- ...
Book
- isbn
- ...
User
- username
- ...
AppBundle
User
- username
- city
Cart
- user
- createdAt
- ...
CartLine
- cart
- purchasable
- quantity
VendorApp
SOBREESCRITURA Y EXTENSIÓN DE
VALIDACIONES, FORMULARIOS y ENTIDADES.
FORMULARIOS
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
EcommerceBundle
PurchasabLeType
- name
- price
- ...
UserBundle
simple shopping cart
UserType
- username
- ...
AppBundle
VendorApp
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
AppBundle
UserBundle EcommerceBundle
AbstractPurchasable
- name
- price
- ...
User
- username
- ...
Car
- ...
Food
- ...
Pen
- ...
simple shopping cart
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
EcommerceBundle
PurchasableType
- name
- price
- ...
UserBundle
simple shopping cart
UserType
- username
- ...
AppBundle
VendorApp
CarType
- color
- ...
UserType
- city
- ...
DECLARADO COMO SERVICIO
FORMULARIOS# 1
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
EcommerceBundle
PurchasableType
- name
- price
- ...
UserBundle
simple shopping cart
UserType
- username
- ...
AppBundle
VendorApp
CarType
- color
- ...
UserType
- city
- ...
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
EcommerceBundle
PurchasableType
- name
- price
- ...
UserBundle
simple shopping cart
UserType
- username
- ...
AppBundle
VendorApp
CarType
- color
- ...
UserType
- city
- ...
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
services:
user_bundle.form.type.usr:
class: UserBundleFormTypeUserType
arguments: ["@my_service"]
tags:
- { name: form.type }
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
services:
user_bundle.form.type.usr:
class: UserBundleFormTypeUserType
arguments: ["@my_service"]
tags:
- { name: form.type }
Como un servicio
SERVICIOS
FORMULARIOS# 1.1
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
1ª Sobreescribir parámetro de la
clase del servicio
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
services:
user_bundle.form.type.user:
class: UserBundleFormTypeUserType
arguments: ["@my_service"]
tags:
- { name: form.type }
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
services:
user_bundle.form.type.user:
class: UserBundleFormTypeUserType
arguments: ["@my_service"]
tags:
- { name: form.type }
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
services:
user_bundle.form.type.user:
class: "%user_bundle.user.class%"
arguments: ["@my_service"]
tags:
- { name: form.type }
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
services:
user_bundle.form.type.user:
class: "%user_bundle.user.class%"
arguments: ["@my_service"]
tags:
- { name: form.type }
W
arning!
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
Symfony Best Practices
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
Parámetros de configuración,
no globales
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
2ª Sobreescribiendo el servicio
creando otro con el mismo id
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
2ª Sobreescribiendo el servicio
creando otro con el mismo id
Muy mala práctica
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
3ª Usando CompilerPass
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
¿Qué es un CompilerPass?
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
Es el modo en que Symfony2 permite
interactuar con los servicio y parámetros
definidos globalmente y de los bundles
cuando han sido cargados, pero antes
de que se hayan compilado y
optimizados en el DependencyInjection
Component (DIC)
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
services:
reusable_bundle.form.type.product:
class: ReusableBundleFormTypeProductType
arguments: ["@my_service"]
tags:
- { name: form.type }
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
// src/Acme/ReusableBundle/DependencyInjection/Compiler/OverrideServiceCompilerPass.php
namespace AcmeReusableBundleDependencyInjectionCompiler;
use SymfonyComponentDependencyInjectionCompilerCompilerPassInterface;
use SymfonyComponentDependencyInjectionContainerBuilder;
class OverrideServiceCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$definition = $container->getDefinition('reusable_bundle.form.type.product');
$definition->setClass('AcmeDemoBundleFormMyProductType');
}
}
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
// src/Acme/ReusableBundle/DependencyInjection/Compiler/OverrideServiceCompilerPass.php
namespace AcmeReusableBundleDependencyInjectionCompiler;
use SymfonyComponentDependencyInjectionCompilerCompilerPassInterface;
use SymfonyComponentDependencyInjectionContainerBuilder;
class OverrideServiceCompilerPass implements CompilerPassInterface
{
public function process(ContainerBuilder $container)
{
$definition = $container->getDefinition('reusable_bundle.form.type.product');
$definition->setClass('AcmeDemoBundleFormMyProductType');
}
}
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
// src/Acme/ReusabeBundle/AcmeReusableBundle.php
class AcmeReusableBundle extends Bundle
{
/**
* @param ContainerBuilder $container
*/
public function build(ContainerBuilder
$container)
{
$container->addCompilerPass(
new OverrideServiceCompilerPass()
);
}
}
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
Volvemos a los Formularios
HERENCIA DE FORMS
FORMULARIOS# 2
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
EcommerceBundle
PurchasableType
- name
- price
- ...
UserBundle
simple shopping cart
UserType
- username
- ...
AppBundle
VendorApp
CarType
- color
- ...
UserType
- city
- ...
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
class MyBookType extends AbstractType
{
...
public function getParent()
{
return PurchasableType::class;
}
}
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
class MyBookType extends PurchasableType
{
...
}
class MyBookType extends AbstractType
{
...
public function getParent()
{
return PurchasableType::class;
}
}
Vs
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
abstract class AbstractType implements FormTypeInterface
{
public function buildForm(FormBuilderInterface $builder, array
$options);
public function buildView(FormView $view, FormInterface $form,
array $options);
public function finishView(FormView $view, FormInterface $form,
array $options);
public function configureOptions(OptionsResolver $resolver);
public function getBlockPrefix();
public function getParent();
}
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
abstract class PurchasableType implements FormTypeInterface
{
public function buildForm(FormBuilderInterface $builder, array
$options);
public function buildView(FormView $view, FormInterface $form,
array $options);
public function finishView(FormView $view, FormInterface $form,
array $options);
public function configureOptions(OptionsResolver $resolver);
public function getBlockPrefix();
public function getParent();
}
SOBREESCRITURA Y EXTENSIÓN DE
VALIDACIONES, FORMULARIOS y ENTIDADES.
VALIDACIONES
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
EcommerceBundle
PurchasableType
- name
- price
- ...
UserBundle
simple shopping cart
UserType
- username
- ...
AppBundle
VendorApp
CarType
- color
- ...
UserType
- city
- ...
¿QUÉ SON?
VALIDACIONES# 1
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
Validator component
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
/**
* @AssertLength(min=2)
*/
private $city;
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
AppBundleEntityAdress:
properties:
city:
- Length:
- min: 2
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
fácil las validaciones, ¿no?
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
pero...
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
¿y cómo sobreescribimos las
validaciones?
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
Symfony dice:
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
“Symfony loads all validation configuration
files from every bundle and combines them
into one validation metadata tree. This
means you are able to add new constraints
to a property, but you cannot override
them.”
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
“To override this, the 3rd party
bundle needs to have
configuration for validation
groups.”
GRUPOS DE VALIDACIÓN
VALIDACIONES# 2
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
class User implements
UserInterface
{
/**
* @AssertEmail(
* groups={"registration"}
* )
*/
private $email;
/**
* @AssertNotBlank(
* groups={"registration"}
* )
* @AssertLength(
* min=7,
* groups={"registration"}
* )
*/
private $password;
/**
* @AssertValid()
* @ORMOneToOne(
* targetEntity="Address",
* mappedBy="address"
* )
*/
private $address;
/**
* @AssertLength(min=2)
*/
private $city;
}
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
class User implements
UserInterface
{
/**
* @AssertEmail(
* groups={"registration"}
* )
*/
private $email;
/**
* @AssertNotBlank(
* groups={"registration"}
* )
* @AssertLength(
* min=7,
* groups={"registration"}
* )
*/
private $password;
/**
* @AssertValid()
* @ORMOneToOne(
* targetEntity="Address",
* mappedBy="address"
* )
*/
private $address;
/**
* @AssertLength(min=2)
*/
private $city;
}
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
¿Cuántos grupos de validación
hay para la clase User?
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
registration
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
class User implements
UserInterface
{
/**
* @AssertEmail(
* groups={"registration"}
* )
*/
private $email;
/**
* @AssertNotBlank(
* groups={"registration"}
* )
* @AssertLength(
* min=7,
* groups={"registration"}
* )
*/
private $password;
/**
* @AssertValid()
* @ORMOneToOne(
* targetEntity="Address",
* mappedBy="address"
* )
*/
private $address;
/**
* @AssertLength(min=2)
*/
private $city;
}
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
class User implements
UserInterface
{
/**
* @AssertEmail(
* groups={"registration"}
* )
*/
private $email;
/**
* @AssertNotBlank(
* groups={"registration"}
* )
* @AssertLength(
* min=7,
* groups={"registration"}
* )
*/
private $password;
/**
* @AssertValid()
* @ORMOneToOne(
* targetEntity="Address",
* mappedBy="address"
* )
*/
private $address;
/**
* @AssertLength(min=2)
*/
private $city;
}
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
Default
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
class User implements
UserInterface
{
/**
* @AssertEmail(
* groups={"registration"}
* )
*/
private $email;
/**
* @AssertNotBlank(
* groups={"registration"}
* )
* @AssertLength(
* min=7,
* groups={"registration"}
* )
*/
private $password;
/**
* @AssertValid()
* @ORMOneToOne(
* targetEntity="Address",
* mappedBy="address"
* )
*/
private $address;
/**
* @AssertLength(min=2)
*/
private $city;
}
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
class User implements
UserInterface
{
/**
* @AssertEmail(
* groups={"registration"}
* )
*/
private $email;
/**
* @AssertNotBlank(
* groups={"registration"}
* )
* @AssertLength(
* min=7,
* groups={"registration"}
* )
*/
private $password;
/**
* @AssertValid()
* @ORMOneToOne(
* targetEntity="Address",
* mappedBy="address"
* )
*/
private $address;
/**
* @AssertLength(min=2)
*/
private $city;
}
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
class User implements
UserInterface
{
/**
* @AssertEmail(
* groups={"registration"}
* )
*/
private $email;
/**
* @AssertNotBlank(
* groups={"registration"}
* )
* @AssertLength(
* min=7,
* groups={"registration"}
* )
*/
private $password;
/**
* @AssertValid()
* @ORMOneToOne(
* targetEntity="Address",
* mappedBy="address"
* )
*/
private $address;
/**
* @AssertLength(min=2)
*/
private $city;
}
?
?
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
class User implements
UserInterface
{
/**
* @AssertEmail(
* groups={"registration"}
* )
*/
private $email;
/**
* @AssertNotBlank(
* groups={"registration"}
* )
* @AssertLength(
* min=7,
* groups={"registration"}
* )
*/
private $password;
/**
* @AssertValid()
* @ORMOneToOne(
* targetEntity="Address",
* mappedBy="address"
* )
*/
private $address;
/**
* @AssertLength(min=2)
*/
private $city;
}
?
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
class User implements
UserInterface
{
/**
* @AssertEmail(
* groups={"registration"}
* )
*/
private $email;
/**
* @AssertNotBlank(
* groups={"registration"}
* )
* @AssertLength(
* min=7,
* groups={"registration"}
* )
*/
private $password;
/**
* @AssertValid()
* @ORMOneToOne(
* targetEntity="Address",
* mappedBy="address"
* )
*/
private $address;
/**
* @AssertLength(min=2)
*/
private $city;
}
?
Depende...
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
class User implements
UserInterface
{
/**
* @AssertEmail(
* groups={"registration"}
* )
*/
private $email;
/**
* @AssertNotBlank(
* groups={"registration"}
* )
* @AssertLength(
* min=7,
* groups={"registration"}
* )
*/
private $password;
/**
* @AssertValid()
* @ORMOneToOne(
* targetEntity="Address",
* mappedBy="address"
* )
*/
private $address;
/**
* @AssertLength(min=2)
*/
private $city;
}
?
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
class User implements
UserInterface
{
/**
* @AssertEmail(
* groups={"registration"}
* )
*/
private $email;
/**
* @AssertNotBlank(
* groups={"registration"}
* )
* @AssertLength(
* min=7,
* groups={"registration"}
* )
*/
private $password;
/**
* @AssertValid()
* @ORMOneToOne(
* targetEntity="Address",
* mappedBy="address"
* )
*/
private $address;
/**
* @AssertLength(min=2)
*/
private $city;
}
Depende...
?
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
class User implements
UserInterface
{
/**
* @AssertEmail(
* groups={"registration"}
* )
*/
private $email;
/**
* @AssertNotBlank(
* groups={"registration"}
* )
* @AssertLength(
* min=7,
* groups={"registration"}
* )
*/
private $password;
/**
* @AssertValid()
* @ORMOneToOne(
* targetEntity="Address",
* mappedBy="address"
* )
*/
private $address;
/**
* @AssertLength(min=2)
*/
private $city;
}
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
User
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
class User implements
UserInterface
{
/**
* @AssertEmail(
* groups={"registration"}
* )
*/
private $email;
/**
* @AssertNotBlank(
* groups={"registration"}
* )
* @AssertLength(
* min=7,
* groups={"registration"}
* )
*/
private $password;
/**
* @AssertValid()
* @ORMOneToOne(
* targetEntity="Address",
* mappedBy="address"
* )
*/
private $address;
/**
* @AssertLength(min=2)
*/
private $city;
}
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
class User implements
UserInterface
{
/**
* @AssertEmail(
* groups={"registration"}
* )
*/
private $email;
/**
* @AssertNotBlank(
* groups={"registration"}
* )
* @AssertLength(
* min=7,
* groups={"registration"}
* )
*/
private $password;
/**
* @AssertValid()
* @ORMOneToOne(
* targetEntity="Address",
* mappedBy="address"
* )
*/
private $address;
/**
* @AssertLength(min=2)
*/
private $city;
}
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
class User implements
UserInterface
{
/**
* @AssertEmail(
* groups={"registration"}
* )
*/
private $email;
/**
* @AssertNotBlank(
* groups={"registration"}
* )
* @AssertLength(
* min=7,
* groups={"registration"}
* )
*/
private $password;
/**
* @AssertValid()
* @ORMOneToOne(
* targetEntity="Address",
* mappedBy="address"
* )
*/
private $address;
/**
* @AssertLength(min=2)
*/
private $city;
}
?
?
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
class User implements
UserInterface
{
/**
* @AssertEmail(
* groups={"registration"}
* )
*/
private $email;
/**
* @AssertNotBlank(
* groups={"registration"}
* )
* @AssertLength(
* min=7,
* groups={"registration"}
* )
*/
private $password;
/**
* @AssertValid()
* @ORMOneToOne(
* targetEntity="Address",
* mappedBy="address"
* )
*/
private $address;
/**
* @AssertLength(min=2)
*/
private $city;
}
?
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
class User implements
UserInterface
{
/**
* @AssertEmail(
* groups={"registration"}
* )
*/
private $email;
/**
* @AssertNotBlank(
* groups={"registration"}
* )
* @AssertLength(
* min=7,
* groups={"registration"}
* )
*/
private $password;
/**
* @AssertValid()
* @ORMOneToOne(
* targetEntity="Address",
* mappedBy="address"
* )
*/
private $address;
/**
* @AssertLength(min=2)
*/
private $city;
}
?
Depende...
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
class User implements
UserInterface
{
/**
* @AssertEmail(
* groups={"registration"}
* )
*/
private $email;
/**
* @AssertNotBlank(
* groups={"registration"}
* )
* @AssertLength(
* min=7,
* groups={"registration"}
* )
*/
private $password;
/**
* @AssertValid()
* @ORMOneToOne(
* targetEntity="Address",
* mappedBy="address"
* )
*/
private $address;
/**
* @AssertLength(min=2)
*/
private $city;
}
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
- “Dos grupos por defecto”:
- { NombreClase, Default }
- Si se especifica un grupo, NO se
añaden “los por defecto”
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
Warning!
- Si se valida una clase con el grupo de
validación del nombre de la clase y las
relaciones también se validan.
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
Y…?
VALIDACIÓN EN FORMULARIOS
VALIDACIONES# 3
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
¿Recordamos lo que hemos
hablado de formularios y
servicios?
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
acme_reusable:
user:
form:
type: AcmeReusableBundleFormTypeUserType
validation_groups: [registration, Default]
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
class FormFactory implements FactoryInterface
{
private $formFactory;
private $name;
private $type;
private $validationGroups;
public function __construct(FormFactoryInterface $formFactory,
$name, $type, array $validationGroups = null)
{
$this->formFactory = $formFactory;
$this->name = $name;
$this->type = $type;
$this->validationGroups = $validationGroups;
}
public function createForm(array $options = array())
{
$options = array_merge(array('validation_groups' =>
$this->validationGroups), $options);
return $this->formFactory->createNamed($this->name, $this->type,
null, $options);
}
}
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
class FormFactory implements FactoryInterface
{
private $formFactory;
private $name;
private $type;
private $validationGroups;
public function __construct(FormFactoryInterface $formFactory,
$name, $type, array $validationGroups = null)
{
$this->formFactory = $formFactory;
$this->name = $name;
$this->type = $type;
$this->validationGroups = $validationGroups;
}
public function createForm(array $options = array())
{
$options = array_merge(array('validation_groups' =>
$this->validationGroups), $options);
return $this->formFactory->createNamed($this->name, $this->type,
null, $options);
}
}
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
class FormFactory implements FactoryInterface
{
private $formFactory;
private $name;
private $type;
private $validationGroups;
public function __construct(FormFactoryInterface $formFactory,
$name, $type, array $validationGroups = null)
{
$this->formFactory = $formFactory;
$this->name = $name;
$this->type = $type;
$this->validationGroups = $validationGroups;
}
public function createForm(array $options = array())
{
$options = array_merge(array('validation_groups' =>
$this->validationGroups), $options);
return $this->formFactory->createNamed($this->name, $this->type,
null, $options);
}
}
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
<service id="acme_reusable.user.form.factory"
class="AcmeReusableBundleFormFactoryFormFactory">
<argument type="service" id="form.factory" />
<argument>%acme_reusable.user.form.name%</argument>
<argument>%acme_reusable.user.form.type%</argument>
<argument>%acme_reusable.user.form.validation_groups%</argument>
</service>
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
$formFactory = $this->get(acme_reusable.user.form.factory');
$form = $formFactory->createForm();
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
En definitiva...
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
$form = $this->createFormBuilder($user, array(
'validation_groups' => array(Create, 'Default'),
))->add(...)->getForm();
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
$form = $this->createFormBuilder($user, array(
'validation_groups' => array(Create, 'Default'),
))->add(...)->getForm();
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
$form = $this->createFormBuilder($user, array(
'validation_groups' => $validationGroupFromParameter,
))->add(...)->getForm();
VALIDACIÓN DE CLASES
VALIDACIONES#4
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
$errors = $validator
->validate($user, null, array('registration', 'Default'));
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
$errors = $validator
->validate($user, null, array('registration', 'Default'));
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
$errors = $validator
->validate($user, null, $validationGroupFromParameter);
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
¿MUCHA
INFORMACIÓN?
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
¿ABURRIDO?
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
¿SUEÑO?
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
TOMA AIRE ...
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
… RESPIRA ...
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
… Y PREPÁRATE ...
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
¡RELEVO!
SOBREESCRITURA Y EXTENSIÓN DE
VALIDACIONES, FORMULARIOS y ENTIDADES.
ENTITY MAPPING
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
Due to the way Doctrine works, it is not
possible to override entity mapping of a
bundle. However, if a bundle provides a
mapped superclass (such as the User entity
in the FOSUserBundle) one can override
attributes and associations. Learn more
about this feature and its limitations in the
Doctrine documentation.
http://symfony.com/doc/current/cookbook/bundles/override.html#entities-entity-mapping
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
EMPECEMOS DESDE CERO
SOBREESCRITURA Y EXTENSIÓN DE
VALIDACIONES, FORMULARIOS y ENTIDADES.
DOCTRINE2
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
SOBREESCRITURA Y EXTENSIÓN DE
VALIDACIONES, FORMULARIOS y ENTIDADES.
CÓMO PROVEER MAPPING
METADATA
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
# Resources/config/doctrine/User.orm.xml
<doctrine-mapping ...>
<mapped-superclass name="FOSUserBundleEntityUser">
...
<field
name="username"
column="username"
type="string"
length="255" />
…
</mapped-superclass>
</doctrine-mapping>
XML:
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
# Resources/config/doctrine/User.orm.yml
DoctrineTestsORMMappingUser:
type: entity
table: cms_users
...
fields:
username:
type: string
length: 50
...
YML:
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
<?php
/** @Entity */
class User
{
/** @Column(type="string", length=100) */
private $username;
...
}
Annotations:
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
Mapping:
En un bundle no pueden
convivir formatos
XML > YML > Annotations
SOBREESCRITURA Y EXTENSIÓN DE
VALIDACIONES, FORMULARIOS y ENTIDADES.
MAPPED-SUPERCLASS
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
Clase Abstracta o concreta
Su finalidad es definir información de mapeo que van a
heredar otras entidades
Mapped-Superclass:
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
# Model/User.php
abstract class User
{
protected $username;
…
}
# Resources/config/doctrine-mapping/User.orm.xml
<mapped-superclass name="FOSUserBundleModelUser">
<field name="username"
column="username"
type="string"
length="180" />
…
</mapped-superclass>
SOBREESCRITURA Y EXTENSIÓN DE
VALIDACIONES, FORMULARIOS y ENTIDADES.
PRIMERA APROXIMACIÓN
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
AppBundle
UserBundle EcommerceBundle
Primera aproximación
AbstractCart
- user
- createdAt
- ...
AbstractCartLine
- cart
- purchasable
- quantity
- ...
AbstractPurchasable
- name
- price
- ...
AbstractUser
- username
- ...
Cart
- ...
CartLine
- ...
Product
- ...
User
- ...
VendorApp
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
Primera aproximación
Pero....
- Obligamos a extender todas las entidades
- Obligamos a escribir el mapeo de las relaciones
SOBREESCRITURA Y EXTENSIÓN DE
VALIDACIONES, FORMULARIOS y ENTIDADES.
SEGUNDA APROXIMACIÓN
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
UserBundle EcommerceBundle
Segunda aproximación
AbstractCart
- user
- createdAt
- ...
AbstractCartLine
- cart
- purchasable
- quantity
- ...
AbstractPurchasable
- name
- price
- ...
AbstractUser
- username
- ...
Cart
- ...
CartLine
- ...
Product
- ...
User
- ...
Vendor
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
AppBundle
UserBundle EcommerceBundle
Segunda aproximación
CÓMO CREAR THIRD PARTY BUNDLES DE SYMFONY COMPLETAMENTE EXTENSIBLES Y SOBREESCRIBIBLES
AbstractCart
- user
- createdAt
- ...
AbstractCartLine
- cart
- purchasable
- quantity
- ...
AbstractPurchasable
- name
- price
- ...
AbstractUser
- username
- ...
Cart
- ...
CartLine
- ...
Product
- ...
User
- ...
VendorApp
Cart
- ...
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
Segunda aproximación
CÓMO CREAR THIRD PARTY BUNDLES DE SYMFONY COMPLETAMENTE EXTENSIBLES Y SOBREESCRIBIBLES
● Ofrecer clases concretas en el bundle
● Permitir que por parámetros en la capa de aplicación se
indique qué clases concretas usar
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
Segunda aproximación
CÓMO CREAR THIRD PARTY BUNDLES DE SYMFONY COMPLETAMENTE EXTENSIBLES Y SOBREESCRIBIBLES
● Ofrecer clases concretas en el bundle
● Permitir que por parámetros en la capa de aplicación se
indique qué clases concretas usar
Implica....
● Que el bundle decida si tiene que mapear o no las entidades
concretas
● Establecer dinámicamente las relaciones entre entidades
SOBREESCRITURA Y EXTENSIÓN DE
VALIDACIONES, FORMULARIOS y ENTIDADES.
AUTO MAPPING
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
Auto Mapping
- Doctrine busca entidades en la carpeta Entity de todos los
bundles
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
Auto Mapping
- Doctrine busca entidades en la carpeta Entity de todos los
bundles
- Busca la información de mapeo en
- Resources/config/doctrine/
- Anotaciones
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
Auto Mapping
- Doctrine busca entidades en la carpeta Entity de todos los
bundles
- Busca la información de mapeo en
- Resources/config/doctrine/
- Anotaciones
- Activado por defecto, pero nuestro bundle tiene que
funcionar independientemente de su estado.
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
Solución:
- Mover las entidades concretas del bundle a otro directorio
- Ej.: Model
- Mover la información de mapeo
- Ej.: Resource/config/doctrine-model
Segunda aproximación
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
¿Cómo mapeo las entidades?
Segunda aproximación
SOBREESCRITURA Y EXTENSIÓN DE
VALIDACIONES, FORMULARIOS y ENTIDADES.
DoctrineOrmMappingPass
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
$container->addCompilerPass(
new DoctrineOrmMappingsPass(
$driver, //DoctrineORMMappingDriverXmlDriver
array('AcmeReusableBundleModelCart'),
array('doctrine.default_entity_manager'),
"boolean_param_name"
)
);
Segunda aproximación
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
$container->addCompilerPass(
new DoctrineOrmMappingsPass(
$driver, //DoctrineORMMappingDriverXmlDriver
array('AcmeReusableBundleModelCart'),
array('acme_reusable.model_manager_name'),
"acme_reusable.tengo_que_mapear_la_clase_cart"
)
);
Segunda aproximación
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
AbstractCart
- user
- createdAt
- ...
AppBundle
UserBundle EcommerceBundle
Segunda aproximación
AbstractCartLine
- cart
- purchasable
- quantity
- ...
AbstractPurchasable
- name
- price
- ...
AbstractUser
- username
- ...
Cart
- ...
CartLine
- ...
Product
- ...
User
- ...
VendorApp
Cart
- ...
SOBREESCRITURA Y EXTENSIÓN DE
VALIDACIONES, FORMULARIOS y ENTIDADES.
MAP TO ABSTRACT AND
INTERFACES
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
# Resources/config/doctrine-base/AbstractCartLine.orm.xml
<mapped-superclass
name="AcmeReusableBundleModelAbstractCartLine">
...
<many-to-one
target-entity="AcmeReusableBundleEntityAbstractPurchasable"
field="purchasable" />
<many-to-one
target-entity="AcmeReusableBundleModelInterfacesCartInterface"
inversed-by="cartLines"
field="cart"/>
...
</mapped-superclass>
Segunda aproximación
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
# Resources/config/doctrine-base/AbstractCartLine.orm.xml
<mapped-superclass
name="AcmeReusableBundleModelAbstractCartLine">
...
<many-to-one
target-entity="AcmeReusableBundleEntityAbstractPurchasable"
field="purchasable" />
<many-to-one
target-entity="AcmeReusableBundleModelInterfacesCartInterface"
inversed-by="cartLines"
field="cart"/>
...
</mapped-superclass>
Segunda aproximación
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
# app/config/config.yml
doctrine:
orm:
resolve_target_entities:
CartInterface: AppBundleEntityCart
Segunda aproximación
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
# DependencyInjection/AcmeReusableExtension.php
public function prepend(ContainerBuilder $container)
{
…
$doctrineConfig = array(
'orm' => array(
'resolve_target_entities' => array(
'CartInterface' => $config['class']['cart'],
),
),
);
$container->prependExtensionConfig('doctrine', $doctrineConfig);
...
}
Segunda aproximación
CÓMO CREAR THIRD PARTY BUNDLES DE SYMFONY COMPLETAMENTE EXTENSIBLES Y SOBREESCRIBIBLES
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
AppBundle
UserBundle EcommerceBundle
Segunda aproximación
AbstractCart
- user
- createdAt
- ...
AbstractCartLine
- cart
- purchasable
- quantity
- ...
AbstractPurchasable
- name
- price
- ...
AbstractUser
- username
- ...
Cart
- ...
CartLine
- ...
Product
- ...
User
- ...
VendorApp
Cart
- ...
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
# Resources/config/doctrine-base/AbstractCartLine.orm.xml
<mapped-superclass name="AbstractCartLine">
...
<many-to-one
target-entity="CartInterface"
inversed-by="cartLines"
field="cart" />
...
</mapped-superclass>
Segunda aproximación
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
# Resources/config/doctrine-base/AbstractCart.orm.xml
<mapped-superclass name="AcmeReusableBundleEntityAbstractCart">
...
<one-to-many
field="cartLines"
target-entity="CartLineInterface"
mapped-by="cart"
/>
...
</mapped-superclass>
Segunda aproximación
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
# Resources/config/doctrine-base/AbstractCart.orm.xml
<mapped-superclass name="AcmeReusableBundleEntityAbstractCart">
...
<one-to-many
field="cartLines"
target-entity="CartLineInterface"
mapped-by="cart"
/>
...
</mapped-superclass>
Segunda aproximación
No se puede
SOBREESCRITURA Y EXTENSIÓN DE
VALIDACIONES, FORMULARIOS y ENTIDADES.
loadClassMetadata
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
// EventListener/MappingSubscriber.php
public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs)
{
$classMetadata = $eventArgs->getClassMetadata();
if ($classMetadata->reflClass === $this->cartClass) {
$classMetadata->mapOneToMany(array(
'fieldName' => 'cartLines',
'targetEntity' => $this->cartLineClass,
'cascade' => array(1 => 'all'),
'mappedBy' => 'cart',
));
}
}
Segunda aproximación
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
// EventListener/MappingSubscriber.php
public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs)
{
$classMetadata = $eventArgs->getClassMetadata();
if ($classMetadata->reflClass === $this->cartClass) {
$classMetadata->mapOneToMany(array(
'fieldName' => 'cartLines',
'targetEntity' => $this->cartLineClass,
'cascade' => array(1 => 'all'),
'mappedBy' => 'cart',
));
}
}
Segunda aproximación
SOBREESCRITURA Y EXTENSIÓN DE
VALIDACIONES, FORMULARIOS y ENTIDADES.
Resumiendo
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
Resumiendo:
- Usamos DoctrineOrmMappingPass para mapear las clases
concretas de nuestro bundle, en función de los parámetros de
configuración
Segunda aproximación
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
Resumiendo:
- Usamos DoctrineOrmMappingPass para mapear las clases
concretas de nuestro bundle, en función de los parámetros de
configuración
- Apuntamos las relaciones de las clases abstractas hacia
Interfaces, para poder hacer que se apunte a la clase de
destino con resolve_target_entity
Segunda aproximación
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
Resumiendo:
- Usamos DoctrineOrmMappingPass para mapear las clases
concretas de nuestro bundle, en función de los parámetros de
configuración
- Apuntamos las relaciones de las clases abstractas hacia
Interfaces, para poder hacer que se apunte a la clase de
destino con resolve_target_entity
- Usamos el evento loadClassMetadata para completar las
relaciones bidireccionales
Segunda aproximación
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
AppBundle
UserBundle EcommerceBundle
CartLine
- cart
- purchasable
- quantity
- ...
AbstractPurchasable
- name
- price
- ...
Segunda aproximación
User
- username
- ...
Cart
- customField
SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
Un ejemplo:
https://github.com/dualhand/ReusableBundle
https://github.com/dualhand/example-app
GRACIAS
Alfonso Machado
almacbe
Germán Figna
gerfigna

Más contenido relacionado

Similar a Sobreescritura y extensión de validaciones, formularios y entidades

2005 la situacion de las agencias de publicidad en España
2005 la situacion de las agencias de publicidad en España       2005 la situacion de las agencias de publicidad en España
2005 la situacion de las agencias de publicidad en España
La estrategia de las 15 paginas
 
LA FUNCIÓN COMERCIAL DE LA EMPRESA
LA FUNCIÓN COMERCIAL DE LA EMPRESALA FUNCIÓN COMERCIAL DE LA EMPRESA
LA FUNCIÓN COMERCIAL DE LA EMPRESA
aarasha013
 
Trabajo sobre la franquicia. modelos de internacionalización de la empresa
Trabajo sobre la franquicia. modelos de internacionalización de la empresaTrabajo sobre la franquicia. modelos de internacionalización de la empresa
Trabajo sobre la franquicia. modelos de internacionalización de la empresa
Carlos Alonso Rodríguez ☁
 
Semana 4 - Go to market, márgenes, Push y Pull.pdf
Semana 4 - Go to market, márgenes, Push y Pull.pdfSemana 4 - Go to market, márgenes, Push y Pull.pdf
Semana 4 - Go to market, márgenes, Push y Pull.pdf
fernanduca191817
 
Repaso de los contenidos del examen del ii parcial emprendimiento 1 y 2
Repaso de los contenidos del examen del ii parcial emprendimiento 1 y 2Repaso de los contenidos del examen del ii parcial emprendimiento 1 y 2
Repaso de los contenidos del examen del ii parcial emprendimiento 1 y 2
LISBETHSARAIMALDONAD1
 
Allstartup. Adaptación del modelo de negocio y Business Model Canvas
Allstartup. Adaptación del modelo de negocio y Business Model CanvasAllstartup. Adaptación del modelo de negocio y Business Model Canvas
Allstartup. Adaptación del modelo de negocio y Business Model Canvas
Flan *
 
Tienda Carlitos
Tienda CarlitosTienda Carlitos
Tienda Carlitos
powerwilson
 
Trabajo autonomo
Trabajo autonomoTrabajo autonomo
Trabajo autonomo
brimaite
 
Trabajo autonomo
Trabajo autonomoTrabajo autonomo
Trabajo autonomo
andbri
 
Repaso de los contenidos del examen del ii parcial administracion general
Repaso de los contenidos del examen del ii parcial administracion generalRepaso de los contenidos del examen del ii parcial administracion general
Repaso de los contenidos del examen del ii parcial administracion general
LISBETHSARAIMALDONAD1
 
Presentación Fairway Andrés Romero
Presentación Fairway Andrés Romero Presentación Fairway Andrés Romero
Presentación Fairway Andrés Romero
Andrés Romero Montero
 
Cyl Contadores Ltda.
Cyl Contadores  Ltda.Cyl Contadores  Ltda.
Cyl Contadores Ltda.
Cristian
 
Taller modelo de negocios
Taller modelo de negociosTaller modelo de negocios
Taller modelo de negocios
Acelerador de Empresas de Panamá
 
Presentacion reciproco 2012
Presentacion reciproco 2012Presentacion reciproco 2012
Presentacion reciproco 2012
Mariano BAzterrica
 
Taller práctico de Marketing Online aplicado a la empresa en Albatera Emprende
Taller práctico de Marketing Online aplicado a la empresa en Albatera EmprendeTaller práctico de Marketing Online aplicado a la empresa en Albatera Emprende
Taller práctico de Marketing Online aplicado a la empresa en Albatera Emprende
📊 Isidro Pérez Ramón
 
Curso de Estrategias de Distribución y Canales 03 La Distribución y sus Dimen...
Curso de Estrategias de Distribución y Canales 03 La Distribución y sus Dimen...Curso de Estrategias de Distribución y Canales 03 La Distribución y sus Dimen...
Curso de Estrategias de Distribución y Canales 03 La Distribución y sus Dimen...
LEOnardo AMARaldo DELgado
 
Travel Advisors oct2010 Bilbao conocimiento
Travel Advisors oct2010 Bilbao conocimientoTravel Advisors oct2010 Bilbao conocimiento
Travel Advisors oct2010 Bilbao conocimiento
MindProject
 
Autoevaluacion
AutoevaluacionAutoevaluacion
Autoevaluacion
mariapolancomedina
 
Proyecto GAES Contabilidad Viva
Proyecto GAES Contabilidad VivaProyecto GAES Contabilidad Viva
Proyecto GAES Contabilidad Viva
Chicos Sena
 
Coopaliments[2]
Coopaliments[2]Coopaliments[2]
Coopaliments[2]
yamilediaz
 

Similar a Sobreescritura y extensión de validaciones, formularios y entidades (20)

2005 la situacion de las agencias de publicidad en España
2005 la situacion de las agencias de publicidad en España       2005 la situacion de las agencias de publicidad en España
2005 la situacion de las agencias de publicidad en España
 
LA FUNCIÓN COMERCIAL DE LA EMPRESA
LA FUNCIÓN COMERCIAL DE LA EMPRESALA FUNCIÓN COMERCIAL DE LA EMPRESA
LA FUNCIÓN COMERCIAL DE LA EMPRESA
 
Trabajo sobre la franquicia. modelos de internacionalización de la empresa
Trabajo sobre la franquicia. modelos de internacionalización de la empresaTrabajo sobre la franquicia. modelos de internacionalización de la empresa
Trabajo sobre la franquicia. modelos de internacionalización de la empresa
 
Semana 4 - Go to market, márgenes, Push y Pull.pdf
Semana 4 - Go to market, márgenes, Push y Pull.pdfSemana 4 - Go to market, márgenes, Push y Pull.pdf
Semana 4 - Go to market, márgenes, Push y Pull.pdf
 
Repaso de los contenidos del examen del ii parcial emprendimiento 1 y 2
Repaso de los contenidos del examen del ii parcial emprendimiento 1 y 2Repaso de los contenidos del examen del ii parcial emprendimiento 1 y 2
Repaso de los contenidos del examen del ii parcial emprendimiento 1 y 2
 
Allstartup. Adaptación del modelo de negocio y Business Model Canvas
Allstartup. Adaptación del modelo de negocio y Business Model CanvasAllstartup. Adaptación del modelo de negocio y Business Model Canvas
Allstartup. Adaptación del modelo de negocio y Business Model Canvas
 
Tienda Carlitos
Tienda CarlitosTienda Carlitos
Tienda Carlitos
 
Trabajo autonomo
Trabajo autonomoTrabajo autonomo
Trabajo autonomo
 
Trabajo autonomo
Trabajo autonomoTrabajo autonomo
Trabajo autonomo
 
Repaso de los contenidos del examen del ii parcial administracion general
Repaso de los contenidos del examen del ii parcial administracion generalRepaso de los contenidos del examen del ii parcial administracion general
Repaso de los contenidos del examen del ii parcial administracion general
 
Presentación Fairway Andrés Romero
Presentación Fairway Andrés Romero Presentación Fairway Andrés Romero
Presentación Fairway Andrés Romero
 
Cyl Contadores Ltda.
Cyl Contadores  Ltda.Cyl Contadores  Ltda.
Cyl Contadores Ltda.
 
Taller modelo de negocios
Taller modelo de negociosTaller modelo de negocios
Taller modelo de negocios
 
Presentacion reciproco 2012
Presentacion reciproco 2012Presentacion reciproco 2012
Presentacion reciproco 2012
 
Taller práctico de Marketing Online aplicado a la empresa en Albatera Emprende
Taller práctico de Marketing Online aplicado a la empresa en Albatera EmprendeTaller práctico de Marketing Online aplicado a la empresa en Albatera Emprende
Taller práctico de Marketing Online aplicado a la empresa en Albatera Emprende
 
Curso de Estrategias de Distribución y Canales 03 La Distribución y sus Dimen...
Curso de Estrategias de Distribución y Canales 03 La Distribución y sus Dimen...Curso de Estrategias de Distribución y Canales 03 La Distribución y sus Dimen...
Curso de Estrategias de Distribución y Canales 03 La Distribución y sus Dimen...
 
Travel Advisors oct2010 Bilbao conocimiento
Travel Advisors oct2010 Bilbao conocimientoTravel Advisors oct2010 Bilbao conocimiento
Travel Advisors oct2010 Bilbao conocimiento
 
Autoevaluacion
AutoevaluacionAutoevaluacion
Autoevaluacion
 
Proyecto GAES Contabilidad Viva
Proyecto GAES Contabilidad VivaProyecto GAES Contabilidad Viva
Proyecto GAES Contabilidad Viva
 
Coopaliments[2]
Coopaliments[2]Coopaliments[2]
Coopaliments[2]
 

Último

MONOGRAFRIA GOOGLE (grupo 1ro de google).pdf
MONOGRAFRIA GOOGLE (grupo 1ro de google).pdfMONOGRAFRIA GOOGLE (grupo 1ro de google).pdf
MONOGRAFRIA GOOGLE (grupo 1ro de google).pdf
darilpisco021
 
FICHA DE EDUCACIÓN RELIGIOSA 17 DE CTUBRE LA oracion.docx
FICHA DE EDUCACIÓN RELIGIOSA  17 DE CTUBRE LA  oracion.docxFICHA DE EDUCACIÓN RELIGIOSA  17 DE CTUBRE LA  oracion.docx
FICHA DE EDUCACIÓN RELIGIOSA 17 DE CTUBRE LA oracion.docx
EmilyEsmeraldaQuispe
 
extraccion-de-alcaloides-de-la-planta-de-coca.pdf
extraccion-de-alcaloides-de-la-planta-de-coca.pdfextraccion-de-alcaloides-de-la-planta-de-coca.pdf
extraccion-de-alcaloides-de-la-planta-de-coca.pdf
JENNYMARITZAHUILLCAR
 
ESTUDIANTES BENEFICIARIOS que se suman a los beneficios de la universidad
ESTUDIANTES BENEFICIARIOS que se suman a los beneficios de la universidadESTUDIANTES BENEFICIARIOS que se suman a los beneficios de la universidad
ESTUDIANTES BENEFICIARIOS que se suman a los beneficios de la universidad
jorgejhonatanaltamir1
 
APLICACIONES DE INTERNET-INFORMATICA.pptx
APLICACIONES DE INTERNET-INFORMATICA.pptxAPLICACIONES DE INTERNET-INFORMATICA.pptx
APLICACIONES DE INTERNET-INFORMATICA.pptx
cpadua713
 
PPT_QUÍMICA GENERAL_TEO_SEM-09_SESIÓN-17_2024_Gases ideales (2).pdf
PPT_QUÍMICA GENERAL_TEO_SEM-09_SESIÓN-17_2024_Gases ideales  (2).pdfPPT_QUÍMICA GENERAL_TEO_SEM-09_SESIÓN-17_2024_Gases ideales  (2).pdf
PPT_QUÍMICA GENERAL_TEO_SEM-09_SESIÓN-17_2024_Gases ideales (2).pdf
josenestorlopezquisp1
 
Oruam, el pequeño y el gran carismatico mago
Oruam, el pequeño y el gran carismatico magoOruam, el pequeño y el gran carismatico mago
Oruam, el pequeño y el gran carismatico mago
ChichipeSevillaJhost
 
SLIDESHARE, qué es, ventajas y desventajas
SLIDESHARE, qué es, ventajas y desventajasSLIDESHARE, qué es, ventajas y desventajas
SLIDESHARE, qué es, ventajas y desventajas
ruthechepurizaca
 
La revolución de Netflix redefiniendo las películas, la televisión, el arte y...
La revolución de Netflix redefiniendo las películas, la televisión, el arte y...La revolución de Netflix redefiniendo las películas, la televisión, el arte y...
La revolución de Netflix redefiniendo las películas, la televisión, el arte y...
NoraRoberts5
 
COMUNIDADES DE APRENDIZAJE EN EL CURSO DE APLICACIONES PARA INTERNET
COMUNIDADES DE APRENDIZAJE EN EL CURSO DE APLICACIONES PARA INTERNETCOMUNIDADES DE APRENDIZAJE EN EL CURSO DE APLICACIONES PARA INTERNET
COMUNIDADES DE APRENDIZAJE EN EL CURSO DE APLICACIONES PARA INTERNET
Kevin Aguilar Garcia
 
Análisis de Crowdfunding con el maestro Tapia de Artes
Análisis de Crowdfunding con el maestro Tapia de ArtesAnálisis de Crowdfunding con el maestro Tapia de Artes
Análisis de Crowdfunding con el maestro Tapia de Artes
al050121024
 
Sesión N°10 / Monografía sobre la inteligencia artifical
Sesión N°10 / Monografía sobre la inteligencia artificalSesión N°10 / Monografía sobre la inteligencia artifical
Sesión N°10 / Monografía sobre la inteligencia artifical
Angeles del Rosario Escobar Mendoza
 
Oración a Pomba Gira María Padilha .docx
Oración a Pomba Gira María Padilha .docxOración a Pomba Gira María Padilha .docx
Oración a Pomba Gira María Padilha .docx
LuisAlbertoCordovaBa
 
COMO EVOLUCIONO LAS WEB EN PLENO 2024.docx
COMO EVOLUCIONO LAS WEB EN PLENO 2024.docxCOMO EVOLUCIONO LAS WEB EN PLENO 2024.docx
COMO EVOLUCIONO LAS WEB EN PLENO 2024.docx
Jean Apellidos
 

Último (14)

MONOGRAFRIA GOOGLE (grupo 1ro de google).pdf
MONOGRAFRIA GOOGLE (grupo 1ro de google).pdfMONOGRAFRIA GOOGLE (grupo 1ro de google).pdf
MONOGRAFRIA GOOGLE (grupo 1ro de google).pdf
 
FICHA DE EDUCACIÓN RELIGIOSA 17 DE CTUBRE LA oracion.docx
FICHA DE EDUCACIÓN RELIGIOSA  17 DE CTUBRE LA  oracion.docxFICHA DE EDUCACIÓN RELIGIOSA  17 DE CTUBRE LA  oracion.docx
FICHA DE EDUCACIÓN RELIGIOSA 17 DE CTUBRE LA oracion.docx
 
extraccion-de-alcaloides-de-la-planta-de-coca.pdf
extraccion-de-alcaloides-de-la-planta-de-coca.pdfextraccion-de-alcaloides-de-la-planta-de-coca.pdf
extraccion-de-alcaloides-de-la-planta-de-coca.pdf
 
ESTUDIANTES BENEFICIARIOS que se suman a los beneficios de la universidad
ESTUDIANTES BENEFICIARIOS que se suman a los beneficios de la universidadESTUDIANTES BENEFICIARIOS que se suman a los beneficios de la universidad
ESTUDIANTES BENEFICIARIOS que se suman a los beneficios de la universidad
 
APLICACIONES DE INTERNET-INFORMATICA.pptx
APLICACIONES DE INTERNET-INFORMATICA.pptxAPLICACIONES DE INTERNET-INFORMATICA.pptx
APLICACIONES DE INTERNET-INFORMATICA.pptx
 
PPT_QUÍMICA GENERAL_TEO_SEM-09_SESIÓN-17_2024_Gases ideales (2).pdf
PPT_QUÍMICA GENERAL_TEO_SEM-09_SESIÓN-17_2024_Gases ideales  (2).pdfPPT_QUÍMICA GENERAL_TEO_SEM-09_SESIÓN-17_2024_Gases ideales  (2).pdf
PPT_QUÍMICA GENERAL_TEO_SEM-09_SESIÓN-17_2024_Gases ideales (2).pdf
 
Oruam, el pequeño y el gran carismatico mago
Oruam, el pequeño y el gran carismatico magoOruam, el pequeño y el gran carismatico mago
Oruam, el pequeño y el gran carismatico mago
 
SLIDESHARE, qué es, ventajas y desventajas
SLIDESHARE, qué es, ventajas y desventajasSLIDESHARE, qué es, ventajas y desventajas
SLIDESHARE, qué es, ventajas y desventajas
 
La revolución de Netflix redefiniendo las películas, la televisión, el arte y...
La revolución de Netflix redefiniendo las películas, la televisión, el arte y...La revolución de Netflix redefiniendo las películas, la televisión, el arte y...
La revolución de Netflix redefiniendo las películas, la televisión, el arte y...
 
COMUNIDADES DE APRENDIZAJE EN EL CURSO DE APLICACIONES PARA INTERNET
COMUNIDADES DE APRENDIZAJE EN EL CURSO DE APLICACIONES PARA INTERNETCOMUNIDADES DE APRENDIZAJE EN EL CURSO DE APLICACIONES PARA INTERNET
COMUNIDADES DE APRENDIZAJE EN EL CURSO DE APLICACIONES PARA INTERNET
 
Análisis de Crowdfunding con el maestro Tapia de Artes
Análisis de Crowdfunding con el maestro Tapia de ArtesAnálisis de Crowdfunding con el maestro Tapia de Artes
Análisis de Crowdfunding con el maestro Tapia de Artes
 
Sesión N°10 / Monografía sobre la inteligencia artifical
Sesión N°10 / Monografía sobre la inteligencia artificalSesión N°10 / Monografía sobre la inteligencia artifical
Sesión N°10 / Monografía sobre la inteligencia artifical
 
Oración a Pomba Gira María Padilha .docx
Oración a Pomba Gira María Padilha .docxOración a Pomba Gira María Padilha .docx
Oración a Pomba Gira María Padilha .docx
 
COMO EVOLUCIONO LAS WEB EN PLENO 2024.docx
COMO EVOLUCIONO LAS WEB EN PLENO 2024.docxCOMO EVOLUCIONO LAS WEB EN PLENO 2024.docx
COMO EVOLUCIONO LAS WEB EN PLENO 2024.docx
 

Sobreescritura y extensión de validaciones, formularios y entidades

  • 1.
  • 2.
  • 3. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES Aquí se cuajó todo:
  • 4. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES ¿De dónde viene esto?
  • 5. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES Librerías comunes para todos los proyectos de la agencia
  • 6. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES wolfwolker JL_Lasopaolacaracola araquemario almacbe frankey90 driera_comraulo79 gerfignaedytebfodavegmiguelvilata
  • 7. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES wolfwolker JL_Lasopaolacaracola araquemario almacbe frankey90 driera_comraulo79 gerfignaedytebfodavegmiguelvilata
  • 10. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
  • 11. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES Sobreescritura y extensión
  • 12. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES ● Bundles ● Controladores ● Templates ● Rutas ● Traducciones ● Validaciones ● Servicios ● Formularios ● Entidades ● Configuraciones ● Resources
  • 13. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES ¿Por qué atender en esta charla?
  • 14. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES ¿Cuál es la motivación?
  • 15. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES Es lo mismo que hacen FOSUserBundle, SymfonyCMF o SonataProject
  • 16. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES ¡Vamos allá!
  • 17. SOBREESCRITURA Y EXTENSIÓN DE VALIDACIONES, FORMULARIOS y ENTIDADES. UN CASO PRÁCTICO
  • 18. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES UserBundle EcommerceBundle simple shopping cart Cart - user - createdAt - ... CartLine - cart - purchasable - quantity - ... Purchasable - name - price - ... Product - media - size - ... Ticket - date - ... Book - isbn - ... User - username - ... Vendor
  • 19. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES Purchasable - name - price - ... Product - media - size - ... Book - isbn - ... UserBundle EcommerceBundle simple shopping cart Cart - user - createdAt - ... CartLine - cart - purchasable - quantity - ... Ticket - date - ... User - username - ... AppBundle User - username - city Cart - user - createdAt - ... CartLine - cart - purchasable - quantity VendorApp
  • 20. UserBundle EcommerceBundle simple shopping cart CÓMO CREAR THIRD PARTY BUNDLES DE SYMFONY COMPLETAMENTE EXTENSIBLES Y SOBREESCRIBIBLES Cart - user - createdAt - ... CartLine - cart - purchasable - quantity - ... Purchasable - name - price - ... Product - media - size - ... Ticket - date - ... Book - isbn - ... User - username - ... AppBundle User - username - city Cart - user - createdAt - ... CartLine - cart - purchasable - quantity VendorApp
  • 21. SOBREESCRITURA Y EXTENSIÓN DE VALIDACIONES, FORMULARIOS y ENTIDADES. FORMULARIOS
  • 22. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES EcommerceBundle PurchasabLeType - name - price - ... UserBundle simple shopping cart UserType - username - ... AppBundle VendorApp
  • 23. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES AppBundle UserBundle EcommerceBundle AbstractPurchasable - name - price - ... User - username - ... Car - ... Food - ... Pen - ... simple shopping cart
  • 24. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES EcommerceBundle PurchasableType - name - price - ... UserBundle simple shopping cart UserType - username - ... AppBundle VendorApp CarType - color - ... UserType - city - ...
  • 26. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES EcommerceBundle PurchasableType - name - price - ... UserBundle simple shopping cart UserType - username - ... AppBundle VendorApp CarType - color - ... UserType - city - ...
  • 27. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES EcommerceBundle PurchasableType - name - price - ... UserBundle simple shopping cart UserType - username - ... AppBundle VendorApp CarType - color - ... UserType - city - ...
  • 28. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES services: user_bundle.form.type.usr: class: UserBundleFormTypeUserType arguments: ["@my_service"] tags: - { name: form.type }
  • 29. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES services: user_bundle.form.type.usr: class: UserBundleFormTypeUserType arguments: ["@my_service"] tags: - { name: form.type } Como un servicio
  • 31. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES 1ª Sobreescribir parámetro de la clase del servicio
  • 32. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES services: user_bundle.form.type.user: class: UserBundleFormTypeUserType arguments: ["@my_service"] tags: - { name: form.type }
  • 33. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES services: user_bundle.form.type.user: class: UserBundleFormTypeUserType arguments: ["@my_service"] tags: - { name: form.type }
  • 34. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES services: user_bundle.form.type.user: class: "%user_bundle.user.class%" arguments: ["@my_service"] tags: - { name: form.type }
  • 35. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES services: user_bundle.form.type.user: class: "%user_bundle.user.class%" arguments: ["@my_service"] tags: - { name: form.type } W arning!
  • 36. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES Symfony Best Practices
  • 37. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES Parámetros de configuración, no globales
  • 38. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES 2ª Sobreescribiendo el servicio creando otro con el mismo id
  • 39. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES 2ª Sobreescribiendo el servicio creando otro con el mismo id Muy mala práctica
  • 40. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES 3ª Usando CompilerPass
  • 41. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES ¿Qué es un CompilerPass?
  • 42. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES Es el modo en que Symfony2 permite interactuar con los servicio y parámetros definidos globalmente y de los bundles cuando han sido cargados, pero antes de que se hayan compilado y optimizados en el DependencyInjection Component (DIC)
  • 43. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES services: reusable_bundle.form.type.product: class: ReusableBundleFormTypeProductType arguments: ["@my_service"] tags: - { name: form.type }
  • 44. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES // src/Acme/ReusableBundle/DependencyInjection/Compiler/OverrideServiceCompilerPass.php namespace AcmeReusableBundleDependencyInjectionCompiler; use SymfonyComponentDependencyInjectionCompilerCompilerPassInterface; use SymfonyComponentDependencyInjectionContainerBuilder; class OverrideServiceCompilerPass implements CompilerPassInterface { public function process(ContainerBuilder $container) { $definition = $container->getDefinition('reusable_bundle.form.type.product'); $definition->setClass('AcmeDemoBundleFormMyProductType'); } }
  • 45. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES // src/Acme/ReusableBundle/DependencyInjection/Compiler/OverrideServiceCompilerPass.php namespace AcmeReusableBundleDependencyInjectionCompiler; use SymfonyComponentDependencyInjectionCompilerCompilerPassInterface; use SymfonyComponentDependencyInjectionContainerBuilder; class OverrideServiceCompilerPass implements CompilerPassInterface { public function process(ContainerBuilder $container) { $definition = $container->getDefinition('reusable_bundle.form.type.product'); $definition->setClass('AcmeDemoBundleFormMyProductType'); } }
  • 46. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES // src/Acme/ReusabeBundle/AcmeReusableBundle.php class AcmeReusableBundle extends Bundle { /** * @param ContainerBuilder $container */ public function build(ContainerBuilder $container) { $container->addCompilerPass( new OverrideServiceCompilerPass() ); } }
  • 47. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES Volvemos a los Formularios
  • 49. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES EcommerceBundle PurchasableType - name - price - ... UserBundle simple shopping cart UserType - username - ... AppBundle VendorApp CarType - color - ... UserType - city - ...
  • 50. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES class MyBookType extends AbstractType { ... public function getParent() { return PurchasableType::class; } }
  • 51. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES class MyBookType extends PurchasableType { ... } class MyBookType extends AbstractType { ... public function getParent() { return PurchasableType::class; } } Vs
  • 52. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES abstract class AbstractType implements FormTypeInterface { public function buildForm(FormBuilderInterface $builder, array $options); public function buildView(FormView $view, FormInterface $form, array $options); public function finishView(FormView $view, FormInterface $form, array $options); public function configureOptions(OptionsResolver $resolver); public function getBlockPrefix(); public function getParent(); }
  • 53. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES abstract class PurchasableType implements FormTypeInterface { public function buildForm(FormBuilderInterface $builder, array $options); public function buildView(FormView $view, FormInterface $form, array $options); public function finishView(FormView $view, FormInterface $form, array $options); public function configureOptions(OptionsResolver $resolver); public function getBlockPrefix(); public function getParent(); }
  • 54. SOBREESCRITURA Y EXTENSIÓN DE VALIDACIONES, FORMULARIOS y ENTIDADES. VALIDACIONES
  • 55. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES EcommerceBundle PurchasableType - name - price - ... UserBundle simple shopping cart UserType - username - ... AppBundle VendorApp CarType - color - ... UserType - city - ...
  • 57. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES Validator component
  • 58. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES /** * @AssertLength(min=2) */ private $city;
  • 59. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES AppBundleEntityAdress: properties: city: - Length: - min: 2
  • 60. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES fácil las validaciones, ¿no?
  • 61. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES pero...
  • 62. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES ¿y cómo sobreescribimos las validaciones?
  • 63. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES Symfony dice:
  • 64. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES “Symfony loads all validation configuration files from every bundle and combines them into one validation metadata tree. This means you are able to add new constraints to a property, but you cannot override them.”
  • 65. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES “To override this, the 3rd party bundle needs to have configuration for validation groups.”
  • 67. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES class User implements UserInterface { /** * @AssertEmail( * groups={"registration"} * ) */ private $email; /** * @AssertNotBlank( * groups={"registration"} * ) * @AssertLength( * min=7, * groups={"registration"} * ) */ private $password; /** * @AssertValid() * @ORMOneToOne( * targetEntity="Address", * mappedBy="address" * ) */ private $address; /** * @AssertLength(min=2) */ private $city; }
  • 68. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES class User implements UserInterface { /** * @AssertEmail( * groups={"registration"} * ) */ private $email; /** * @AssertNotBlank( * groups={"registration"} * ) * @AssertLength( * min=7, * groups={"registration"} * ) */ private $password; /** * @AssertValid() * @ORMOneToOne( * targetEntity="Address", * mappedBy="address" * ) */ private $address; /** * @AssertLength(min=2) */ private $city; }
  • 69. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES ¿Cuántos grupos de validación hay para la clase User?
  • 70. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES registration
  • 71. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES class User implements UserInterface { /** * @AssertEmail( * groups={"registration"} * ) */ private $email; /** * @AssertNotBlank( * groups={"registration"} * ) * @AssertLength( * min=7, * groups={"registration"} * ) */ private $password; /** * @AssertValid() * @ORMOneToOne( * targetEntity="Address", * mappedBy="address" * ) */ private $address; /** * @AssertLength(min=2) */ private $city; }
  • 72. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES class User implements UserInterface { /** * @AssertEmail( * groups={"registration"} * ) */ private $email; /** * @AssertNotBlank( * groups={"registration"} * ) * @AssertLength( * min=7, * groups={"registration"} * ) */ private $password; /** * @AssertValid() * @ORMOneToOne( * targetEntity="Address", * mappedBy="address" * ) */ private $address; /** * @AssertLength(min=2) */ private $city; }
  • 73. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES Default
  • 74. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES class User implements UserInterface { /** * @AssertEmail( * groups={"registration"} * ) */ private $email; /** * @AssertNotBlank( * groups={"registration"} * ) * @AssertLength( * min=7, * groups={"registration"} * ) */ private $password; /** * @AssertValid() * @ORMOneToOne( * targetEntity="Address", * mappedBy="address" * ) */ private $address; /** * @AssertLength(min=2) */ private $city; }
  • 75. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES class User implements UserInterface { /** * @AssertEmail( * groups={"registration"} * ) */ private $email; /** * @AssertNotBlank( * groups={"registration"} * ) * @AssertLength( * min=7, * groups={"registration"} * ) */ private $password; /** * @AssertValid() * @ORMOneToOne( * targetEntity="Address", * mappedBy="address" * ) */ private $address; /** * @AssertLength(min=2) */ private $city; }
  • 76. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES class User implements UserInterface { /** * @AssertEmail( * groups={"registration"} * ) */ private $email; /** * @AssertNotBlank( * groups={"registration"} * ) * @AssertLength( * min=7, * groups={"registration"} * ) */ private $password; /** * @AssertValid() * @ORMOneToOne( * targetEntity="Address", * mappedBy="address" * ) */ private $address; /** * @AssertLength(min=2) */ private $city; } ? ?
  • 77. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES class User implements UserInterface { /** * @AssertEmail( * groups={"registration"} * ) */ private $email; /** * @AssertNotBlank( * groups={"registration"} * ) * @AssertLength( * min=7, * groups={"registration"} * ) */ private $password; /** * @AssertValid() * @ORMOneToOne( * targetEntity="Address", * mappedBy="address" * ) */ private $address; /** * @AssertLength(min=2) */ private $city; } ?
  • 78. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES class User implements UserInterface { /** * @AssertEmail( * groups={"registration"} * ) */ private $email; /** * @AssertNotBlank( * groups={"registration"} * ) * @AssertLength( * min=7, * groups={"registration"} * ) */ private $password; /** * @AssertValid() * @ORMOneToOne( * targetEntity="Address", * mappedBy="address" * ) */ private $address; /** * @AssertLength(min=2) */ private $city; } ? Depende...
  • 79. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES class User implements UserInterface { /** * @AssertEmail( * groups={"registration"} * ) */ private $email; /** * @AssertNotBlank( * groups={"registration"} * ) * @AssertLength( * min=7, * groups={"registration"} * ) */ private $password; /** * @AssertValid() * @ORMOneToOne( * targetEntity="Address", * mappedBy="address" * ) */ private $address; /** * @AssertLength(min=2) */ private $city; } ?
  • 80. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES class User implements UserInterface { /** * @AssertEmail( * groups={"registration"} * ) */ private $email; /** * @AssertNotBlank( * groups={"registration"} * ) * @AssertLength( * min=7, * groups={"registration"} * ) */ private $password; /** * @AssertValid() * @ORMOneToOne( * targetEntity="Address", * mappedBy="address" * ) */ private $address; /** * @AssertLength(min=2) */ private $city; } Depende... ?
  • 81. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES class User implements UserInterface { /** * @AssertEmail( * groups={"registration"} * ) */ private $email; /** * @AssertNotBlank( * groups={"registration"} * ) * @AssertLength( * min=7, * groups={"registration"} * ) */ private $password; /** * @AssertValid() * @ORMOneToOne( * targetEntity="Address", * mappedBy="address" * ) */ private $address; /** * @AssertLength(min=2) */ private $city; }
  • 82. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES User
  • 83. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES class User implements UserInterface { /** * @AssertEmail( * groups={"registration"} * ) */ private $email; /** * @AssertNotBlank( * groups={"registration"} * ) * @AssertLength( * min=7, * groups={"registration"} * ) */ private $password; /** * @AssertValid() * @ORMOneToOne( * targetEntity="Address", * mappedBy="address" * ) */ private $address; /** * @AssertLength(min=2) */ private $city; }
  • 84. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES class User implements UserInterface { /** * @AssertEmail( * groups={"registration"} * ) */ private $email; /** * @AssertNotBlank( * groups={"registration"} * ) * @AssertLength( * min=7, * groups={"registration"} * ) */ private $password; /** * @AssertValid() * @ORMOneToOne( * targetEntity="Address", * mappedBy="address" * ) */ private $address; /** * @AssertLength(min=2) */ private $city; }
  • 85. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES class User implements UserInterface { /** * @AssertEmail( * groups={"registration"} * ) */ private $email; /** * @AssertNotBlank( * groups={"registration"} * ) * @AssertLength( * min=7, * groups={"registration"} * ) */ private $password; /** * @AssertValid() * @ORMOneToOne( * targetEntity="Address", * mappedBy="address" * ) */ private $address; /** * @AssertLength(min=2) */ private $city; } ? ?
  • 86. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES class User implements UserInterface { /** * @AssertEmail( * groups={"registration"} * ) */ private $email; /** * @AssertNotBlank( * groups={"registration"} * ) * @AssertLength( * min=7, * groups={"registration"} * ) */ private $password; /** * @AssertValid() * @ORMOneToOne( * targetEntity="Address", * mappedBy="address" * ) */ private $address; /** * @AssertLength(min=2) */ private $city; } ?
  • 87. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES class User implements UserInterface { /** * @AssertEmail( * groups={"registration"} * ) */ private $email; /** * @AssertNotBlank( * groups={"registration"} * ) * @AssertLength( * min=7, * groups={"registration"} * ) */ private $password; /** * @AssertValid() * @ORMOneToOne( * targetEntity="Address", * mappedBy="address" * ) */ private $address; /** * @AssertLength(min=2) */ private $city; } ? Depende...
  • 88. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES class User implements UserInterface { /** * @AssertEmail( * groups={"registration"} * ) */ private $email; /** * @AssertNotBlank( * groups={"registration"} * ) * @AssertLength( * min=7, * groups={"registration"} * ) */ private $password; /** * @AssertValid() * @ORMOneToOne( * targetEntity="Address", * mappedBy="address" * ) */ private $address; /** * @AssertLength(min=2) */ private $city; }
  • 89. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES - “Dos grupos por defecto”: - { NombreClase, Default } - Si se especifica un grupo, NO se añaden “los por defecto”
  • 90. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES Warning! - Si se valida una clase con el grupo de validación del nombre de la clase y las relaciones también se validan.
  • 91. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES Y…?
  • 93. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES ¿Recordamos lo que hemos hablado de formularios y servicios?
  • 94. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES acme_reusable: user: form: type: AcmeReusableBundleFormTypeUserType validation_groups: [registration, Default]
  • 95. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES class FormFactory implements FactoryInterface { private $formFactory; private $name; private $type; private $validationGroups; public function __construct(FormFactoryInterface $formFactory, $name, $type, array $validationGroups = null) { $this->formFactory = $formFactory; $this->name = $name; $this->type = $type; $this->validationGroups = $validationGroups; } public function createForm(array $options = array()) { $options = array_merge(array('validation_groups' => $this->validationGroups), $options); return $this->formFactory->createNamed($this->name, $this->type, null, $options); } }
  • 96. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES class FormFactory implements FactoryInterface { private $formFactory; private $name; private $type; private $validationGroups; public function __construct(FormFactoryInterface $formFactory, $name, $type, array $validationGroups = null) { $this->formFactory = $formFactory; $this->name = $name; $this->type = $type; $this->validationGroups = $validationGroups; } public function createForm(array $options = array()) { $options = array_merge(array('validation_groups' => $this->validationGroups), $options); return $this->formFactory->createNamed($this->name, $this->type, null, $options); } }
  • 97. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES class FormFactory implements FactoryInterface { private $formFactory; private $name; private $type; private $validationGroups; public function __construct(FormFactoryInterface $formFactory, $name, $type, array $validationGroups = null) { $this->formFactory = $formFactory; $this->name = $name; $this->type = $type; $this->validationGroups = $validationGroups; } public function createForm(array $options = array()) { $options = array_merge(array('validation_groups' => $this->validationGroups), $options); return $this->formFactory->createNamed($this->name, $this->type, null, $options); } }
  • 98. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES <service id="acme_reusable.user.form.factory" class="AcmeReusableBundleFormFactoryFormFactory"> <argument type="service" id="form.factory" /> <argument>%acme_reusable.user.form.name%</argument> <argument>%acme_reusable.user.form.type%</argument> <argument>%acme_reusable.user.form.validation_groups%</argument> </service>
  • 99. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES $formFactory = $this->get(acme_reusable.user.form.factory'); $form = $formFactory->createForm();
  • 100. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES En definitiva...
  • 101. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES $form = $this->createFormBuilder($user, array( 'validation_groups' => array(Create, 'Default'), ))->add(...)->getForm();
  • 102. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES $form = $this->createFormBuilder($user, array( 'validation_groups' => array(Create, 'Default'), ))->add(...)->getForm();
  • 103. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES $form = $this->createFormBuilder($user, array( 'validation_groups' => $validationGroupFromParameter, ))->add(...)->getForm();
  • 105. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES $errors = $validator ->validate($user, null, array('registration', 'Default'));
  • 106. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES $errors = $validator ->validate($user, null, array('registration', 'Default'));
  • 107. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES $errors = $validator ->validate($user, null, $validationGroupFromParameter);
  • 108. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES ¿MUCHA INFORMACIÓN?
  • 109. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES ¿ABURRIDO?
  • 110. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES ¿SUEÑO?
  • 111. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES TOMA AIRE ...
  • 112. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES … RESPIRA ...
  • 113. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES … Y PREPÁRATE ...
  • 114. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES ¡RELEVO!
  • 115. SOBREESCRITURA Y EXTENSIÓN DE VALIDACIONES, FORMULARIOS y ENTIDADES. ENTITY MAPPING
  • 116. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES Due to the way Doctrine works, it is not possible to override entity mapping of a bundle. However, if a bundle provides a mapped superclass (such as the User entity in the FOSUserBundle) one can override attributes and associations. Learn more about this feature and its limitations in the Doctrine documentation. http://symfony.com/doc/current/cookbook/bundles/override.html#entities-entity-mapping
  • 117. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES EMPECEMOS DESDE CERO
  • 118. SOBREESCRITURA Y EXTENSIÓN DE VALIDACIONES, FORMULARIOS y ENTIDADES. DOCTRINE2
  • 119. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
  • 120. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES
  • 121. SOBREESCRITURA Y EXTENSIÓN DE VALIDACIONES, FORMULARIOS y ENTIDADES. CÓMO PROVEER MAPPING METADATA
  • 122. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES # Resources/config/doctrine/User.orm.xml <doctrine-mapping ...> <mapped-superclass name="FOSUserBundleEntityUser"> ... <field name="username" column="username" type="string" length="255" /> … </mapped-superclass> </doctrine-mapping> XML:
  • 123. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES # Resources/config/doctrine/User.orm.yml DoctrineTestsORMMappingUser: type: entity table: cms_users ... fields: username: type: string length: 50 ... YML:
  • 124. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES <?php /** @Entity */ class User { /** @Column(type="string", length=100) */ private $username; ... } Annotations:
  • 125. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES Mapping: En un bundle no pueden convivir formatos XML > YML > Annotations
  • 126. SOBREESCRITURA Y EXTENSIÓN DE VALIDACIONES, FORMULARIOS y ENTIDADES. MAPPED-SUPERCLASS
  • 127. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES Clase Abstracta o concreta Su finalidad es definir información de mapeo que van a heredar otras entidades Mapped-Superclass:
  • 128. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES # Model/User.php abstract class User { protected $username; … } # Resources/config/doctrine-mapping/User.orm.xml <mapped-superclass name="FOSUserBundleModelUser"> <field name="username" column="username" type="string" length="180" /> … </mapped-superclass>
  • 129. SOBREESCRITURA Y EXTENSIÓN DE VALIDACIONES, FORMULARIOS y ENTIDADES. PRIMERA APROXIMACIÓN
  • 130. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES AppBundle UserBundle EcommerceBundle Primera aproximación AbstractCart - user - createdAt - ... AbstractCartLine - cart - purchasable - quantity - ... AbstractPurchasable - name - price - ... AbstractUser - username - ... Cart - ... CartLine - ... Product - ... User - ... VendorApp
  • 131. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES Primera aproximación Pero.... - Obligamos a extender todas las entidades - Obligamos a escribir el mapeo de las relaciones
  • 132. SOBREESCRITURA Y EXTENSIÓN DE VALIDACIONES, FORMULARIOS y ENTIDADES. SEGUNDA APROXIMACIÓN
  • 133. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES UserBundle EcommerceBundle Segunda aproximación AbstractCart - user - createdAt - ... AbstractCartLine - cart - purchasable - quantity - ... AbstractPurchasable - name - price - ... AbstractUser - username - ... Cart - ... CartLine - ... Product - ... User - ... Vendor
  • 134. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES AppBundle UserBundle EcommerceBundle Segunda aproximación CÓMO CREAR THIRD PARTY BUNDLES DE SYMFONY COMPLETAMENTE EXTENSIBLES Y SOBREESCRIBIBLES AbstractCart - user - createdAt - ... AbstractCartLine - cart - purchasable - quantity - ... AbstractPurchasable - name - price - ... AbstractUser - username - ... Cart - ... CartLine - ... Product - ... User - ... VendorApp Cart - ...
  • 135. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES Segunda aproximación CÓMO CREAR THIRD PARTY BUNDLES DE SYMFONY COMPLETAMENTE EXTENSIBLES Y SOBREESCRIBIBLES ● Ofrecer clases concretas en el bundle ● Permitir que por parámetros en la capa de aplicación se indique qué clases concretas usar
  • 136. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES Segunda aproximación CÓMO CREAR THIRD PARTY BUNDLES DE SYMFONY COMPLETAMENTE EXTENSIBLES Y SOBREESCRIBIBLES ● Ofrecer clases concretas en el bundle ● Permitir que por parámetros en la capa de aplicación se indique qué clases concretas usar Implica.... ● Que el bundle decida si tiene que mapear o no las entidades concretas ● Establecer dinámicamente las relaciones entre entidades
  • 137. SOBREESCRITURA Y EXTENSIÓN DE VALIDACIONES, FORMULARIOS y ENTIDADES. AUTO MAPPING
  • 138. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES Auto Mapping - Doctrine busca entidades en la carpeta Entity de todos los bundles
  • 139. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES Auto Mapping - Doctrine busca entidades en la carpeta Entity de todos los bundles - Busca la información de mapeo en - Resources/config/doctrine/ - Anotaciones
  • 140. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES Auto Mapping - Doctrine busca entidades en la carpeta Entity de todos los bundles - Busca la información de mapeo en - Resources/config/doctrine/ - Anotaciones - Activado por defecto, pero nuestro bundle tiene que funcionar independientemente de su estado.
  • 141. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES Solución: - Mover las entidades concretas del bundle a otro directorio - Ej.: Model - Mover la información de mapeo - Ej.: Resource/config/doctrine-model Segunda aproximación
  • 142. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES ¿Cómo mapeo las entidades? Segunda aproximación
  • 143. SOBREESCRITURA Y EXTENSIÓN DE VALIDACIONES, FORMULARIOS y ENTIDADES. DoctrineOrmMappingPass
  • 144. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES $container->addCompilerPass( new DoctrineOrmMappingsPass( $driver, //DoctrineORMMappingDriverXmlDriver array('AcmeReusableBundleModelCart'), array('doctrine.default_entity_manager'), "boolean_param_name" ) ); Segunda aproximación
  • 145. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES $container->addCompilerPass( new DoctrineOrmMappingsPass( $driver, //DoctrineORMMappingDriverXmlDriver array('AcmeReusableBundleModelCart'), array('acme_reusable.model_manager_name'), "acme_reusable.tengo_que_mapear_la_clase_cart" ) ); Segunda aproximación
  • 146. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES AbstractCart - user - createdAt - ... AppBundle UserBundle EcommerceBundle Segunda aproximación AbstractCartLine - cart - purchasable - quantity - ... AbstractPurchasable - name - price - ... AbstractUser - username - ... Cart - ... CartLine - ... Product - ... User - ... VendorApp Cart - ...
  • 147. SOBREESCRITURA Y EXTENSIÓN DE VALIDACIONES, FORMULARIOS y ENTIDADES. MAP TO ABSTRACT AND INTERFACES
  • 148. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES # Resources/config/doctrine-base/AbstractCartLine.orm.xml <mapped-superclass name="AcmeReusableBundleModelAbstractCartLine"> ... <many-to-one target-entity="AcmeReusableBundleEntityAbstractPurchasable" field="purchasable" /> <many-to-one target-entity="AcmeReusableBundleModelInterfacesCartInterface" inversed-by="cartLines" field="cart"/> ... </mapped-superclass> Segunda aproximación
  • 149. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES # Resources/config/doctrine-base/AbstractCartLine.orm.xml <mapped-superclass name="AcmeReusableBundleModelAbstractCartLine"> ... <many-to-one target-entity="AcmeReusableBundleEntityAbstractPurchasable" field="purchasable" /> <many-to-one target-entity="AcmeReusableBundleModelInterfacesCartInterface" inversed-by="cartLines" field="cart"/> ... </mapped-superclass> Segunda aproximación
  • 150. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES # app/config/config.yml doctrine: orm: resolve_target_entities: CartInterface: AppBundleEntityCart Segunda aproximación
  • 151. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES # DependencyInjection/AcmeReusableExtension.php public function prepend(ContainerBuilder $container) { … $doctrineConfig = array( 'orm' => array( 'resolve_target_entities' => array( 'CartInterface' => $config['class']['cart'], ), ), ); $container->prependExtensionConfig('doctrine', $doctrineConfig); ... } Segunda aproximación CÓMO CREAR THIRD PARTY BUNDLES DE SYMFONY COMPLETAMENTE EXTENSIBLES Y SOBREESCRIBIBLES
  • 152. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES AppBundle UserBundle EcommerceBundle Segunda aproximación AbstractCart - user - createdAt - ... AbstractCartLine - cart - purchasable - quantity - ... AbstractPurchasable - name - price - ... AbstractUser - username - ... Cart - ... CartLine - ... Product - ... User - ... VendorApp Cart - ...
  • 153. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES # Resources/config/doctrine-base/AbstractCartLine.orm.xml <mapped-superclass name="AbstractCartLine"> ... <many-to-one target-entity="CartInterface" inversed-by="cartLines" field="cart" /> ... </mapped-superclass> Segunda aproximación
  • 154. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES # Resources/config/doctrine-base/AbstractCart.orm.xml <mapped-superclass name="AcmeReusableBundleEntityAbstractCart"> ... <one-to-many field="cartLines" target-entity="CartLineInterface" mapped-by="cart" /> ... </mapped-superclass> Segunda aproximación
  • 155. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES # Resources/config/doctrine-base/AbstractCart.orm.xml <mapped-superclass name="AcmeReusableBundleEntityAbstractCart"> ... <one-to-many field="cartLines" target-entity="CartLineInterface" mapped-by="cart" /> ... </mapped-superclass> Segunda aproximación No se puede
  • 156. SOBREESCRITURA Y EXTENSIÓN DE VALIDACIONES, FORMULARIOS y ENTIDADES. loadClassMetadata
  • 157. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES // EventListener/MappingSubscriber.php public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs) { $classMetadata = $eventArgs->getClassMetadata(); if ($classMetadata->reflClass === $this->cartClass) { $classMetadata->mapOneToMany(array( 'fieldName' => 'cartLines', 'targetEntity' => $this->cartLineClass, 'cascade' => array(1 => 'all'), 'mappedBy' => 'cart', )); } } Segunda aproximación
  • 158. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES // EventListener/MappingSubscriber.php public function loadClassMetadata(LoadClassMetadataEventArgs $eventArgs) { $classMetadata = $eventArgs->getClassMetadata(); if ($classMetadata->reflClass === $this->cartClass) { $classMetadata->mapOneToMany(array( 'fieldName' => 'cartLines', 'targetEntity' => $this->cartLineClass, 'cascade' => array(1 => 'all'), 'mappedBy' => 'cart', )); } } Segunda aproximación
  • 159. SOBREESCRITURA Y EXTENSIÓN DE VALIDACIONES, FORMULARIOS y ENTIDADES. Resumiendo
  • 160. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES Resumiendo: - Usamos DoctrineOrmMappingPass para mapear las clases concretas de nuestro bundle, en función de los parámetros de configuración Segunda aproximación
  • 161. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES Resumiendo: - Usamos DoctrineOrmMappingPass para mapear las clases concretas de nuestro bundle, en función de los parámetros de configuración - Apuntamos las relaciones de las clases abstractas hacia Interfaces, para poder hacer que se apunte a la clase de destino con resolve_target_entity Segunda aproximación
  • 162. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES Resumiendo: - Usamos DoctrineOrmMappingPass para mapear las clases concretas de nuestro bundle, en función de los parámetros de configuración - Apuntamos las relaciones de las clases abstractas hacia Interfaces, para poder hacer que se apunte a la clase de destino con resolve_target_entity - Usamos el evento loadClassMetadata para completar las relaciones bidireccionales Segunda aproximación
  • 163. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES AppBundle UserBundle EcommerceBundle CartLine - cart - purchasable - quantity - ... AbstractPurchasable - name - price - ... Segunda aproximación User - username - ... Cart - customField
  • 164. SOBREESCRITURA Y EXTENSIÓN DE VALIDADORES, FORMULARIOS Y ENTIDADES Un ejemplo: https://github.com/dualhand/ReusableBundle https://github.com/dualhand/example-app