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

Redirect Bundle Laravel Package

awaresoft/redirect-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require awaresoft/redirect-bundle
    

    Note: Due to symlinking requirements, follow the README's local setup guide if modifying the bundle.

  2. Enable the Bundle: Add to config/bundles.php:

    return [
        // ...
        Awaresoft\RedirectBundle\AwaresoftRedirectBundle::class => ['all' => true],
    ];
    
  3. Database Migration: Run Doctrine migrations to create the redirect table:

    php bin/console doctrine:migrations:diff
    php bin/console doctrine:migrations:migrate
    
  4. First Redirect: Use the RedirectManager service in a controller:

    use Awaresoft\RedirectBundle\Manager\RedirectManager;
    
    class MyController extends AbstractController {
        public function redirectAction(RedirectManager $redirectManager) {
            $redirect = $redirectManager->createRedirect(
                '/old-path',
                '/new-path',
                301 // HTTP status code
            );
            $redirectManager->save($redirect);
            return $this->redirect('/new-path');
        }
    }
    

Implementation Patterns

Core Workflows

  1. Creating Redirects:

    • Programmatic: Use RedirectManager to create and persist redirects.
      $redirect = $redirectManager->createRedirect(
          '/old-url',
          '/new-url',
          301,
          ['domain' => 'example.com'] // Optional: domain-specific redirects
      );
      $redirectManager->save($redirect);
      
    • Admin Panel: Build a CRUD interface using Symfony’s make:crud or manually with forms tied to the Redirect entity.
  2. Handling Redirects:

    • Event Listener: Subscribe to kernel.request to auto-redirect old URLs:
      use Awaresoft\RedirectBundle\Event\RedirectEvent;
      use Symfony\Component\HttpKernel\Event\RequestEvent;
      use Symfony\Component\HttpKernel\KernelEvents;
      
      class RedirectListener {
          public function onKernelRequest(RequestEvent $event) {
              $dispatcher = $event->getRequest()->get('redirect_dispatcher');
              $dispatcher->dispatch($event->getRequest());
          }
      }
      
      Register in services.yaml:
      services:
          App\EventListener\RedirectListener:
              tags:
                  - { name: kernel.event_listener, event: kernel.request, method: onKernelRequest }
      
  3. Batch Processing:

    • Use Doctrine’s EntityManager to bulk-insert redirects:
      $redirects = [];
      foreach ($oldUrls as $oldUrl) {
          $redirects[] = $redirectManager->createRedirect($oldUrl, $newUrl, 301);
      }
      $entityManager->persist($redirects);
      $entityManager->flush();
      
  4. Domain-Specific Redirects:

    • Filter redirects by domain in queries:
      $redirects = $redirectManager->findBy(['domain' => 'example.com']);
      

Integration Tips

  1. Symfony Forms: Create a form type for the Redirect entity:

    namespace App\Form;
    
    use Awaresoft\RedirectBundle\Entity\Redirect;
    use Symfony\Component\Form\AbstractType;
    use Symfony\Component\Form\FormBuilderInterface;
    
    class RedirectType extends AbstractType {
        public function buildForm(FormBuilderInterface $builder, array $options) {
            $builder
                ->add('oldPath', TextType::class)
                ->add('newPath', TextType::class)
                ->add('statusCode', IntegerType::class, ['data' => 301])
                ->add('domain', TextType::class, ['required' => false]);
        }
    }
    
  2. API Endpoints: Expose redirects as JSON for frontend use:

    use Symfony\Component\HttpFoundation\JsonResponse;
    
    public function getRedirectsAction(RedirectManager $redirectManager) {
        $redirects = $redirectManager->findAll();
        return new JsonResponse(array_map(function($r) {
            return [
                'oldPath' => $r->getOldPath(),
                'newPath' => $r->getNewPath(),
                'statusCode' => $r->getStatusCode(),
            ];
        }, $redirects));
    }
    
  3. Caching: Cache redirect lookups to reduce database hits:

    # config/packages/cache.yaml
    framework:
        cache:
            app.redirects:
                provider: 'doctrine'
    

    Then use CacheInterface in your listener:

    $cache->get('redirects', function() use ($redirectManager) {
        return $redirectManager->findAll();
    });
    

Gotchas and Tips

Pitfalls

  1. Symlinking Requirements:

    • Issue: Forgetting to symlink /src/Awaresoft or remove Composer’s autoload entry breaks the bundle.
    • Fix: Follow the README’s modification guide precisely. Use:
      php bin/console cache:clear
      
      after symlinking.
  2. Backward Compatibility:

    • Issue: The bundle enforces strict BC rules. Modifying entities or methods may break dependent projects.
    • Fix: Test changes in a sandbox project first. Use git tag to version changes correctly (e.g., 1.0.1 for hotfixes).
  3. Domain Handling:

    • Issue: Redirects without a domain field may not work as expected in multi-domain setups.
    • Fix: Always specify a domain or use null for root-level redirects:
      $redirectManager->createRedirect('/old', '/new', 301, ['domain' => null]);
      
  4. Performance:

    • Issue: Large redirect tables slow down findBy() queries.
    • Fix: Add indexes to the old_path and domain columns in your migration:
      // src/Migrations/VersionYYYYMMDDHHMMSS.php
      public function up(Schema $schema) {
          $table = $schema->getTable('redirect');
          $table->addIndex(['old_path'], 'IDX_REDIRECT_OLD_PATH');
          $table->addIndex(['domain'], 'IDX_REDIRECT_DOMAIN');
      }
      
  5. HTTP Status Codes:

    • Issue: Using 302 (temporary) instead of 301 (permanent) for SEO-critical redirects.
    • Fix: Default to 301 unless temporary redirects are explicitly needed.

Debugging

  1. Missing Redirects:

    • Check: Verify the RedirectListener is registered and the redirect_dispatcher service is injected.
    • Debug: Add logging in the listener:
      $this->logger->debug('Dispatching redirects for: ' . $request->getUri());
      
  2. Symlink Issues:

    • Check: Run composer dump-autoload after symlinking.
    • Debug: Verify the autoload file (vendor/composer/autoload_psr4.php) includes:
      'Awaresoft\\' => __DIR__ . '/../src/Awaresoft',
      
  3. Database Errors:

    • Check: Ensure the redirect table exists and matches the entity schema. Run:
      php bin/console doctrine:schema:validate
      

Extension Points

  1. Custom Redirect Logic:

    • Extend the RedirectManager to add validation or preprocessing:
      class CustomRedirectManager extends RedirectManager {
          public function createRedirect($oldPath, $newPath, $statusCode = 301, array $options = []) {
              if (strpos($oldPath, 'admin/') === 0) {
                  throw new \RuntimeException('Cannot redirect admin paths');
              }
              return parent::createRedirect($oldPath, $newPath, $statusCode, $options);
          }
      }
      
      Override the service in services.yaml:
      services:
          Awaresoft\RedirectBundle\Manager\RedirectManager: '@App\Manager\CustomRedirectManager'
      
  2. Event Dispatching:

    • Listen for redirect.pre_save and redirect.post_save events to add custom logic:
      services:
          App\EventSubscriber\RedirectSubscriber:
              tags:
                  - { name: kernel.event_subscriber }
      
      use Awaresoft\RedirectBundle\Event\RedirectEvents;
      use Symfony\Component\EventDispatcher\EventSubscriberInterface;
      
      class RedirectSubscriber implements EventSubscriberInterface {
          public static function getSubscribedEvents() {
              return [
                  RedirectEvents::PRE_SAVE => 'onPreSave',
                  RedirectEvents::POST_SAVE => 'onPostSave',
              ];
          }
      
          public function on
      
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.
comsave/common
alecsammon/php-raml-parser
chrome-php/wrench
lendable/composer-license-checker
typhoon/reflection
mesilov/moneyphp-percentage
mike42/gfx-php
bookdown/themes
aura/view
aura/html
aura/cli
povils/phpmnd
nayjest/manipulator
omnipay/tests
psr-mock/http-message-implementation
psr-mock/http-factory-implementation
psr-mock/http-client-implementation
voku/email-check
voku/urlify
rtheunissen/guzzle-log-middleware