[Doc] Use Markdown syntax highlighting

This commit is contained in:
Laurent Ghirardotti 2014-09-26 12:51:50 +02:00 committed by Fabien Potencier
parent c3feed6df2
commit 638ce847b3
21 changed files with 626 additions and 527 deletions

View File

@ -40,7 +40,7 @@
Before: Before:
``` ```yaml
framework: framework:
session: session:
default_locale: fr default_locale: fr
@ -48,7 +48,7 @@
After: After:
``` ```yaml
framework: framework:
default_locale: fr default_locale: fr
``` ```
@ -77,7 +77,7 @@
registering a listener that looks like the following if the parameter which registering a listener that looks like the following if the parameter which
handles the locale value in the request is `_locale`: handles the locale value in the request is `_locale`:
``` ```php
namespace XXX; namespace XXX;
use Symfony\Component\HttpKernel\Event\GetResponseEvent; use Symfony\Component\HttpKernel\Event\GetResponseEvent;
@ -138,7 +138,7 @@
Before: Before:
``` ```php
class User implements UserInterface class User implements UserInterface
{ {
// ... // ...
@ -149,7 +149,7 @@
After: After:
``` ```php
class User implements UserInterface, EquatableInterface class User implements UserInterface, EquatableInterface
{ {
// ... // ...
@ -182,7 +182,7 @@
After: After:
``` ```php
namespace Acme\DemoBundle; namespace Acme\DemoBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle; use Symfony\Component\HttpKernel\Bundle\Bundle;
@ -245,14 +245,14 @@
Before: Before:
``` ```php
use Symfony\Bundle\SecurityBundle\Validator\Constraint\UserPassword; use Symfony\Bundle\SecurityBundle\Validator\Constraint\UserPassword;
use Symfony\Bundle\SecurityBundle\Validator\Constraint as SecurityAssert; use Symfony\Bundle\SecurityBundle\Validator\Constraint as SecurityAssert;
``` ```
After: After:
``` ```php
use Symfony\Component\Security\Core\Validator\Constraint\UserPassword; use Symfony\Component\Security\Core\Validator\Constraint\UserPassword;
use Symfony\Component\Security\Core\Validator\Constraint as SecurityAssert; use Symfony\Component\Security\Core\Validator\Constraint as SecurityAssert;
``` ```
@ -270,7 +270,7 @@
Before: Before:
``` ```php
use Symfony\Component\Form\FormBuilder; use Symfony\Component\Form\FormBuilder;
public function buildForm(FormBuilder $builder, array $options) public function buildForm(FormBuilder $builder, array $options)
@ -278,7 +278,7 @@
After: After:
``` ```php
use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\FormBuilderInterface;
public function buildForm(FormBuilderInterface $builder, array $options) public function buildForm(FormBuilderInterface $builder, array $options)
@ -301,7 +301,7 @@
Before: Before:
``` ```php
public function getParent(array $options) public function getParent(array $options)
{ {
return 'field'; return 'field';
@ -310,7 +310,7 @@
After: After:
``` ```php
public function getParent() public function getParent()
{ {
return 'form'; return 'form';
@ -333,7 +333,7 @@
Before: Before:
``` ```php
public function getParent(array $options) public function getParent(array $options)
{ {
return $options['expanded'] ? 'form' : 'field'; return $options['expanded'] ? 'form' : 'field';
@ -342,7 +342,7 @@
After: After:
``` ```php
use Symfony\Component\OptionsResolver\OptionsResolverInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\Options;
@ -374,7 +374,7 @@
Form mapped to an instance of `Person`: Form mapped to an instance of `Person`:
``` ```php
use Symfony\Component\OptionsResolver\OptionsResolverInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface;
public function setDefaultOptions(OptionsResolverInterface $resolver) public function setDefaultOptions(OptionsResolverInterface $resolver)
@ -399,7 +399,7 @@
Before: Before:
``` ```php
$builder->add('name', 'text', array( $builder->add('name', 'text', array(
'property_path' => 'address.street', 'property_path' => 'address.street',
)); ));
@ -407,7 +407,7 @@
After (if the address object is an array): After (if the address object is an array):
``` ```php
$builder->add('name', 'text', array( $builder->add('name', 'text', array(
'property_path' => 'address[street]', 'property_path' => 'address[street]',
)); ));
@ -427,7 +427,7 @@
underscores wherever you specify a value for the field's "prototype_name" underscores wherever you specify a value for the field's "prototype_name"
option. option.
``` ```php
$builder->add('tags', 'collection', array('prototype_name' => '__proto__')); $builder->add('tags', 'collection', array('prototype_name' => '__proto__'));
// results in the name "__proto__" in the template // results in the name "__proto__" in the template
@ -455,7 +455,7 @@
Before: Before:
``` ```jinja
{% block url_widget %} {% block url_widget %}
{% spaceless %} {% spaceless %}
{% set type = type|default('url') %} {% set type = type|default('url') %}
@ -466,7 +466,7 @@
After: After:
``` ```jinja
{% block url_widget %} {% block url_widget %}
{% spaceless %} {% spaceless %}
{% set type = type|default('url') %} {% set type = type|default('url') %}
@ -482,7 +482,7 @@
Before: Before:
``` ```jinja
{% block form_errors %} {% block form_errors %}
{% spaceless %} {% spaceless %}
... form code ... ... form code ...
@ -498,7 +498,7 @@
After: After:
``` ```jinja
{% block form_errors %} {% block form_errors %}
{% spaceless %} {% spaceless %}
{% if compound %} {% if compound %}
@ -532,7 +532,7 @@
Before: Before:
``` ```jinja
{% for choice, label in choices %} {% for choice, label in choices %}
{% if _form_is_choice_group(label) %} {% if _form_is_choice_group(label) %}
<optgroup label="{{ choice|trans }}"> <optgroup label="{{ choice|trans }}">
@ -550,7 +550,7 @@
After: After:
``` ```jinja
{% for label, choice in choices %} {% for label, choice in choices %}
{% if choice is iterable %} {% if choice is iterable %}
<optgroup label="{{ label|trans({}, translation_domain) }}"> <optgroup label="{{ label|trans({}, translation_domain) }}">
@ -571,7 +571,7 @@
accommodate those cases when the `label` option has not been explicitly accommodate those cases when the `label` option has not been explicitly
set. set.
``` ```jinja
{% block form_label %} {% block form_label %}
{% if label is empty %} {% if label is empty %}
{% set label = name|humanize %} {% set label = name|humanize %}
@ -588,7 +588,7 @@
Before: Before:
``` ```jinja
{% block _author_tags_0_label %} {% block _author_tags_0_label %}
{# ... #} {# ... #}
{% endblock %} {% endblock %}
@ -600,7 +600,7 @@
After: After:
``` ```jinja
{% block _author_tags_entry_label %} {% block _author_tags_entry_label %}
{# ... #} {# ... #}
{% endblock %} {% endblock %}
@ -612,13 +612,13 @@
Before: Before:
``` ```php
<?php echo $view['form']->renderBlock('widget_attributes') ?> <?php echo $view['form']->renderBlock('widget_attributes') ?>
``` ```
After: After:
``` ```php
<?php echo $view['form']->block($form, 'widget_attributes') ?> <?php echo $view['form']->block($form, 'widget_attributes') ?>
``` ```
@ -631,13 +631,13 @@
Before: Before:
``` ```php
$form = $factory->createNamed('text', 'firstName'); $form = $factory->createNamed('text', 'firstName');
``` ```
After: After:
``` ```php
$form = $factory->createNamed('firstName', 'text'); $form = $factory->createNamed('firstName', 'text');
``` ```
@ -648,7 +648,7 @@
Before: Before:
``` ```php
class MyChoiceList extends ArrayChoiceList class MyChoiceList extends ArrayChoiceList
{ {
protected function load() protected function load()
@ -664,7 +664,7 @@
After: After:
``` ```php
class MyChoiceList extends SimpleChoiceList class MyChoiceList extends SimpleChoiceList
{ {
public function __construct() public function __construct()
@ -680,7 +680,7 @@
accessed for the first time -- you can extend `LazyChoiceList` instead accessed for the first time -- you can extend `LazyChoiceList` instead
and load the choices by overriding `loadChoiceList()`. and load the choices by overriding `loadChoiceList()`.
``` ```php
class MyChoiceList extends LazyChoiceList class MyChoiceList extends LazyChoiceList
{ {
protected function loadChoiceList() protected function loadChoiceList()
@ -705,13 +705,13 @@
Before: Before:
``` ```jinja
{{ form_label(form.name, 'Your Name', { 'attr': {'class': 'foo'} }) }} {{ form_label(form.name, 'Your Name', { 'attr': {'class': 'foo'} }) }}
``` ```
After: After:
``` ```jinja
{{ form_label(form.name, 'Your Name', { 'label_attr': {'class': 'foo'} }) }} {{ form_label(form.name, 'Your Name', { 'label_attr': {'class': 'foo'} }) }}
``` ```
@ -751,7 +751,7 @@
Before: Before:
``` ```php
public function getDefaultOptions(array $options) public function getDefaultOptions(array $options)
{ {
return array( return array(
@ -769,7 +769,7 @@
After: After:
``` ```php
public function setDefaultOptions(OptionsResolverInterface $resolver) public function setDefaultOptions(OptionsResolverInterface $resolver)
{ {
$resolver->setDefaults(array( $resolver->setDefaults(array(
@ -786,7 +786,7 @@
Before: Before:
``` ```php
public function getDefaultOptions(array $options) public function getDefaultOptions(array $options)
{ {
$defaultOptions = array(); $defaultOptions = array();
@ -801,7 +801,7 @@
After: After:
``` ```php
public function setDefaultOptions(OptionsResolverInterface $resolver) public function setDefaultOptions(OptionsResolverInterface $resolver)
{ {
$resolver->setDefaults(array( $resolver->setDefaults(array(
@ -832,13 +832,13 @@
Before: Before:
``` ```php
$builder->appendClientTransformer(new MyTransformer()); $builder->appendClientTransformer(new MyTransformer());
``` ```
After: After:
``` ```php
$builder->addViewTransformer(new MyTransformer()); $builder->addViewTransformer(new MyTransformer());
``` ```
@ -857,7 +857,7 @@
Before: Before:
``` ```php
$builder->addListener(FormEvents::BIND_CLIENT_DATA, function (FilterDataEvent $event) { $builder->addListener(FormEvents::BIND_CLIENT_DATA, function (FilterDataEvent $event) {
// ... // ...
}); });
@ -865,7 +865,7 @@
After: After:
``` ```php
$builder->addListener(FormEvents::PRE_BIND, function (FormEvent $event) { $builder->addListener(FormEvents::PRE_BIND, function (FormEvent $event) {
// ... // ...
}); });
@ -886,7 +886,7 @@
Before: Before:
``` ```php
public function guessMinLength($class, $property) public function guessMinLength($class, $property)
{ {
if (/* condition */) { if (/* condition */) {
@ -897,7 +897,7 @@
After: After:
``` ```php
public function guessPattern($class, $property) public function guessPattern($class, $property)
{ {
if (/* condition */) { if (/* condition */) {
@ -914,7 +914,7 @@
Before: Before:
``` ```php
$builder->add('termsAccepted', 'checkbox', array( $builder->add('termsAccepted', 'checkbox', array(
'property_path' => false, 'property_path' => false,
)); ));
@ -922,7 +922,7 @@
After: After:
``` ```php
$builder->add('termsAccepted', 'checkbox', array( $builder->add('termsAccepted', 'checkbox', array(
'mapped' => false, 'mapped' => false,
)); ));
@ -944,13 +944,13 @@
Before: Before:
``` ```php
$form->getErrorBubbling() $form->getErrorBubbling()
``` ```
After: After:
``` ```php
$form->getConfig()->getErrorBubbling(); $form->getConfig()->getErrorBubbling();
``` ```
@ -962,13 +962,13 @@
Before: Before:
``` ```php
if ($form->hasChildren()) { if ($form->hasChildren()) {
``` ```
After: After:
``` ```php
if (count($form) > 0) { if (count($form) > 0) {
``` ```
@ -976,13 +976,13 @@
Before: Before:
``` ```php
$form->bindRequest($request); $form->bindRequest($request);
``` ```
After: After:
``` ```php
$form->bind($request); $form->bind($request);
``` ```
@ -992,7 +992,7 @@
Before: Before:
``` ```php
$builder->add('name', 'text', array( $builder->add('name', 'text', array(
'validation_constraint' => new NotBlank(), 'validation_constraint' => new NotBlank(),
)); ));
@ -1000,7 +1000,7 @@
After: After:
``` ```php
$builder->add('name', 'text', array( $builder->add('name', 'text', array(
'constraints' => new NotBlank(), 'constraints' => new NotBlank(),
)); ));
@ -1008,7 +1008,7 @@
Unlike previously, you can also pass a list of constraints now: Unlike previously, you can also pass a list of constraints now:
``` ```php
$builder->add('name', 'text', array( $builder->add('name', 'text', array(
'constraints' => array( 'constraints' => array(
new NotBlank(), new NotBlank(),
@ -1021,7 +1021,7 @@
to the validated group! So if you validate a form in group "Custom" to the validated group! So if you validate a form in group "Custom"
and previously did: and previously did:
``` ```php
$builder->add('name', 'text', array( $builder->add('name', 'text', array(
'validation_constraint' => new NotBlank(), 'validation_constraint' => new NotBlank(),
)); ));
@ -1029,7 +1029,7 @@
Then you need to add the constraint to the group "Custom" now: Then you need to add the constraint to the group "Custom" now:
``` ```php
$builder->add('name', 'text', array( $builder->add('name', 'text', array(
'constraints' => new NotBlank(array('groups' => 'Custom')), 'constraints' => new NotBlank(array('groups' => 'Custom')),
)); ));
@ -1041,7 +1041,7 @@
Before: Before:
``` ```php
$builder->add('scheduledFor', 'date', array( $builder->add('scheduledFor', 'date', array(
'data_timezone' => 'UTC', 'data_timezone' => 'UTC',
'user_timezone' => 'America/New_York', 'user_timezone' => 'America/New_York',
@ -1050,7 +1050,7 @@
After: After:
``` ```php
$builder->add('scheduledFor', 'date', array( $builder->add('scheduledFor', 'date', array(
'model_timezone' => 'UTC', 'model_timezone' => 'UTC',
'view_timezone' => 'America/New_York', 'view_timezone' => 'America/New_York',
@ -1063,13 +1063,13 @@
Before: Before:
``` ```php
$this->get('form.factory')->addType(new MyFormType()); $this->get('form.factory')->addType(new MyFormType());
``` ```
After: After:
``` ```php
$registry = $this->get('form.registry'); $registry = $this->get('form.registry');
$registry->addType($registry->resolveType(new MyFormType())); $registry->addType($registry->resolveType(new MyFormType()));
@ -1098,14 +1098,14 @@
Before: Before:
``` ```php
$view->set('help', 'A text longer than six characters'); $view->set('help', 'A text longer than six characters');
$view->set('error_class', 'max_length_error'); $view->set('error_class', 'max_length_error');
``` ```
After: After:
``` ```php
$view->vars = array_replace($view->vars, array( $view->vars = array_replace($view->vars, array(
'help' => 'A text longer than six characters', 'help' => 'A text longer than six characters',
'error_class' => 'max_length_error', 'error_class' => 'max_length_error',
@ -1114,25 +1114,25 @@
Before: Before:
``` ```php
echo $view->get('error_class'); echo $view->get('error_class');
``` ```
After: After:
``` ```php
echo $view->vars['error_class']; echo $view->vars['error_class'];
``` ```
Before: Before:
``` ```php
if ($view->hasChildren()) { ... if ($view->hasChildren()) { ...
``` ```
After: After:
``` ```php
if (count($view->children)) { ... if (count($view->children)) { ...
``` ```
@ -1147,7 +1147,7 @@
Before: Before:
``` ```php
public function isValid($value, Constraint $constraint) public function isValid($value, Constraint $constraint)
{ {
// ... // ...
@ -1163,7 +1163,7 @@
After: After:
``` ```php
public function isValid($value, Constraint $constraint) public function isValid($value, Constraint $constraint)
{ {
// ... // ...
@ -1185,7 +1185,7 @@
Before: Before:
``` ```php
public function isPropertyValid(ExecutionContext $context) public function isPropertyValid(ExecutionContext $context)
{ {
// ... // ...
@ -1197,7 +1197,7 @@
After: After:
``` ```php
public function isPropertyValid(ExecutionContext $context) public function isPropertyValid(ExecutionContext $context)
{ {
// ... // ...
@ -1216,7 +1216,7 @@
Before: Before:
``` ```php
public function isValid($value, Constraint $constraint) public function isValid($value, Constraint $constraint)
{ {
// ... // ...
@ -1232,7 +1232,7 @@
After: After:
``` ```php
public function validate($value, Constraint $constraint) public function validate($value, Constraint $constraint)
{ {
// ... // ...
@ -1259,14 +1259,14 @@
Before: Before:
``` ```php
/** @Assert\Valid */ /** @Assert\Valid */
private $recursiveCollection; private $recursiveCollection;
``` ```
After: After:
``` ```php
/** @Assert\Valid(deep = true) */ /** @Assert\Valid(deep = true) */
private $recursiveCollection; private $recursiveCollection;
``` ```
@ -1276,28 +1276,28 @@
Before: Before:
``` ```php
/** @Assert\Size(min = 2, max = 16) */ /** @Assert\Size(min = 2, max = 16) */
private $numberOfCpus; private $numberOfCpus;
``` ```
After: After:
``` ```php
/** @Assert\Range(min = 2, max = 16) */ /** @Assert\Range(min = 2, max = 16) */
private $numberOfCpus; private $numberOfCpus;
``` ```
Before: Before:
``` ```php
/** @Assert\Min(2) */ /** @Assert\Min(2) */
private $numberOfCpus; private $numberOfCpus;
``` ```
After: After:
``` ```php
/** @Assert\Range(min = 2) */ /** @Assert\Range(min = 2) */
private $numberOfCpus; private $numberOfCpus;
``` ```
@ -1307,14 +1307,14 @@
Before: Before:
``` ```php
/** @Assert\MinLength(8) */ /** @Assert\MinLength(8) */
private $password; private $password;
``` ```
After: After:
``` ```php
/** @Assert\Length(min = 8) */ /** @Assert\Length(min = 8) */
private $password; private $password;
``` ```
@ -1325,14 +1325,14 @@
Before: Before:
``` ```php
$validator = ValidatorFactory::buildDefault(array('path/to/mapping.xml')) $validator = ValidatorFactory::buildDefault(array('path/to/mapping.xml'))
->getValidator(); ->getValidator();
``` ```
After: After:
``` ```php
$validator = Validation::createValidatorBuilder() $validator = Validation::createValidatorBuilder()
->addXmlMapping('path/to/mapping.xml') ->addXmlMapping('path/to/mapping.xml')
->getValidator(); ->getValidator();
@ -1349,7 +1349,7 @@
Before: Before:
``` ```jinja
{% if app.session.hasFlash('notice') %} {% if app.session.hasFlash('notice') %}
<div class="flash-notice"> <div class="flash-notice">
{{ app.session.getFlash('notice') }} {{ app.session.getFlash('notice') }}
@ -1358,7 +1358,7 @@
``` ```
After: After:
``` ```jinja
{% for flashMessage in app.session.flashbag.get('notice') %} {% for flashMessage in app.session.flashbag.get('notice') %}
<div class="flash-notice"> <div class="flash-notice">
{{ flashMessage }} {{ flashMessage }}
@ -1368,7 +1368,7 @@
You can process all flash messages in a single loop with: You can process all flash messages in a single loop with:
``` ```jinja
{% for type, flashMessages in app.session.flashbag.all() %} {% for type, flashMessages in app.session.flashbag.all() %}
{% for flashMessage in flashMessages %} {% for flashMessage in flashMessages %}
<div class="flash-{{ type }}"> <div class="flash-{{ type }}">
@ -1433,7 +1433,7 @@
Before: Before:
``` ```yaml
framework: framework:
session: session:
lifetime: 3600 lifetime: 3600
@ -1445,7 +1445,7 @@
After: After:
``` ```yaml
framework: framework:
session: session:
cookie_lifetime: 3600 cookie_lifetime: 3600
@ -1457,7 +1457,7 @@
Added `handler_id`, defaults to `session.handler.native_file`. Added `handler_id`, defaults to `session.handler.native_file`.
``` ```yaml
framework: framework:
session: session:
storage_id: session.storage.native storage_id: session.storage.native
@ -1466,7 +1466,7 @@ Added `handler_id`, defaults to `session.handler.native_file`.
To use mock session storage use the following. `handler_id` is irrelevant in this context. To use mock session storage use the following. `handler_id` is irrelevant in this context.
``` ```yaml
framework: framework:
session: session:
storage_id: session.storage.mock_file storage_id: session.storage.mock_file

View File

@ -7,13 +7,13 @@
Before: Before:
``` ```jinja
{% render 'BlogBundle:Post:list' with { 'limit': 2 }, { 'alt': 'BlogBundle:Post:error' } %} {% render 'BlogBundle:Post:list' with { 'limit': 2 }, { 'alt': 'BlogBundle:Post:error' } %}
``` ```
After: After:
``` ```jinja
{% render controller('BlogBundle:Post:list', { 'limit': 2 }), { 'alt': 'BlogBundle:Post:error' } %} {% render controller('BlogBundle:Post:list', { 'limit': 2 }), { 'alt': 'BlogBundle:Post:error' } %}
{# Or: #} {# Or: #}
{{ render(controller('BlogBundle:Post:list', { 'limit': 2 }), { 'alt': 'BlogBundle:Post:error'}) }} {{ render(controller('BlogBundle:Post:list', { 'limit': 2 }), { 'alt': 'BlogBundle:Post:error'}) }}
@ -29,7 +29,7 @@
Before: Before:
``` ```jinja
{% render 'BlogBundle:Post:list' with { 'limit': 2 }, {'standalone': true} %} {% render 'BlogBundle:Post:list' with { 'limit': 2 }, {'standalone': true} %}
{% render 'BlogBundle:Post:list' with { 'limit': 2 }, {'standalone': false} %} {% render 'BlogBundle:Post:list' with { 'limit': 2 }, {'standalone': false} %}
{% render 'BlogBundle:Post:list' with { 'limit': 2 }, {'standalone': 'js'} %} {% render 'BlogBundle:Post:list' with { 'limit': 2 }, {'standalone': 'js'} %}
@ -37,7 +37,7 @@
After: After:
``` ```jinja
{{ render(controller('BlogBundle:Post:list', { 'limit': 2 }), { 'strategy': 'esi'}) }} {{ render(controller('BlogBundle:Post:list', { 'limit': 2 }), { 'strategy': 'esi'}) }}
{{ render(controller('BlogBundle:Post:list', { 'limit': 2 }), { 'strategy': 'inline'}) }} {{ render(controller('BlogBundle:Post:list', { 'limit': 2 }), { 'strategy': 'inline'}) }}
{{ render(controller('BlogBundle:Post:list', { 'limit': 2 }), { 'strategy': 'hinclude'}) }} {{ render(controller('BlogBundle:Post:list', { 'limit': 2 }), { 'strategy': 'hinclude'}) }}
@ -65,7 +65,7 @@
You should now use the `AcceptHeader` class which give you fluent methods to You should now use the `AcceptHeader` class which give you fluent methods to
parse request accept-* headers. Some examples: parse request accept-* headers. Some examples:
``` ```php
$accept = AcceptHeader::fromString($request->headers->get('Accept')); $accept = AcceptHeader::fromString($request->headers->get('Accept'));
if ($accept->has('text/html') { if ($accept->has('text/html') {
$item = $accept->get('html'); $item = $accept->get('html');
@ -95,7 +95,7 @@
Before: Before:
``` ```jinja
{{ {{
error.messagePluralization is null error.messagePluralization is null
? error.messageTemplate|trans(error.messageParameters, 'validators') ? error.messageTemplate|trans(error.messageParameters, 'validators')
@ -105,7 +105,7 @@
After: After:
``` ```jinja
{{ error.message }} {{ error.message }}
``` ```
@ -117,7 +117,7 @@
Before: Before:
``` ```php
use Symfony\Component\Form\Extensions\Core\DataMapper\PropertyPathMapper; use Symfony\Component\Form\Extensions\Core\DataMapper\PropertyPathMapper;
class CustomMapper extends PropertyPathMapper class CustomMapper extends PropertyPathMapper
@ -133,7 +133,7 @@
After: After:
``` ```php
use Symfony\Component\Form\Extensions\Core\DataMapper\PropertyPathMapper; use Symfony\Component\Form\Extensions\Core\DataMapper\PropertyPathMapper;
class CustomMapper extends PropertyPathMapper class CustomMapper extends PropertyPathMapper
@ -163,7 +163,7 @@
Before: Before:
``` ```php
use Symfony\Component\Form\Util\PropertyPath; use Symfony\Component\Form\Util\PropertyPath;
use Symfony\Component\Form\Util\PropertyPathBuilder; use Symfony\Component\Form\Util\PropertyPathBuilder;
use Symfony\Component\Form\Util\PropertyPathInterface; use Symfony\Component\Form\Util\PropertyPathInterface;
@ -176,7 +176,7 @@
After: After:
``` ```php
use Symfony\Component\PropertyAccess\PropertyPath; use Symfony\Component\PropertyAccess\PropertyPath;
use Symfony\Component\PropertyAccess\PropertyPathBuilder; use Symfony\Component\PropertyAccess\PropertyPathBuilder;
use Symfony\Component\PropertyAccess\PropertyPathInterface; use Symfony\Component\PropertyAccess\PropertyPathInterface;
@ -192,7 +192,7 @@
Before: Before:
``` ```php
use Symfony\Component\Form\Util\FormUtil; use Symfony\Component\Form\Util\FormUtil;
$singular = FormUtil::singularify($plural); $singular = FormUtil::singularify($plural);
@ -200,7 +200,7 @@
After: After:
``` ```php
use Symfony\Component\PropertyAccess\StringUtil; use Symfony\Component\PropertyAccess\StringUtil;
$singular = StringUtil::singularify($plural); $singular = StringUtil::singularify($plural);
@ -211,7 +211,7 @@
Before: Before:
``` ```php
use Symfony\Component\Form\Util\PropertyPath; use Symfony\Component\Form\Util\PropertyPath;
$propertyPath = new PropertyPath('some.path'); $propertyPath = new PropertyPath('some.path');
@ -222,7 +222,7 @@
After (alternative 1): After (alternative 1):
``` ```php
use Symfony\Component\PropertyAccess\PropertyAccess; use Symfony\Component\PropertyAccess\PropertyAccess;
$propertyAccessor = PropertyAccess::getPropertyAccessor(); $propertyAccessor = PropertyAccess::getPropertyAccessor();
@ -233,7 +233,7 @@
After (alternative 2): After (alternative 2):
``` ```php
use Symfony\Component\PropertyAccess\PropertyAccess; use Symfony\Component\PropertyAccess\PropertyAccess;
use Symfony\Component\PropertyAccess\PropertyPath; use Symfony\Component\PropertyAccess\PropertyPath;
@ -253,7 +253,7 @@
Before: Before:
``` ```php
$rootCollection = new RouteCollection(); $rootCollection = new RouteCollection();
$subCollection = new RouteCollection(); $subCollection = new RouteCollection();
$rootCollection->addCollection($subCollection); $rootCollection->addCollection($subCollection);
@ -262,7 +262,7 @@
After: After:
``` ```php
$rootCollection = new RouteCollection(); $rootCollection = new RouteCollection();
$subCollection = new RouteCollection(); $subCollection = new RouteCollection();
$subCollection->add('foo', new Route('/foo')); $subCollection->add('foo', new Route('/foo'));
@ -272,7 +272,7 @@
Also one must call `addCollection` from the bottom to the top hierarchy. Also one must call `addCollection` from the bottom to the top hierarchy.
So the correct sequence is the following (and not the reverse): So the correct sequence is the following (and not the reverse):
``` ```php
$childCollection->addCollection($grandchildCollection); $childCollection->addCollection($grandchildCollection);
$rootCollection->addCollection($childCollection); $rootCollection->addCollection($childCollection);
``` ```
@ -298,7 +298,7 @@
use-case instead. use-case instead.
Before: `$parentCollection->addCollection($collection, '/prefix', array(...), array(...))` Before: `$parentCollection->addCollection($collection, '/prefix', array(...), array(...))`
After: After:
``` ```php
$collection->addPrefix('/prefix', array(...), array(...)); $collection->addPrefix('/prefix', array(...), array(...));
$parentCollection->addCollection($collection); $parentCollection->addCollection($collection);
``` ```
@ -312,7 +312,7 @@
Before: Before:
``` ```php
use Symfony\Component\Validator\ExecutionContext; use Symfony\Component\Validator\ExecutionContext;
public function validateCustomLogic(ExecutionContext $context) public function validateCustomLogic(ExecutionContext $context)
@ -320,7 +320,7 @@
After: After:
``` ```php
use Symfony\Component\Validator\ExecutionContextInterface; use Symfony\Component\Validator\ExecutionContextInterface;
public function validateCustomLogic(ExecutionContextInterface $context) public function validateCustomLogic(ExecutionContextInterface $context)
@ -331,7 +331,7 @@
Before: Before:
``` ```php
use Symfony\Component\Validator\ConstraintValidatorInterface; use Symfony\Component\Validator\ConstraintValidatorInterface;
use Symfony\Component\Validator\ExecutionContext; use Symfony\Component\Validator\ExecutionContext;
@ -346,7 +346,7 @@
After: After:
``` ```php
use Symfony\Component\Validator\ConstraintValidatorInterface; use Symfony\Component\Validator\ConstraintValidatorInterface;
use Symfony\Component\Validator\ExecutionContextInterface; use Symfony\Component\Validator\ExecutionContextInterface;
@ -391,7 +391,7 @@
Before: Before:
``` ```php
use Symfony\Component\Validator\Mapping\ClassMetadataFactoryInterface; use Symfony\Component\Validator\Mapping\ClassMetadataFactoryInterface;
class MyMetadataFactory implements ClassMetadataFactoryInterface class MyMetadataFactory implements ClassMetadataFactoryInterface
@ -405,7 +405,7 @@
After: After:
``` ```php
use Symfony\Component\Validator\MetadataFactoryInterface; use Symfony\Component\Validator\MetadataFactoryInterface;
use Symfony\Component\Validator\Exception\NoSuchMetadataException; use Symfony\Component\Validator\Exception\NoSuchMetadataException;
@ -432,14 +432,14 @@
Before: Before:
``` ```php
$metadataFactory = $validator->getMetadataFactory(); $metadataFactory = $validator->getMetadataFactory();
$metadata = $metadataFactory->getClassMetadata('Vendor\MyClass'); $metadata = $metadataFactory->getClassMetadata('Vendor\MyClass');
``` ```
After: After:
``` ```php
$metadataFactory = $validator->getMetadataFactory(); $metadataFactory = $validator->getMetadataFactory();
$metadata = $metadataFactory->getMetadataFor('Vendor\MyClass'); $metadata = $metadataFactory->getMetadataFor('Vendor\MyClass');
``` ```
@ -451,7 +451,7 @@
Before: Before:
``` ```php
use Symfony\Component\Validator\ExecutionContext; use Symfony\Component\Validator\ExecutionContext;
public function validateCustomLogic(ExecutionContext $context) public function validateCustomLogic(ExecutionContext $context)
@ -471,7 +471,7 @@
After: After:
``` ```php
use Symfony\Component\Validator\ExecutionContextInterface; use Symfony\Component\Validator\ExecutionContextInterface;
public function validateCustomLogic(ExecutionContextInterface $context) public function validateCustomLogic(ExecutionContextInterface $context)
@ -488,7 +488,7 @@
Before: Before:
``` ```php
use Symfony\Component\Validator\ExecutionContext; use Symfony\Component\Validator\ExecutionContext;
public function validateCustomLogic(ExecutionContext $context) public function validateCustomLogic(ExecutionContext $context)
@ -501,7 +501,7 @@
After: After:
``` ```php
use Symfony\Component\Validator\ExecutionContextInterface; use Symfony\Component\Validator\ExecutionContextInterface;
public function validateCustomLogic(ExecutionContextInterface $context) public function validateCustomLogic(ExecutionContextInterface $context)
@ -519,7 +519,7 @@
Before: Before:
``` ```php
use Symfony\Component\Validator\ExecutionContext; use Symfony\Component\Validator\ExecutionContext;
public function validateCustomLogic(ExecutionContext $context) public function validateCustomLogic(ExecutionContext $context)
@ -534,7 +534,7 @@
After: After:
``` ```php
use Symfony\Component\Validator\ExecutionContextInterface; use Symfony\Component\Validator\ExecutionContextInterface;
public function validateCustomLogic(ExecutionContextInterface $context) public function validateCustomLogic(ExecutionContextInterface $context)
@ -553,20 +553,20 @@
Before: Before:
``` ```php
<?php echo $view['actions']->render('BlogBundle:Post:list', array('limit' => 2), array('alt' => 'BlogBundle:Post:error')) ?> <?php echo $view['actions']->render('BlogBundle:Post:list', array('limit' => 2), array('alt' => 'BlogBundle:Post:error')) ?>
``` ```
After: After:
``` ```php
<?php echo $view['actions']->render($view['router']->generate('post_list', array('limit' => 2)), array('alt' => 'BlogBundle:Post:error')) ?> <?php echo $view['actions']->render($view['router']->generate('post_list', array('limit' => 2)), array('alt' => 'BlogBundle:Post:error')) ?>
``` ```
where `post_list` is the route name for the `BlogBundle:Post:list` where `post_list` is the route name for the `BlogBundle:Post:list`
controller, or if you don't want to create a route: controller, or if you don't want to create a route:
``` ```php
<?php echo $view['actions']->render(new ControllerReference('BlogBundle:Post:list', array('limit' => 2)), array('alt' => 'BlogBundle:Post:error')) ?> <?php echo $view['actions']->render(new ControllerReference('BlogBundle:Post:list', array('limit' => 2)), array('alt' => 'BlogBundle:Post:error')) ?>
``` ```
@ -577,7 +577,7 @@
Before: Before:
``` ```yaml
# app/config/config.yml # app/config/config.yml
framework: framework:
trust_proxy_headers: false trust_proxy_headers: false
@ -585,7 +585,7 @@
After: After:
``` ```yaml
# app/config/config.yml # app/config/config.yml
framework: framework:
trusted_proxies: ['127.0.0.1', '10.0.0.1'] # a list of proxy IPs you trust trusted_proxies: ['127.0.0.1', '10.0.0.1'] # a list of proxy IPs you trust
@ -598,13 +598,13 @@
Before: Before:
``` ```php
use Symfony\Component\Security\Core\Validator\Constraint\UserPassword; use Symfony\Component\Security\Core\Validator\Constraint\UserPassword;
``` ```
After: (note the `s` at the end of `Constraint`) After: (note the `s` at the end of `Constraint`)
``` ```php
use Symfony\Component\Security\Core\Validator\Constraints\UserPassword; use Symfony\Component\Security\Core\Validator\Constraints\UserPassword;
``` ```
@ -612,7 +612,7 @@
``service`` option that allows to specify a custom validator service name in ``service`` option that allows to specify a custom validator service name in
order to validate the current logged-in user's password. order to validate the current logged-in user's password.
``` ```php
use Symfony\Component\Security\Core\Validator\Constraints\UserPassword; use Symfony\Component\Security\Core\Validator\Constraints\UserPassword;
$constraint = new UserPassword(array( $constraint = new UserPassword(array(
@ -628,14 +628,14 @@
Before: Before:
``` ```php
use Symfony\Component\Security\Core\Validator\Constraint\UserPassword; use Symfony\Component\Security\Core\Validator\Constraint\UserPassword;
use Symfony\Component\Security\Core\Validator\Constraint\UserPasswordValidator; use Symfony\Component\Security\Core\Validator\Constraint\UserPasswordValidator;
``` ```
After: After:
``` ```php
use Symfony\Component\Security\Core\Validator\Constraints\UserPassword; use Symfony\Component\Security\Core\Validator\Constraints\UserPassword;
use Symfony\Component\Security\Core\Validator\Constraints\UserPasswordValidator; use Symfony\Component\Security\Core\Validator\Constraints\UserPasswordValidator;
``` ```

View File

@ -41,7 +41,7 @@ Form
Before: Before:
``` ```php
use Symfony\Component\Form\DataMapperInterface; use Symfony\Component\Form\DataMapperInterface;
class MyDataMapper class MyDataMapper
@ -60,7 +60,7 @@ Form
After: After:
``` ```php
use Symfony\Component\Form\DataMapperInterface; use Symfony\Component\Form\DataMapperInterface;
class MyDataMapper class MyDataMapper
@ -84,7 +84,7 @@ Form
Before: Before:
``` ```php
use Symfony\Component\Form\Util\VirtualFormAwareIterator; use Symfony\Component\Form\Util\VirtualFormAwareIterator;
public function mapFormsToData(array $forms, $data) public function mapFormsToData(array $forms, $data)
@ -101,7 +101,7 @@ Form
After: After:
``` ```php
public function mapFormsToData($forms, $data) public function mapFormsToData($forms, $data)
{ {
foreach ($forms as $form) { foreach ($forms as $form) {
@ -121,7 +121,7 @@ Form
Before: Before:
``` ```php
$form = $factory->create('form'); $form = $factory->create('form');
$form->add($factory->createNamed('field', 'text')); $form->add($factory->createNamed('field', 'text'));
``` ```
@ -135,7 +135,7 @@ Form
After (Alternative 1): After (Alternative 1):
``` ```php
$form = $factory->create('form'); $form = $factory->create('form');
$form->add($factory->createNamed('field', 'text', array(), array( $form->add($factory->createNamed('field', 'text', array(), array(
'auto_initialize' => false, 'auto_initialize' => false,
@ -147,7 +147,7 @@ Form
After (Alternative 2): After (Alternative 2):
``` ```php
$builder = $factory->createBuilder('form'); $builder = $factory->createBuilder('form');
$builder->add($factory->createBuilder('field', 'text')); $builder->add($factory->createBuilder('field', 'text'));
$form = $builder->getForm(); $form = $builder->getForm();
@ -157,14 +157,14 @@ Form
After (Alternative 3): After (Alternative 3):
``` ```php
$form = $factory->create('form'); $form = $factory->create('form');
$form->add('field', 'text'); $form->add('field', 'text');
``` ```
After (Alternative 4): After (Alternative 4):
``` ```php
$builder = $factory->createBuilder('form'); $builder = $factory->createBuilder('form');
$builder->add('field', 'text'); $builder->add('field', 'text');
$form = $builder->getForm(); $form = $builder->getForm();
@ -180,7 +180,7 @@ Form
Before: Before:
``` ```php
$builder->add('field', 'text', array( $builder->add('field', 'text', array(
'data' => $defaultData ?: null, 'data' => $defaultData ?: null,
)); ));
@ -188,7 +188,7 @@ Form
After: After:
``` ```php
$options = array(); $options = array();
if ($defaultData) { if ($defaultData) {
$options['data'] = $defaultData; $options['data'] = $defaultData;
@ -203,7 +203,7 @@ PropertyAccess
even if a non-public match was found. This means that the property "author" even if a non-public match was found. This means that the property "author"
in the following class will now correctly be found: in the following class will now correctly be found:
``` ```php
class Article class Article
{ {
public $author; public $author;
@ -224,7 +224,7 @@ PropertyAccess
Before: Before:
``` ```php
use Symfony\Component\PropertyAccess\Exception\PropertyAccessDeniedException; use Symfony\Component\PropertyAccess\Exception\PropertyAccessDeniedException;
use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException; use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException;
@ -239,7 +239,7 @@ PropertyAccess
After: After:
``` ```php
use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException; use Symfony\Component\PropertyAccess\Exception\NoSuchPropertyException;
try { try {
@ -257,7 +257,7 @@ DomCrawler
Before: Before:
``` ```php
$data = $crawler->each(function ($node, $i) { $data = $crawler->each(function ($node, $i) {
return $node->nodeValue; return $node->nodeValue;
}); });
@ -265,7 +265,7 @@ DomCrawler
After: After:
``` ```php
$data = $crawler->each(function ($crawler, $i) { $data = $crawler->each(function ($crawler, $i) {
return $crawler->text(); return $crawler->text();
}); });
@ -280,13 +280,13 @@ Console
Before: Before:
``` ```php
if (OutputInterface::VERBOSITY_VERBOSE === $output->getVerbosity()) { ... } if (OutputInterface::VERBOSITY_VERBOSE === $output->getVerbosity()) { ... }
``` ```
After: After:
``` ```php
if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { ... } if (OutputInterface::VERBOSITY_VERBOSE <= $output->getVerbosity()) { ... }
``` ```

View File

@ -25,13 +25,13 @@ UPGRADE FROM 2.x to 3.0
Before: Before:
``` ```php
$form->bind(array(...)); $form->bind(array(...));
``` ```
After: After:
``` ```php
$form->submit(array(...)); $form->submit(array(...));
``` ```
@ -42,7 +42,7 @@ UPGRADE FROM 2.x to 3.0
Before: Before:
``` ```php
if ('POST' === $request->getMethod()) { if ('POST' === $request->getMethod()) {
$form->bind($request); $form->bind($request);
@ -54,7 +54,7 @@ UPGRADE FROM 2.x to 3.0
After: After:
``` ```php
$form->handleRequest($request); $form->handleRequest($request);
if ($form->isValid()) { if ($form->isValid()) {
@ -65,7 +65,7 @@ UPGRADE FROM 2.x to 3.0
If you want to test whether the form was submitted separately, you can use If you want to test whether the form was submitted separately, you can use
the method `isSubmitted()`: the method `isSubmitted()`:
``` ```php
$form->handleRequest($request); $form->handleRequest($request);
if ($form->isSubmitted()) { if ($form->isSubmitted()) {
@ -82,7 +82,7 @@ UPGRADE FROM 2.x to 3.0
Before: Before:
``` ```php
$builder->addEventListener(FormEvents::PRE_BIND, function (FormEvent $event) { $builder->addEventListener(FormEvents::PRE_BIND, function (FormEvent $event) {
// ... // ...
}); });
@ -90,7 +90,7 @@ UPGRADE FROM 2.x to 3.0
After: After:
``` ```php
$builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) { $builder->addEventListener(FormEvents::PRE_SUBMIT, function (FormEvent $event) {
// ... // ...
}); });
@ -100,7 +100,7 @@ UPGRADE FROM 2.x to 3.0
Before: Before:
``` ```php
$builder->add('address', 'form', array( $builder->add('address', 'form', array(
'virtual' => true, 'virtual' => true,
)); ));
@ -108,7 +108,7 @@ UPGRADE FROM 2.x to 3.0
After: After:
``` ```php
$builder->add('address', 'form', array( $builder->add('address', 'form', array(
'inherit_data' => true, 'inherit_data' => true,
)); ));
@ -118,7 +118,7 @@ UPGRADE FROM 2.x to 3.0
Before: Before:
``` ```php
use Symfony\Component\Form\Util\VirtualFormAwareIterator; use Symfony\Component\Form\Util\VirtualFormAwareIterator;
$iterator = new VirtualFormAwareIterator($forms); $iterator = new VirtualFormAwareIterator($forms);
@ -126,7 +126,7 @@ UPGRADE FROM 2.x to 3.0
After: After:
``` ```php
use Symfony\Component\Form\Util\InheritDataAwareIterator; use Symfony\Component\Form\Util\InheritDataAwareIterator;
$iterator = new InheritDataAwareIterator($forms); $iterator = new InheritDataAwareIterator($forms);
@ -136,7 +136,7 @@ UPGRADE FROM 2.x to 3.0
Before: Before:
``` ```php
use Symfony\Component\Form\Tests\Extension\Core\Type\TypeTestCase use Symfony\Component\Form\Tests\Extension\Core\Type\TypeTestCase
class MyTypeTest extends TypeTestCase class MyTypeTest extends TypeTestCase
@ -147,7 +147,7 @@ UPGRADE FROM 2.x to 3.0
After: After:
``` ```php
use Symfony\Component\Form\Test\TypeTestCase; use Symfony\Component\Form\Test\TypeTestCase;
class MyTypeTest extends TypeTestCase class MyTypeTest extends TypeTestCase
@ -166,7 +166,7 @@ UPGRADE FROM 2.x to 3.0
Before: Before:
``` ```php
<form method="post" action="http://example.com" <?php echo $view['form']->enctype($form) ?>> <form method="post" action="http://example.com" <?php echo $view['form']->enctype($form) ?>>
... ...
</form> </form>
@ -174,7 +174,7 @@ UPGRADE FROM 2.x to 3.0
After: After:
``` ```php
<?php echo $view['form']->start($form) ?> <?php echo $view['form']->start($form) ?>
... ...
<?php echo $view['form']->end($form) ?> <?php echo $view['form']->end($form) ?>
@ -186,7 +186,7 @@ UPGRADE FROM 2.x to 3.0
Alternative 1: Alternative 1:
``` ```php
$form = $this->createForm('my_form', $formData, array( $form = $this->createForm('my_form', $formData, array(
'method' => 'PUT', 'method' => 'PUT',
'action' => $this->generateUrl('target_route'), 'action' => $this->generateUrl('target_route'),
@ -195,7 +195,7 @@ UPGRADE FROM 2.x to 3.0
Alternative 2: Alternative 2:
``` ```php
$form = $this->createFormBuilder($formData) $form = $this->createFormBuilder($formData)
// ... // ...
->setMethod('PUT') ->setMethod('PUT')
@ -205,7 +205,7 @@ UPGRADE FROM 2.x to 3.0
It is also possible to override the method and the action in the template: It is also possible to override the method and the action in the template:
``` ```php
<?php echo $view['form']->start($form, array('method' => 'GET', 'action' => 'http://example.com')) ?> <?php echo $view['form']->start($form, array('method' => 'GET', 'action' => 'http://example.com')) ?>
... ...
<?php echo $view['form']->end($form) ?> <?php echo $view['form']->end($form) ?>
@ -259,7 +259,7 @@ UPGRADE FROM 2.x to 3.0
Before: Before:
``` ```php
use Symfony\Component\PropertyAccess\PropertyAccess; use Symfony\Component\PropertyAccess\PropertyAccess;
$accessor = PropertyAccess::getPropertyAccessor(); $accessor = PropertyAccess::getPropertyAccessor();
@ -267,7 +267,7 @@ UPGRADE FROM 2.x to 3.0
After: After:
``` ```php
use Symfony\Component\PropertyAccess\PropertyAccess; use Symfony\Component\PropertyAccess\PropertyAccess;
$accessor = PropertyAccess::createPropertyAccessor(); $accessor = PropertyAccess::createPropertyAccessor();
@ -282,17 +282,21 @@ UPGRADE FROM 2.x to 3.0
Before: Before:
``` ```yaml
article_edit: article_edit:
pattern: /article/{id} pattern: /article/{id}
requirements: { '_method': 'POST|PUT', '_scheme': 'https', 'id': '\d+' } requirements: { '_method': 'POST|PUT', '_scheme': 'https', 'id': '\d+' }
```
```xml
<route id="article_edit" pattern="/article/{id}"> <route id="article_edit" pattern="/article/{id}">
<requirement key="_method">POST|PUT</requirement> <requirement key="_method">POST|PUT</requirement>
<requirement key="_scheme">https</requirement> <requirement key="_scheme">https</requirement>
<requirement key="id">\d+</requirement> <requirement key="id">\d+</requirement>
</route> </route>
```
```php
$route = new Route(); $route = new Route();
$route->setPattern('/article/{id}'); $route->setPattern('/article/{id}');
$route->setRequirement('_method', 'POST|PUT'); $route->setRequirement('_method', 'POST|PUT');
@ -301,17 +305,21 @@ UPGRADE FROM 2.x to 3.0
After: After:
``` ```yaml
article_edit: article_edit:
path: /article/{id} path: /article/{id}
methods: [POST, PUT] methods: [POST, PUT]
schemes: https schemes: https
requirements: { 'id': '\d+' } requirements: { 'id': '\d+' }
```
```xml
<route id="article_edit" path="/article/{id}" methods="POST PUT" schemes="https"> <route id="article_edit" path="/article/{id}" methods="POST PUT" schemes="https">
<requirement key="id">\d+</requirement> <requirement key="id">\d+</requirement>
</route> </route>
```
```php
$route = new Route(); $route = new Route();
$route->setPath('/article/{id}'); $route->setPath('/article/{id}');
$route->setMethods(array('POST', 'PUT')); $route->setMethods(array('POST', 'PUT'));
@ -332,7 +340,7 @@ UPGRADE FROM 2.x to 3.0
Before: Before:
``` ```php
<form method="post" action="http://example.com" {{ form_enctype(form) }}> <form method="post" action="http://example.com" {{ form_enctype(form) }}>
... ...
</form> </form>
@ -340,7 +348,7 @@ UPGRADE FROM 2.x to 3.0
After: After:
``` ```jinja
{{ form_start(form) }} {{ form_start(form) }}
... ...
{{ form_end(form) }} {{ form_end(form) }}
@ -352,7 +360,7 @@ UPGRADE FROM 2.x to 3.0
Alternative 1: Alternative 1:
``` ```php
$form = $this->createForm('my_form', $formData, array( $form = $this->createForm('my_form', $formData, array(
'method' => 'PUT', 'method' => 'PUT',
'action' => $this->generateUrl('target_route'), 'action' => $this->generateUrl('target_route'),
@ -361,7 +369,7 @@ UPGRADE FROM 2.x to 3.0
Alternative 2: Alternative 2:
``` ```php
$form = $this->createFormBuilder($formData) $form = $this->createFormBuilder($formData)
// ... // ...
->setMethod('PUT') ->setMethod('PUT')
@ -371,7 +379,7 @@ UPGRADE FROM 2.x to 3.0
It is also possible to override the method and the action in the template: It is also possible to override the method and the action in the template:
``` ```jinja
{{ form_start(form, {'method': 'GET', 'action': 'http://example.com'}) }} {{ form_start(form, {'method': 'GET', 'action': 'http://example.com'}) }}
... ...
{{ form_end(form) }} {{ form_end(form) }}
@ -385,7 +393,7 @@ UPGRADE FROM 2.x to 3.0
Before: Before:
``` ```php
use Symfony\Component\Validator\Constraints as Assert; use Symfony\Component\Validator\Constraints as Assert;
/** /**
@ -399,7 +407,7 @@ UPGRADE FROM 2.x to 3.0
After: After:
``` ```php
use Symfony\Component\Validator\Constraints as Assert; use Symfony\Component\Validator\Constraints as Assert;
/** /**
@ -417,12 +425,12 @@ UPGRADE FROM 2.x to 3.0
Before: Before:
``` ```php
Yaml::parse($fileName); Yaml::parse($fileName);
``` ```
After: After:
``` ```php
Yaml::parse(file_get_contents($fileName)); Yaml::parse(file_get_contents($fileName));
``` ```

View File

@ -9,51 +9,63 @@ standard or the PEAR naming convention.
First, register the autoloader: First, register the autoloader:
```php
require_once __DIR__.'/src/Symfony/Component/ClassLoader/UniversalClassLoader.php'; require_once __DIR__.'/src/Symfony/Component/ClassLoader/UniversalClassLoader.php';
use Symfony\Component\ClassLoader\UniversalClassLoader; use Symfony\Component\ClassLoader\UniversalClassLoader;
$loader = new UniversalClassLoader(); $loader = new UniversalClassLoader();
$loader->register(); $loader->register();
```
Then, register some namespaces with the `registerNamespace()` method: Then, register some namespaces with the `registerNamespace()` method:
```php
$loader->registerNamespace('Symfony', __DIR__.'/src'); $loader->registerNamespace('Symfony', __DIR__.'/src');
$loader->registerNamespace('Monolog', __DIR__.'/vendor/monolog/src'); $loader->registerNamespace('Monolog', __DIR__.'/vendor/monolog/src');
```
The `registerNamespace()` method takes a namespace prefix and a path where to The `registerNamespace()` method takes a namespace prefix and a path where to
look for the classes as arguments. look for the classes as arguments.
You can also register a sub-namespaces: You can also register a sub-namespaces:
```php
$loader->registerNamespace('Doctrine\\Common', __DIR__.'/vendor/doctrine-common/lib'); $loader->registerNamespace('Doctrine\\Common', __DIR__.'/vendor/doctrine-common/lib');
```
The order of registration is significant and the first registered namespace The order of registration is significant and the first registered namespace
takes precedence over later registered one. takes precedence over later registered one.
You can also register more than one path for a given namespace: You can also register more than one path for a given namespace:
```php
$loader->registerNamespace('Symfony', array(__DIR__.'/src', __DIR__.'/symfony/src')); $loader->registerNamespace('Symfony', array(__DIR__.'/src', __DIR__.'/symfony/src'));
```
Alternatively, you can use the `registerNamespaces()` method to register more Alternatively, you can use the `registerNamespaces()` method to register more
than one namespace at once: than one namespace at once:
```php
$loader->registerNamespaces(array( $loader->registerNamespaces(array(
'Symfony' => array(__DIR__.'/src', __DIR__.'/symfony/src'), 'Symfony' => array(__DIR__.'/src', __DIR__.'/symfony/src'),
'Doctrine\\Common' => __DIR__.'/vendor/doctrine-common/lib', 'Doctrine\\Common' => __DIR__.'/vendor/doctrine-common/lib',
'Doctrine' => __DIR__.'/vendor/doctrine/lib', 'Doctrine' => __DIR__.'/vendor/doctrine/lib',
'Monolog' => __DIR__.'/vendor/monolog/src', 'Monolog' => __DIR__.'/vendor/monolog/src',
)); ));
```
For better performance, you can use the APC based version of the universal For better performance, you can use the APC based version of the universal
class loader: class loader:
```php
require_once __DIR__.'/src/Symfony/Component/ClassLoader/UniversalClassLoader.php'; require_once __DIR__.'/src/Symfony/Component/ClassLoader/UniversalClassLoader.php';
require_once __DIR__.'/src/Symfony/Component/ClassLoader/ApcUniversalClassLoader.php'; require_once __DIR__.'/src/Symfony/Component/ClassLoader/ApcUniversalClassLoader.php';
use Symfony\Component\ClassLoader\ApcUniversalClassLoader; use Symfony\Component\ClassLoader\ApcUniversalClassLoader;
$loader = new ApcUniversalClassLoader('apc.prefix.'); $loader = new ApcUniversalClassLoader('apc.prefix.');
```
Furthermore, the component provides tools to aggregate classes into a single Furthermore, the component provides tools to aggregate classes into a single
file, which is especially useful to improve performance on servers that do not file, which is especially useful to improve performance on servers that do not

View File

@ -5,10 +5,12 @@ Console eases the creation of beautiful and testable command line interfaces.
The Application object manages the CLI application: The Application object manages the CLI application:
```php
use Symfony\Component\Console\Application; use Symfony\Component\Console\Application;
$console = new Application(); $console = new Application();
$console->run(); $console->run();
```
The ``run()`` method parses the arguments and options passed on the command The ``run()`` method parses the arguments and options passed on the command
line and executes the right command. line and executes the right command.
@ -16,6 +18,7 @@ line and executes the right command.
Registering a new command can easily be done via the ``register()`` method, Registering a new command can easily be done via the ``register()`` method,
which returns a ``Command`` instance: which returns a ``Command`` instance:
```php
use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputOption; use Symfony\Component\Console\Input\InputOption;
@ -33,6 +36,7 @@ which returns a ``Command`` instance:
$output->writeln(sprintf('Dir listing for <info>%s</info>', $dir)); $output->writeln(sprintf('Dir listing for <info>%s</info>', $dir));
}) })
; ;
```
You can also register new commands via classes. You can also register new commands via classes.

View File

@ -6,9 +6,11 @@ CssSelector converts CSS selectors to XPath expressions.
The component only goal is to convert CSS selectors to their XPath The component only goal is to convert CSS selectors to their XPath
equivalents: equivalents:
```php
use Symfony\Component\CssSelector\CssSelector; use Symfony\Component\CssSelector\CssSelector;
print CssSelector::toXPath('div.item > h4 > a'); print CssSelector::toXPath('div.item > h4 > a');
```
HTML and XML are different HTML and XML are different
-------------------------- --------------------------
@ -18,11 +20,13 @@ default. If you need to use this component with `XML` documents, you have to
disable this `HTML` extension. That's because, `HTML` tag & attribute names disable this `HTML` extension. That's because, `HTML` tag & attribute names
are always lower-cased, but case-sensitive in `XML`: are always lower-cased, but case-sensitive in `XML`:
```php
// disable `HTML` extension: // disable `HTML` extension:
CssSelector::disableHtmlExtension(); CssSelector::disableHtmlExtension();
// re-enable `HTML` extension: // re-enable `HTML` extension:
CssSelector::enableHtmlExtension(); CssSelector::enableHtmlExtension();
```
When the `HTML` extension is enabled, tag names are lower-cased, attribute When the `HTML` extension is enabled, tag names are lower-cased, attribute
names are lower-cased, the following extra pseudo-classes are supported: names are lower-cased, the following extra pseudo-classes are supported:

View File

@ -6,12 +6,15 @@ Debug provides tools to make debugging easier.
Enabling all debug tools is as easy as calling the `enable()` method on the Enabling all debug tools is as easy as calling the `enable()` method on the
main `Debug` class: main `Debug` class:
```php
use Symfony\Component\Debug\Debug; use Symfony\Component\Debug\Debug;
Debug::enable(); Debug::enable();
```
You can also use the tools individually: You can also use the tools individually:
```php
use Symfony\Component\Debug\ErrorHandler; use Symfony\Component\Debug\ErrorHandler;
use Symfony\Component\Debug\ExceptionHandler; use Symfony\Component\Debug\ExceptionHandler;
@ -23,6 +26,7 @@ You can also use the tools individually:
} elseif (!ini_get('log_errors') || ini_get('error_log')) { } elseif (!ini_get('log_errors') || ini_get('error_log')) {
ini_set('display_errors', 1); ini_set('display_errors', 1);
} }
```
Note that the `Debug::enable()` call also registers the debug class loader Note that the `Debug::enable()` call also registers the debug class loader
from the Symfony ClassLoader component when available. from the Symfony ClassLoader component when available.

View File

@ -6,6 +6,7 @@ Injection Container.
Here is a simple example that shows how to register services and parameters: Here is a simple example that shows how to register services and parameters:
```php
use Symfony\Component\DependencyInjection\ContainerBuilder; use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference; use Symfony\Component\DependencyInjection\Reference;
@ -17,9 +18,11 @@ Here is a simple example that shows how to register services and parameters:
$sc->setParameter('foo.class', 'Foo'); $sc->setParameter('foo.class', 'Foo');
$sc->get('foo'); $sc->get('foo');
```
Method Calls (Setter Injection): Method Calls (Setter Injection):
```php
$sc = new ContainerBuilder(); $sc = new ContainerBuilder();
$sc $sc
@ -29,11 +32,13 @@ Method Calls (Setter Injection):
$sc->setParameter('bar.class', 'Bar'); $sc->setParameter('bar.class', 'Bar');
$sc->get('bar'); $sc->get('bar');
```
Factory Class: Factory Class:
If your service is retrieved by calling a static method: If your service is retrieved by calling a static method:
```php
$sc = new ContainerBuilder(); $sc = new ContainerBuilder();
$sc $sc
@ -45,6 +50,7 @@ If your service is retrieved by calling a static method:
$sc->setParameter('bar.class', 'Bar'); $sc->setParameter('bar.class', 'Bar');
$sc->get('bar'); $sc->get('bar');
```
File Include: File Include:
@ -52,6 +58,7 @@ For some services, especially those that are difficult or impossible to
autoload, you may need the container to include a file before autoload, you may need the container to include a file before
instantiating your class. instantiating your class.
```php
$sc = new ContainerBuilder(); $sc = new ContainerBuilder();
$sc $sc
@ -62,6 +69,7 @@ instantiating your class.
$sc->setParameter('bar.class', 'Bar'); $sc->setParameter('bar.class', 'Bar');
$sc->get('bar'); $sc->get('bar');
```
Resources Resources
--------- ---------

View File

@ -5,22 +5,26 @@ DomCrawler eases DOM navigation for HTML and XML documents.
If you are familiar with jQuery, DomCrawler is a PHP equivalent: If you are familiar with jQuery, DomCrawler is a PHP equivalent:
```php
use Symfony\Component\DomCrawler\Crawler; use Symfony\Component\DomCrawler\Crawler;
$crawler = new Crawler(); $crawler = new Crawler();
$crawler->addContent('<html><body><p>Hello World!</p></body></html>'); $crawler->addContent('<html><body><p>Hello World!</p></body></html>');
print $crawler->filterXPath('descendant-or-self::body/p')->text(); print $crawler->filterXPath('descendant-or-self::body/p')->text();
```
If you are also using the CssSelector component, you can use CSS Selectors If you are also using the CssSelector component, you can use CSS Selectors
instead of XPath expressions: instead of XPath expressions:
```php
use Symfony\Component\DomCrawler\Crawler; use Symfony\Component\DomCrawler\Crawler;
$crawler = new Crawler(); $crawler = new Crawler();
$crawler->addContent('<html><body><p>Hello World!</p></body></html>'); $crawler->addContent('<html><body><p>Hello World!</p></body></html>');
print $crawler->filter('body > p')->text(); print $crawler->filter('body > p')->text();
```
Resources Resources
--------- ---------

View File

@ -4,6 +4,7 @@ EventDispatcher Component
The Symfony2 EventDispatcher component implements the Mediator pattern in a The Symfony2 EventDispatcher component implements the Mediator pattern in a
simple and effective way to make your projects truly extensible. simple and effective way to make your projects truly extensible.
```php
use Symfony\Component\EventDispatcher\EventDispatcher; use Symfony\Component\EventDispatcher\EventDispatcher;
use Symfony\Component\EventDispatcher\Event; use Symfony\Component\EventDispatcher\Event;
@ -14,6 +15,7 @@ simple and effective way to make your projects truly extensible.
}); });
$dispatcher->dispatch('event_name'); $dispatcher->dispatch('event_name');
```
Resources Resources
--------- ---------

View File

@ -3,6 +3,7 @@ Finder Component
Finder finds files and directories via an intuitive fluent interface. Finder finds files and directories via an intuitive fluent interface.
```php
use Symfony\Component\Finder\Finder; use Symfony\Component\Finder\Finder;
$finder = new Finder(); $finder = new Finder();
@ -17,10 +18,12 @@ Finder finds files and directories via an intuitive fluent interface.
foreach ($iterator as $file) { foreach ($iterator as $file) {
print $file->getRealpath()."\n"; print $file->getRealpath()."\n";
} }
```
But you can also use it to find files stored remotely like in this example where But you can also use it to find files stored remotely like in this example where
we are looking for files on Amazon S3: we are looking for files on Amazon S3:
```php
$s3 = new \Zend_Service_Amazon_S3($key, $secret); $s3 = new \Zend_Service_Amazon_S3($key, $secret);
$s3->registerStreamWrapper("s3"); $s3->registerStreamWrapper("s3");
@ -29,6 +32,7 @@ we are looking for files on Amazon S3:
foreach ($finder->in('s3://bucket-name') as $file) { foreach ($finder->in('s3://bucket-name') as $file) {
print $file->getFilename()."\n"; print $file->getFilename()."\n";
} }
```
Resources Resources
--------- ---------
@ -38,4 +42,3 @@ You can run the unit tests with the following command:
$ cd path/to/Symfony/Component/Finder/ $ cd path/to/Symfony/Component/Finder/
$ composer.phar install $ composer.phar install
$ phpunit $ phpunit

View File

@ -9,21 +9,27 @@ sessions, ...
In this example, we get a Request object from the current PHP global In this example, we get a Request object from the current PHP global
variables: variables:
```php
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Response;
$request = Request::createFromGlobals(); $request = Request::createFromGlobals();
echo $request->getPathInfo(); echo $request->getPathInfo();
```
You can also create a Request directly -- that's interesting for unit testing: You can also create a Request directly -- that's interesting for unit testing:
```php
$request = Request::create('/?foo=bar', 'GET'); $request = Request::create('/?foo=bar', 'GET');
echo $request->getPathInfo(); echo $request->getPathInfo();
```
And here is how to create and send a Response: And here is how to create and send a Response:
```php
$response = new Response('Not Found', 404, array('Content-Type' => 'text/plain')); $response = new Response('Not Found', 404, array('Content-Type' => 'text/plain'));
$response->send(); $response->send();
```
The Request and the Response classes have many other methods that implement The Request and the Response classes have many other methods that implement
the HTTP specification. the HTTP specification.
@ -33,10 +39,12 @@ Loading
If you are not using Composer but are using PHP 5.3.x, you must add the following to your autoloader: If you are not using Composer but are using PHP 5.3.x, you must add the following to your autoloader:
```php
// SessionHandlerInterface // SessionHandlerInterface
if (!interface_exists('SessionHandlerInterface')) { if (!interface_exists('SessionHandlerInterface')) {
$loader->registerPrefixFallback(__DIR__.'/../vendor/symfony/src/Symfony/Component/HttpFoundation/Resources/stubs'); $loader->registerPrefixFallback(__DIR__.'/../vendor/symfony/src/Symfony/Component/HttpFoundation/Resources/stubs');
} }
```
Resources Resources
--------- ---------

View File

@ -7,6 +7,7 @@ frameworks.
``HttpKernelInterface`` is the core interface of the Symfony2 full-stack ``HttpKernelInterface`` is the core interface of the Symfony2 full-stack
framework: framework:
```php
interface HttpKernelInterface interface HttpKernelInterface
{ {
/** /**
@ -18,6 +19,7 @@ framework:
*/ */
function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true); function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true);
} }
```
It takes a ``Request`` as an input and should return a ``Response`` as an It takes a ``Request`` as an input and should return a ``Response`` as an
output. Using this interface makes your code compatible with all frameworks output. Using this interface makes your code compatible with all frameworks
@ -27,6 +29,7 @@ free.
Creating a framework based on the Symfony2 components is really easy. Here is Creating a framework based on the Symfony2 components is really easy. Here is
a very simple, but fully-featured framework based on the Symfony2 components: a very simple, but fully-featured framework based on the Symfony2 components:
```php
$routes = new RouteCollection(); $routes = new RouteCollection();
$routes->add('hello', new Route('/hello', array('_controller' => $routes->add('hello', new Route('/hello', array('_controller' =>
function (Request $request) { function (Request $request) {
@ -49,6 +52,7 @@ a very simple, but fully-featured framework based on the Symfony2 components:
$kernel = new HttpKernel($dispatcher, $resolver); $kernel = new HttpKernel($dispatcher, $resolver);
$kernel->handle($request)->send(); $kernel->handle($request)->send();
```
This is all you need to create a flexible framework with the Symfony2 This is all you need to create a flexible framework with the Symfony2
components. components.
@ -56,24 +60,30 @@ components.
Want to add an HTTP reverse proxy and benefit from HTTP caching and Edge Side Want to add an HTTP reverse proxy and benefit from HTTP caching and Edge Side
Includes? Includes?
```php
$kernel = new HttpKernel($dispatcher, $resolver); $kernel = new HttpKernel($dispatcher, $resolver);
$kernel = new HttpCache($kernel, new Store(__DIR__.'/cache')); $kernel = new HttpCache($kernel, new Store(__DIR__.'/cache'));
```
Want to functional test this small framework? Want to functional test this small framework?
```php
$client = new Client($kernel); $client = new Client($kernel);
$crawler = $client->request('GET', '/hello/Fabien'); $crawler = $client->request('GET', '/hello/Fabien');
$this->assertEquals('Fabien', $crawler->filter('p > span')->text()); $this->assertEquals('Fabien', $crawler->filter('p > span')->text());
```
Want nice error pages instead of ugly PHP exceptions? Want nice error pages instead of ugly PHP exceptions?
```php
$dispatcher->addSubscriber(new ExceptionListener(function (Request $request) { $dispatcher->addSubscriber(new ExceptionListener(function (Request $request) {
$msg = 'Something went wrong! ('.$request->get('exception')->getMessage().')'; $msg = 'Something went wrong! ('.$request->get('exception')->getMessage().')';
return new Response($msg, 500); return new Response($msg, 500);
})); }));
```
And that's why the simple looking ``HttpKernelInterface`` is so powerful. It And that's why the simple looking ``HttpKernelInterface`` is so powerful. It
gives you access to a lot of cool features, ready to be used out of the box, gives you access to a lot of cool features, ready to be used out of the box,

View File

@ -12,6 +12,7 @@ The following example demonstrates a Person class with two required options
the default value of "gender" is derived from the passed first name, if the default value of "gender" is derived from the passed first name, if
possible, and may only be one of "male" and "female". possible, and may only be one of "male" and "female".
```php
use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\OptionsResolver\OptionsResolverInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface;
use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\Options;
@ -51,27 +52,33 @@ possible, and may only be one of "male" and "female".
)); ));
} }
} }
```
We can now easily instantiate a Person object: We can now easily instantiate a Person object:
```php
// 'gender' is implicitly set to 'female' // 'gender' is implicitly set to 'female'
$person = new Person(array( $person = new Person(array(
'firstName' => 'Jane', 'firstName' => 'Jane',
'lastName' => 'Doe', 'lastName' => 'Doe',
)); ));
```
We can also override the default values of the optional options: We can also override the default values of the optional options:
```php
$person = new Person(array( $person = new Person(array(
'firstName' => 'Abdullah', 'firstName' => 'Abdullah',
'lastName' => 'Mogashi', 'lastName' => 'Mogashi',
'gender' => 'male', 'gender' => 'male',
'age' => 30, 'age' => 30,
)); ));
```
Options can be added or changed in subclasses by overriding the `setDefaultOptions` Options can be added or changed in subclasses by overriding the `setDefaultOptions`
method: method:
```php
use Symfony\Component\OptionsResolver\OptionsResolver; use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\OptionsResolver\Options; use Symfony\Component\OptionsResolver\Options;
@ -94,6 +101,7 @@ method:
)); ));
} }
} }
```

View File

@ -5,6 +5,7 @@ Process executes commands in sub-processes.
In this example, we run a simple directory listing and get the result back: In this example, we run a simple directory listing and get the result back:
```php
use Symfony\Component\Process\Process; use Symfony\Component\Process\Process;
$process = new Process('ls -lsa'); $process = new Process('ls -lsa');
@ -15,6 +16,7 @@ In this example, we run a simple directory listing and get the result back:
} }
print $process->getOutput(); print $process->getOutput();
```
You can think that this is easy to achieve with plain PHP but it's not especially You can think that this is easy to achieve with plain PHP but it's not especially
if you want to take care of the subtle differences between the different platforms. if you want to take care of the subtle differences between the different platforms.
@ -23,6 +25,7 @@ And if you want to be able to get some feedback in real-time, just pass an
anonymous function to the ``run()`` method and you will get the output buffer anonymous function to the ``run()`` method and you will get the output buffer
as it becomes available: as it becomes available:
```php
use Symfony\Component\Process\Process; use Symfony\Component\Process\Process;
$process = new Process('ls -lsa'); $process = new Process('ls -lsa');
@ -33,6 +36,7 @@ as it becomes available:
echo 'OUT > '.$buffer; echo 'OUT > '.$buffer;
} }
}); });
```
That's great if you want to execute a long running command (like rsync-ing files to a That's great if you want to execute a long running command (like rsync-ing files to a
remote server) and give feedback to the user in real-time. remote server) and give feedback to the user in real-time.

View File

@ -16,17 +16,21 @@ CHANGELOG
Before: Before:
``` ```yaml
article_edit: article_edit:
pattern: /article/{id} pattern: /article/{id}
requirements: { '_method': 'POST|PUT', '_scheme': 'https', 'id': '\d+' } requirements: { '_method': 'POST|PUT', '_scheme': 'https', 'id': '\d+' }
```
```xml
<route id="article_edit" pattern="/article/{id}"> <route id="article_edit" pattern="/article/{id}">
<requirement key="_method">POST|PUT</requirement> <requirement key="_method">POST|PUT</requirement>
<requirement key="_scheme">https</requirement> <requirement key="_scheme">https</requirement>
<requirement key="id">\d+</requirement> <requirement key="id">\d+</requirement>
</route> </route>
```
```php
$route = new Route(); $route = new Route();
$route->setPattern('/article/{id}'); $route->setPattern('/article/{id}');
$route->setRequirement('_method', 'POST|PUT'); $route->setRequirement('_method', 'POST|PUT');
@ -35,17 +39,21 @@ CHANGELOG
After: After:
``` ```yaml
article_edit: article_edit:
path: /article/{id} path: /article/{id}
methods: [POST, PUT] methods: [POST, PUT]
schemes: https schemes: https
requirements: { 'id': '\d+' } requirements: { 'id': '\d+' }
```
```xml
<route id="article_edit" pattern="/article/{id}" methods="POST PUT" schemes="https"> <route id="article_edit" pattern="/article/{id}" methods="POST PUT" schemes="https">
<requirement key="id">\d+</requirement> <requirement key="id">\d+</requirement>
</route> </route>
```
```php
$route = new Route(); $route = new Route();
$route->setPath('/article/{id}'); $route->setPath('/article/{id}');
$route->setMethods(array('POST', 'PUT')); $route->setMethods(array('POST', 'PUT'));
@ -59,7 +67,7 @@ CHANGELOG
Before: Before:
``` ```php
$rootCollection = new RouteCollection(); $rootCollection = new RouteCollection();
$subCollection = new RouteCollection(); $subCollection = new RouteCollection();
$rootCollection->addCollection($subCollection); $rootCollection->addCollection($subCollection);
@ -68,7 +76,7 @@ CHANGELOG
After: After:
``` ```php
$rootCollection = new RouteCollection(); $rootCollection = new RouteCollection();
$subCollection = new RouteCollection(); $subCollection = new RouteCollection();
$subCollection->add('foo', new Route('/foo')); $subCollection->add('foo', new Route('/foo'));
@ -78,8 +86,8 @@ CHANGELOG
Also one must call `addCollection` from the bottom to the top hierarchy. Also one must call `addCollection` from the bottom to the top hierarchy.
So the correct sequence is the following (and not the reverse): So the correct sequence is the following (and not the reverse):
``` ```php
$childCollection->->addCollection($grandchildCollection); $childCollection->addCollection($grandchildCollection);
$rootCollection->addCollection($childCollection); $rootCollection->addCollection($childCollection);
``` ```
@ -105,7 +113,7 @@ CHANGELOG
use-case instead. use-case instead.
Before: `$parentCollection->addCollection($collection, '/prefix', array(...), array(...))` Before: `$parentCollection->addCollection($collection, '/prefix', array(...), array(...))`
After: After:
``` ```php
$collection->addPrefix('/prefix', array(...), array(...)); $collection->addPrefix('/prefix', array(...), array(...));
$parentCollection->addCollection($collection); $parentCollection->addCollection($collection);
``` ```

View File

@ -6,6 +6,7 @@ Routing associates a request with the code that will convert it to a response.
The example below demonstrates how you can set up a fully working routing The example below demonstrates how you can set up a fully working routing
system: system:
```php
use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Matcher\UrlMatcher; use Symfony\Component\Routing\Matcher\UrlMatcher;
use Symfony\Component\Routing\RequestContext; use Symfony\Component\Routing\RequestContext;
@ -23,6 +24,7 @@ system:
$matcher = new UrlMatcher($routes, $context); $matcher = new UrlMatcher($routes, $context);
$parameters = $matcher->match('/hello'); $parameters = $matcher->match('/hello');
```
Resources Resources
--------- ---------

View File

@ -4,6 +4,7 @@ Translation Component
Translation provides tools for loading translation files and generating Translation provides tools for loading translation files and generating
translated strings from these including support for pluralization. translated strings from these including support for pluralization.
```php
use Symfony\Component\Translation\Translator; use Symfony\Component\Translation\Translator;
use Symfony\Component\Translation\MessageSelector; use Symfony\Component\Translation\MessageSelector;
use Symfony\Component\Translation\Loader\ArrayLoader; use Symfony\Component\Translation\Loader\ArrayLoader;
@ -16,6 +17,7 @@ translated strings from these including support for pluralization.
), 'fr'); ), 'fr');
echo $translator->trans('Hello World!')."\n"; echo $translator->trans('Hello World!')."\n";
```
Resources Resources
--------- ---------

View File

@ -12,12 +12,14 @@ The component provides "validation constraints", which are simple objects
containing the rules for the validation. Let's validate a simple string containing the rules for the validation. Let's validate a simple string
as an example: as an example:
```php
use Symfony\Component\Validator\Validation; use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Constraints\Length; use Symfony\Component\Validator\Constraints\Length;
$validator = Validation::createValidator(); $validator = Validation::createValidator();
$violations = $validator->validateValue('Bernhard', new Length(array('min' => 10))); $violations = $validator->validateValue('Bernhard', new Length(array('min' => 10)));
```
This validation will fail because the given string is shorter than ten This validation will fail because the given string is shorter than ten
characters. The precise errors, here called "constraint violations", are characters. The precise errors, here called "constraint violations", are
@ -26,6 +28,7 @@ If the violation list is empty, validation succeeded.
Validation of arrays is possible using the `Collection` constraint: Validation of arrays is possible using the `Collection` constraint:
```php
use Symfony\Component\Validator\Validation; use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Constraints as Assert; use Symfony\Component\Validator\Constraints as Assert;
@ -44,6 +47,7 @@ Validation of arrays is possible using the `Collection` constraint:
)); ));
$violations = $validator->validateValue($input, $constraint); $violations = $validator->validateValue($input, $constraint);
```
Again, the validator returns the list of violations. Again, the validator returns the list of violations.
@ -52,6 +56,7 @@ a mapping you can put constraints onto properties and objects of classes.
Whenever an object of this class is validated, its properties and Whenever an object of this class is validated, its properties and
method results are matched against the constraints. method results are matched against the constraints.
```php
use Symfony\Component\Validator\Validation; use Symfony\Component\Validator\Validation;
use Symfony\Component\Validator\Constraints as Assert; use Symfony\Component\Validator\Constraints as Assert;
@ -91,6 +96,7 @@ method results are matched against the constraints.
$user = new User('John Doe', 'john@example.com'); $user = new User('John Doe', 'john@example.com');
$violations = $validator->validate($user); $violations = $validator->validate($user);
```
This example uses the annotation support of Doctrine Common to This example uses the annotation support of Doctrine Common to
map constraints to properties and methods. You can also map constraints map constraints to properties and methods. You can also map constraints

View File

@ -3,11 +3,13 @@ Yaml Component
YAML implements most of the YAML 1.2 specification. YAML implements most of the YAML 1.2 specification.
```php
use Symfony\Component\Yaml\Yaml; use Symfony\Component\Yaml\Yaml;
$array = Yaml::parse($file); $array = Yaml::parse($file);
print Yaml::dump($array); print Yaml::dump($array);
```
Resources Resources
--------- ---------