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

Phpmorphy Laravel Package

nqxcode/phpmorphy

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require nqxcode/phpmorphy
    

    Add to composer.json if not auto-loaded:

    "autoload": {
        "psr-4": {
            "App\\": "app/",
            "Nqxcode\\PhpMorphy\\": "vendor/nqxcode/phpmorphy/src/"
        }
    }
    

    Run composer dump-autoload.

  2. First Use Case: Initialize the morpher in a service or controller:

    use Nqxcode\PhpMorphy\PhpMorphy;
    
    $morpher = new PhpMorphy();
    $morpher->loadDictionary('path/to/dictionary'); // e.g., 'ru_RU' for Russian
    
  3. Basic Morphing:

    $word = $morpher->inflect('бегу', 'nomn'); // Converts to nominative case
    $plural = $morpher->inflect('дом', 'plur'); // Converts to plural
    

Implementation Patterns

Common Workflows

  1. Case Conversion:

    $morpher->inflect('собака', 'genm'); // 'собаки' (genitive)
    $morpher->inflect('собаки', 'nomn'); // 'собака' (nominative)
    
  2. Number Agreement:

    $morpher->inflect('яблоко', 'plur'); // 'яблоки' (plural)
    $morpher->inflect('яблоки', 'sing'); // 'яблоко' (singular)
    
  3. Gender Handling:

    $morpher->inflect('красивый', 'femn'); // 'красивая' (feminine)
    
  4. Integration with Laravel:

    • Service Provider:
      // app/Providers/PhpMorphyServiceProvider.php
      public function register()
      {
          $this->app->singleton('morpher', function () {
              $morpher = new PhpMorphy();
              $morpher->loadDictionary(config('morphy.dictionary'));
              return $morpher;
          });
      }
      
    • Config:
      // config/morphy.php
      return [
          'dictionary' => 'ru_RU',
      ];
      
  5. Batch Processing:

    $words = ['дом', 'собака', 'яблоко'];
    $inflected = array_map(function ($word) use ($morpher) {
        return $morpher->inflect($word, 'genm');
    }, $words);
    
  6. Validation Rules:

    // app/Rules/ValidRussianWord.php
    public function passes($attribute, $value)
    {
        $morpher = app('morpher');
        return $morpher->checkWord($value); // Checks if word exists in dictionary
    }
    

Gotchas and Tips

Pitfalls

  1. Dictionary Loading:

    • The package requires a pre-downloaded dictionary (e.g., ru_RU for Russian). Ensure the path is correct:
      $morpher->loadDictionary(base_path('dictionaries/ru_RU'));
      
    • Default dictionaries are not included in the package. Download them from phpmorphy sources.
  2. Case Sensitivity:

    • Input words must match the dictionary's case. For robustness, normalize input:
      $normalized = mb_strtolower($word, 'UTF-8');
      $morpher->inflect($normalized, 'nomn');
      
  3. Performance:

    • Dictionary loading is memory-intensive. Cache the PhpMorphy instance in Laravel's container or a singleton:
      $morpher = app('morpher'); // Reuse instance
      
  4. Unsupported Languages:

    • The package is primarily designed for Russian. Testing with other languages may yield unexpected results.
  5. Deprecated Methods:

    • Avoid PhpMorphy::getDictionary() if the package evolves. Use loadDictionary() for explicit control.

Debugging Tips

  1. Check Word Existence:

    if (!$morpher->checkWord('несуществующее')) {
        Log::warning('Word not found in dictionary: несуществующее');
    }
    
  2. Log Inflection Results:

    $result = $morpher->inflect('бег', 'nomn');
    Log::debug("Inflected 'бег' to '$result'");
    
  3. Handle Exceptions: Wrap usage in try-catch for edge cases:

    try {
        $inflected = $morpher->inflect($word, $grammemes);
    } catch (\Exception $e) {
        Log::error("Morphy error: " . $e->getMessage());
        return $word; // Fallback
    }
    

Extension Points

  1. Custom Grammemes: Extend the package by adding new grammeme rules (requires modifying the source or forking the repo).

  2. Laravel Facade: Create a facade for cleaner syntax:

    // app/Facades/PhpMorphy.php
    public static function inflect($word, $grammemes)
    {
        return app('morpher')->inflect($word, $grammemes);
    }
    

    Usage:

    PhpMorphy::inflect('дом', 'genm'); // 'дома'
    
  3. Event Listeners: Trigger events for inflection results (e.g., log or analyze changes):

    // app/Listeners/LogInflection.php
    public function handle($event)
    {
        Log::info("Inflected {$event->original} to {$event->inflected}");
    }
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity