Comment réutiliser du code avec des bundles symfony 5? Partie 2. Nous sortons le code dans le bundle

Parlons de la façon d'arrêter le copier-coller entre les projets et de transférer le code dans un bundle de plug-ins réutilisable Symfony 5. Une série d'articles résumant mon expérience avec les bundles permettra en pratique de créer un bundle minimal et de refactoriser une application de démonstration en tests et en cycle de publication de bundle.


Dans l' article précédent, nous avons créé un ensemble minimal de deux fichiers et l'avons inclus dans le projet.


Dans cet article:


  • Portage du code vers le bundle
  • Injection de dépendances: enregistrement de services groupés dans un conteneur DI
  • Migration des contrôleurs et configuration du routage
  • Mécanisme de détermination du chemin d'accès aux ressources
  • Transfert de modèles vers des bundles

Contenu de la série

Si vous ne terminez pas le didacticiel de manière séquentielle, téléchargez l'application à partir du référentiel et passez à la branche 1-bundle-mockup .


Instructions pour installer et démarrer le projet dans un fichier README.md.


Vous trouverez la version finale du code de cet article dans la branche 2-basic-refactoring .


Passons à la refactorisation.


Nous déplaçons les fichiers principaux


Un bundle peut contenir tout de même que les applications Symfony classiques: entités, contrôleurs et commandes, modèles, actifs, tests et tout autre code.

, , 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. ,


All Articles