Hablemos sobre cómo detener el copiar y pegar entre proyectos y transferir el código a un paquete de plug-in reutilizable Symfony 5. Una serie de artículos que resumen mi experiencia con los paquetes se llevarán a cabo en la práctica desde la creación de un paquete mínimo y la refactorización de una aplicación de demostración para las pruebas y el ciclo de lanzamiento del paquete.
En el artículo anterior, creamos un paquete mínimo de dos archivos y lo incluimos en el proyecto.
En este articulo:
- Código de portabilidad para agrupar
 - Inyección de dependencia: registro de servicios de paquete en un contenedor DI
 - Migración de controladores y configuración de enrutamiento
 - Mecanismo de determinación de ruta de recursos
 - Transferencia de plantillas a paquetes
 
Si no está completando el tutorial secuencialmente, descargue la aplicación desde el repositorio y cambie a la rama 1-bundle-mockup .
Instrucciones para instalar e iniciar el proyecto en un archivo README.md.
Encontrará la versión final del código para este artículo en la rama 2-basic-refactoring .
Pasemos a refactorizar.
Movemos los archivos principales
Un paquete puede contener lo mismo que las aplicaciones regulares de Symfony: entidades, controladores y comandos, plantillas, activos, pruebas y cualquier otro código.
, , bundles/CalendarBundle/src ( ):
# Crate dirs
cd bundles/CalendarBundle/src/
mkdir Controller Entity Service
cd ../../../src
# Move files
mv Form Repository ../bundles/CalendarBundle/src/
mv Controller/EditorController.php Controller/EventController.php ../bundles/CalendarBundle/src/Controller
mv Entity/Event.php ../bundles/CalendarBundle/src/Entity
mv Service/EventExporter ../bundles/CalendarBundle/src/Service/EventExporter
mv Twig ../bundles/CalendarBundle/src/Twig

, . namespace use App\ bravik\CalendarBundle\.
App\: .
IDE .
IDE PhpStorm Ctrl/Cmd + Shift + R.
use App\Repository\EventRepository SiteController

.
:

SiteController : EventRepository. autowiring Symfony typehints DI-.
src/Services , .
Dependency Injection
, DI- , .
, .
, Symfony- services.yaml, DI-.
src config/services.yaml:
parameters:
    #     
services:
    #         
    _defaults:
        #      
        #     typehints   (  )
        # https://symfony.com/doc/current/service_container.html#the-autowire-option
        autowire: true
        #   :
        #       
        # https://symfony.com/doc/current/service_container.html#the-autoconfigure-option
        autoconfigure: true 
    #       DI-
    bravik\CalendarBundle\Repository\EventRepository: ~
    bravik\CalendarBundle\Controller\EventController: ~
    bravik\CalendarBundle\Controller\EditorController: ~
3 .
- config/services.yaml , .
@todo :
#  Twig   
bravik\CalendarBundle\Twig\TwigRuDateFilter: ~
#     EventExporter  DI-
bravik\CalendarBundle\Service\EventExporter\:
    resource: '../src/Service/EventExporter/*'
#  ExporterProvider   DI-
#    2   
bravik\CalendarBundle\Service\EventExporter\ExporterManager:
    arguments:
        $exporters:
            - '@bravik\CalendarBundle\Service\EventExporter\Exporters\GoogleCalendarExporter'
            - '@bravik\CalendarBundle\Service\EventExporter\Exporters\ICalendarExporter'
, , . , . src DependencyInjection/CalendarExtension.php:
<?php
namespace bravik\CalendarBundle\DependencyInjection;
use Exception;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\Extension;
class CalendarExtension extends Extension
{
    public function load(array $configs, ContainerBuilder $container)
    {
    }
}
. <BundleName>Extension, src/DependencyInjection Symfony\Component\DependencyInjection\Extension\Extension.
Symfony DI-, Extension-. , Extension::load() .
, . , PHP-. .
services.yaml :
public function load(array $configs, ContainerBuilder $container)
{
    $loader = new YamlFileLoader(
        $container,
        new FileLocator(__DIR__.'/../../config')
    );
    $loader->load('services.yaml');
}
, :

.
Symfony :
config/routes.yaml              #   
config/routes/annotations.yaml  #   ,
                                #    
. annotations.yaml:
controllers:                          #  
    type: annotation                  #   
    resource: ../../src/Controller/   #   ,  
: config/routes.yaml.
calendar_routes:
    type: annotation
    resource: '../src/Controller/'
config/routes/annotations.yaml.
:
calendar_bundle:
    resource: '@CalendarBundle/config/routes.yaml'
.
@CalendarBundle — .
Symfony .
, /admin - : /admin ?
, :
calendar_bundle:
    resource: '@CalendarBundle/config/routes.yaml'
    prefix:   /admin
    name_prefix: cms.
security . , .
, Symfony vendor_name_. .
, Twig «» .
:
@<BundleName>Bundle/path/to/config —@<BundleName>/path/to/template — .
Symfony « ». . .
./src. , Symfony 4 src/Resources. 4 Symfony , — . , .
CalendarBundle getPath():
public function getPath(): string
{
    return dirname(__DIR__);
}
@CalendarBundle .
, !

? .
. , , -.
templates templates/event :
mkdir bundles/CalendarBundle/templates
mv templates/event/* bundles/CalendarBundle/templates
— , . .
«  » IDE . event/ @Calendar/.

@Calendar Twig , namespace Twig. templates , Symfony namespace, templates Resources/views ( ).
site/index.html.twig twig-. :

, — .
: base.html.twig -:
{% extends 'base.html.twig' %}
.
, , DI-. Example Project 2-basic-refactoring.
-  , —   namespace   .       
App - , — Extension-.     DI-     . ,   .
 -   .   .   .
 -   ,    ,  ..,   «»  ,   .      .
 
, JS -.
:
1.
2.
3. : , , JS
4.
5.
6. ,
7. ,