Skip to content

[Form] Replace passing type instances by class names #5321

@webmozart

Description

@webmozart

This ticket is a follow-up to #5221.

Currently, it is a common practice to use form types by instantiating them directly instead of registering them in the DIC:

<?php

// (1) creating forms
$form = $this->createForm(new MyFormType());

// (2) adding fields
$builder->add('field', new MyFieldType());

// (3) declaring parent types
public function getParent()
{
    return new MyParentType();
}

This practice has a series of advantages:

  • Easy and rapid coding, no extra configuration needed.
  • Support for IDE auto-completion.

But it also has limitations:

  • If (1), (2) or (3) occurs multiple times during the same request (e.g. within a collection form), caching is impossible and degrades performance. Removing this performance impact means adding the affected types to the DIC and rewriting all code that uses them.
  • (3) cannot inject dependencies into the parent type.
  • (2) does not make use of type extensions.

Because of these inconsistencies, I suggest to deprecate this API and replace it by the following:

<?php

// (1) creating forms
$form = $this->createForm('Vendor\Bundle\Form\MyFormType');
$form = $this->createForm('VendorBundle:MyFormType');
$form = $this->createForm(MyFormType::class); // PHP 5.5

// (2) adding fields
$builder->add('field', 'Vendor\Bundle\Form\MyFieldType');
$builder->add('field', 'VendorBundle:MyFieldType');
$builder->add('field', MyFieldType::class); // PHP 5.5

// (3) declaring parent types
public function getParent()
{
    return 'Vendor\Bundle\Form\MyParentType';
}
public function getParent()
{
    return 'VendorBundle:MyParentType';
}
public function getParent()
{
    return MyParentType::class; // PHP 5.5
}

The advantages of this approach are:

  • Support for class names and registered types is identical. No difference in performance, support for type extensions etc.
  • Easy and rapid coding, no extra configuration needed.

The downsides:

  • No IDE support until PHP 5.5 [1] (except if IDEs add special treatment for form types).
  • Types that receive arguments in their constructors must be registered in the DIC.

[1] assuming that https://wiki.php.net/rfc/class_name_scalars gets accepted

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy