Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Legacy Bridge Bundle Laravel Package

basster/legacy-bridge-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:
    composer require basster/legacy-bridge-bundle
    
  2. Enable Bundle in config/bundles.php:
    return [
        // ...
        Basster\LegacyBridgeBundle\BassterLegacyBridgeBundle::class => ['all' => true],
    ];
    
  3. Configure Legacy Path in config/packages/basster_legacy_bridge.yaml:
    basster_legacy_bridge:
        legacy_path: '%kernel.project_dir%/legacy'  # Path to your legacy PHP files
        legacy_namespace: 'Legacy\\'               # Optional: Namespace prefix for legacy files
    
  4. First Use Case: Place a legacy PHP file (e.g., legacy/old-script.php) in the configured path. Access it via Symfony’s front controller:
    http://your-app.dev/old-script.php
    
    The bundle auto-generates a route for it.

Key First Steps

  • Verify Auto-Routing: Check bin/console debug:router for generated legacy routes.
  • Access Symfony Container: In legacy code, use:
    $container = $_SERVER['SYMFONY_CONTAINER'] ?? null;
    if ($container) {
        $service = $container->get('some_symfony_service');
    }
    
  • Test Legacy Logic: Ensure legacy scripts work as-is before refactoring.

Implementation Patterns

Workflow: Gradual Refactoring

  1. Expose Legacy as Routes:

    • Drop legacy files into legacy_path (e.g., legacy/auth/login.php).
    • Access via Symfony routes (e.g., /auth/login.php).
    • Tip: Use legacy_namespace to group related legacy files (e.g., Legacy\Auth\Login).
  2. Inject Symfony Services:

    • Modify legacy code to use $_SERVER['SYMFONY_CONTAINER']:
      $userService = $_SERVER['SYMFONY_CONTAINER']->get('app.user_service');
      
    • Pattern: Wrap legacy logic in a Symfony service, then call it from both legacy and modern code.
  3. URL Generation:

    • Use Symfony’s UrlGenerator in legacy templates:
      $url = $_SERVER['SYMFONY_CONTAINER']->get('router')->generate('modern_route_name');
      
  4. Shared Dependencies:

    • Create a hybrid service that bridges legacy and Symfony:
      # config/services.yaml
      services:
          App\Service\LegacyUserBridge:
              arguments:
                  $legacyUserClass: '%legacy_namespace%User'
                  $symfonyContainer: '@service_container'
      
  5. Asset Handling:

    • Serve legacy assets (CSS/JS) via Symfony’s assets component:
      $assetUrl = $_SERVER['SYMFONY_CONTAINER']->get('assets')->getUrl('legacy/css/style.css');
      

Integration Tips

  • Routing Overrides: Customize legacy routes in config/routes.yaml:
    legacy_routes:
        resource: "@BassterLegacyBridgeBundle/Resources/config/routing/legacy.xml"
        prefix: "/legacy"
    
  • Middleware: Apply Symfony middleware to legacy requests via kernel.request event listeners.
  • Testing: Test legacy routes with Symfony’s WebTestCase:
    $client = static::createClient();
    $client->request('GET', '/legacy/old-script.php');
    $this->assertEquals(200, $client->getResponse()->getStatusCode());
    

Gotchas and Tips

Pitfalls

  1. Case Sensitivity:

    • Legacy routes are case-sensitive. Ensure filenames match the requested URL exactly (e.g., old-script.phpOld-Script.php).
  2. Global State Pollution:

    • Legacy code may rely on global state (e.g., $_SESSION, register_globals). Isolate it by:
      • Using Symfony’s RequestStack for session access.
      • Avoiding global keywords in legacy files.
  3. Performance Overhead:

    • Auto-routing adds minimal overhead, but avoid deep legacy paths (e.g., legacy/deep/nested/script.php). Use legacy_namespace to organize.
  4. Container Unavailability:

    • Legacy scripts run without the container if:
      • The route doesn’t exist (check legacy_path).
      • Symfony’s kernel isn’t bootstrapped (ensure SYMFONY_CONTAINER is set in $_SERVER).
  5. Caching Issues:

    • Clear Symfony’s cache (php bin/console cache:clear) after adding/removing legacy files to update routes.

Debugging Tips

  • Route Not Found:
    • Verify the file exists at legacy_path/filename.php.
    • Check bin/console debug:router | grep legacy for generated routes.
  • Container Not Injected:
    • Add this to legacy files to debug:
      error_log(print_r($_SERVER, true)); // Check for 'SYMFONY_CONTAINER'
      
  • Symfony vs. Legacy Conflicts:
    • Use basster_legacy_bridge.debug config to log legacy route generation:
      basster_legacy_bridge:
          debug: true
      

Extension Points

  1. Custom Route Loading: Override the route loader in a custom bundle:

    // src/BassterLegacyBridgeBundle/DependencyInjection/Compiler/LegacyRoutePass.php
    public function process(ContainerBuilder $container) {
        $definition = $container->findDefinition('basster_legacy_bridge.route_loader');
        $definition->addMethodCall('setCustomLoader', [[$this, 'loadCustomRoutes']]);
    }
    
  2. Pre/Post-Processing: Hook into kernel.request to modify legacy requests/responses:

    // src/EventListener/LegacyRequestListener.php
    public function onKernelRequest(GetResponseEvent $event) {
        $request = $event->getRequest();
        if ($request->attributes->get('_legacy_route')) {
            // Modify legacy request (e.g., add headers, rewrite paths)
        }
    }
    
  3. Legacy Service Proxy: Create a proxy service to wrap legacy functions:

    // src/Service/LegacyUserProxy.php
    class LegacyUserProxy {
        public function __construct(private ContainerInterface $container) {}
    
        public function getUser() {
            return $_SERVER['SYMFONY_CONTAINER']->get('legacy.user_service')->fetch();
        }
    }
    

Config Quirks

  • Legacy Path Traversal: Avoid symlinks or relative paths in legacy_path—use absolute paths to prevent security risks.
  • Namespace Collisions: If legacy_namespace conflicts with existing classes, use fully qualified paths:
    legacy_namespace: '\Legacy\\'
    
  • Environment-Specific Paths: Use %kernel.environment% in legacy_path for environment-specific legacy directories:
    legacy_path: '%kernel.project_dir%/legacy_%kernel.environment%'
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
milito/query-filter
apiboxsym/user-bundle
apiboxsym/health-check-bundle
jayeshmepani/jpl-moshier-ephemeris-php
elnasnato/laraliveui
labrodev/rest-sdk
sampaui/sampaui
babelqueue/php-sdk
facebook/capi-param-builder-php
babelqueue/symfony
hamzi/corewatch
minionfactory/raw-hydrator
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours