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

Static Entity Bundle Laravel Package

byscripts/static-entity-bundle

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Steps

  1. Installation:

    composer require byscripts/static-entity-bundle:~4.0
    

    For Symfony 4, add the bundle to config/bundles.php:

    return [
        // ...
        Byscripts\Bundle\StaticEntityBundle\ByscriptsStaticEntityBundle::class => ['all' => true],
    ];
    
  2. Define a Static Entity: Create a class extending Byscripts\StaticEntity\StaticEntity (e.g., src/Entity/Static/Country.php):

    namespace App\Entity\Static;
    
    use Byscripts\StaticEntity\StaticEntity;
    
    class Country extends StaticEntity
    {
        public static function getDataSet()
        {
            return [
                'US' => ['name' => 'United States', 'code' => 'USA'],
                'CA' => ['name' => 'Canada', 'code' => 'CAN'],
            ];
        }
    }
    
  3. First Use Case: Use the entity in a controller with ParamConverter (Symfony 3/4):

    use Sensio\Bundle\FrameworkExtraBundle\Configuration\ParamConverter;
    use App\Entity\Static\Country;
    
    class CountryController extends AbstractController
    {
        /**
         * @ParamConverter("country", converter="static_entity")
         */
        public function show(Country $country)
        {
            return $this->render('country/show.html.twig', ['country' => $country]);
        }
    }
    

Implementation Patterns

ParamConverter Integration

  • Route-based resolution: Use @ParamConverter to auto-resolve static entities from route parameters (e.g., /country/{code}). Example:

    # config/routes.yaml
    country_show:
        path: /country/{code}
        controller: App\Controller\CountryController::show
    
  • Custom converter configuration: Override the default converter in config/services.yaml:

    services:
        App\Converter\StaticEntityConverter:
            tags:
                - { name: 'controller.service_arguments' }
            arguments:
                - '@static_entity.converter'
    

FormType Integration

  • Create a FormType: Extend Byscripts\StaticEntityBundle\Form\Type\StaticEntityType:

    namespace App\Form\Type;
    
    use App\Entity\Static\Country;
    use Byscripts\StaticEntityBundle\Form\Type\StaticEntityType;
    
    class CountryType extends StaticEntityType
    {
        public function __construct()
        {
            parent::__construct(Country::class);
        }
    }
    
  • Use in a Form:

    use App\Form\Type\CountryType;
    use Symfony\Component\Form\Extension\Core\Type\FormType;
    
    class CountryFormBuilder
    {
        public function buildForm()
        {
            return FormType::createBuilder()
                ->add('country', CountryType::class)
                ->getForm();
        }
    }
    

Workflows

  1. Validation: Static entities support Symfony’s validator constraints (e.g., @Assert\Choice):

    use Symfony\Component\Validator\Constraints as Assert;
    
    class Country
    {
        /**
         * @Assert\Choice(callback="getDataSet")
         */
        private $code;
    }
    
  2. Dynamic DataSets: Load datasets from external sources (e.g., API, database) in getDataSet():

    public static function getDataSet()
    {
        return Cache::remember('static_countries', 3600, function() {
            return $this->fetchFromExternalSource();
        });
    }
    
  3. Translation: Localize static entity values via Symfony’s translation system:

    public static function getDataSet()
    {
        return [
            'US' => ['name' => 'app.country.us', 'code' => 'USA'],
        ];
    }
    

    Translations in translations/messages.en.yaml:

    app.country.us: "United States"
    

Gotchas and Tips

Pitfalls

  1. Bundle Compatibility:

    • The ~4.0 branch supports Symfony 3/4 only. For Symfony 2.x, use branches 3.x or 1.x.
    • If using Symfony 5+, consider alternatives like api-platform/core for static data.
  2. ParamConverter Misconfiguration:

    • Ensure the converter is registered as a service. If using Symfony 4, verify ByscriptsStaticEntityBundle is enabled in bundles.php.
    • Debug with:
      php bin/console debug:container static_entity.converter
      
  3. Caching Issues:

    • Static datasets are cached by default. Clear cache after modifying getDataSet():
      php bin/console cache:clear
      
  4. FormType Overrides:

    • If extending StaticEntityType, ensure the parent constructor is called with the correct entity class:
      parent::__construct(Country::class); // Not nullable!
      

Debugging

  • Dump Dataset: Temporarily add this to getDataSet() to verify data:

    var_dump(self::getDataSet()); die;
    
  • Converter Errors: Check for StaticEntityNotFoundException if the route parameter doesn’t match any dataset key.

Tips

  1. Reuse Static Entities: Share static entities across bundles by placing them in a shared namespace (e.g., App\Shared\Entity\Static).

  2. Performance: For large datasets, lazy-load values in getDataSet():

    public static function getDataSet()
    {
        static $dataset;
        if (!$dataset) {
            $dataset = require __DIR__.'/dataset.php'; // Load once
        }
        return $dataset;
    }
    
  3. Testing: Mock static entities in PHPUnit:

    $this->getMockBuilder(Country::class)
        ->disableOriginalConstructor()
        ->setMethods(['getDataSet'])
        ->getMock();
    
  4. Extension Points:

    • Override StaticEntity to add custom logic (e.g., validation, serialization).
    • Extend the converter to support additional data sources (e.g., Doctrine repositories).
  5. Symfony 4 Autowiring: Enable autowiring for StaticEntityType in config/services.yaml:

    services:
        _defaults:
            autowire: true
            autoconfigure: true
    
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