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

Code Snippets Laravel Package

permafrost-dev/code-snippets

Laravel package for organizing and sharing reusable code snippets. Store, tag, search, and quickly insert common patterns and helpers into your projects to speed up development and keep teams consistent across applications.

Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require permafrost-dev/code-snippets
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="Permafrost\CodeSnippets\CodeSnippetsServiceProvider"
    
  2. Basic Usage Register a snippet via a service provider or in a config file:

    // config/snippets.php
    'snippets' => [
        'greeting' => [
            'description' => 'A simple greeting snippet',
            'code' => '<?php echo "Hello, {name}!"; ?>',
            'tags' => ['php', 'template'],
        ],
    ],
    
  3. First Use Case Retrieve and render a snippet in a Blade view:

    use Permafrost\CodeSnippets\Facades\CodeSnippets;
    
    $snippet = CodeSnippets::get('greeting');
    echo $snippet->render(['name' => 'John']);
    

Implementation Patterns

Workflows

  1. Dynamic Snippet Management

    • Use the CodeSnippets::add() method to register snippets programmatically:
      CodeSnippets::add('dynamic_snippet', [
          'code' => '<?php echo "Dynamic: {value}"; ?>',
          'tags' => ['dynamic'],
      ]);
      
  2. Blade Directives Create custom Blade directives for seamless snippet integration:

    // In a service provider
    Blade::directive('snippet', function ($expression) {
        return "<?php echo Permafrost\CodeSnippets\Facades\CodeSnippets::get({$expression})->render(); ?>";
    });
    

    Usage in Blade:

    @snippet('greeting', ['name' => 'Alice'])
    
  3. Tag-Based Filtering Fetch snippets by tags for modular organization:

    $phpSnippets = CodeSnippets::getByTags(['php']);
    
  4. Snippet Caching Cache snippets for performance (e.g., in a controller):

    $snippet = Cache::remember("snippet_{$key}", now()->addHours(1), function () use ($key) {
        return CodeSnippets::get($key);
    });
    

Integration Tips

  • Laravel Mix/Webpack: Use snippets to generate reusable JS/PHP templates.
  • API Responses: Return snippets as part of API responses for dynamic content.
  • Testing: Mock snippets in tests:
    CodeSnippets::shouldReceive('get')->andReturn(new MockSnippet());
    

Gotchas and Tips

Pitfalls

  1. Variable Injection Risks Avoid injecting untrusted user input directly into snippet placeholders. Sanitize or escape variables:

    $safeName = htmlspecialchars($userInput);
    echo $snippet->render(['name' => $safeName]);
    
  2. Config Overrides Ensure config values in config/snippets.php don’t conflict with environment-specific settings. Use .env overrides if needed:

    SNIPPETS_CACHE_DRIVER=redis
    
  3. Namespace Collisions If using custom snippet classes, ensure they don’t conflict with Laravel’s core classes. Prefix namespaces (e.g., App\Snippets\).

  4. Dynamic Snippet Persistence Programmatically added snippets (CodeSnippets::add()) are lost on cache refresh. Use a database or file storage for persistence:

    // Example: Store in database
    $snippet = new Snippet();
    $snippet->key = 'dynamic_snippet';
    $snippet->code = '<?php echo "Stored: {value}"; ?>';
    $snippet->save();
    

Debugging

  • Missing Snippets: Verify the snippet key exists in config/snippets.php or was added programmatically.
  • Render Errors: Check for syntax errors in snippet code using:
    try {
        $snippet->render();
    } catch (\Exception $e) {
        Log::error("Snippet render error: " . $e->getMessage());
    }
    
  • Tag Filtering Issues: Ensure tags are strings and match case-sensitively:
    // Correct:
    CodeSnippets::getByTags(['PHP']); // Matches 'php' tag if case-insensitive
    

Extension Points

  1. Custom Snippet Storage Override the default storage (array/config) by binding a custom SnippetRepository:

    $this->app->bind(\Permafrost\CodeSnippets\Contracts\SnippetRepository::class, CustomSnippetRepository::class);
    
  2. Snippet Events Listen for snippet-related events (e.g., snippet.rendering):

    event(new SnippetRendering($snippet, $data));
    
  3. Syntax Highlighting Extend the package to support syntax highlighting for snippets in admin panels:

    $snippet->highlight(); // Hypothetical method
    
  4. Localization Add language support by extending the Snippet class:

    class LocalizedSnippet extends Snippet {
        public function __construct(array $attributes, string $locale = 'en') {
            // ...
        }
    }
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport